@antseed/payments 0.1.9 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/web/assets/{add-CJkKK-SD.js → add-DocZPFAh.js} +1 -1
- package/dist/web/assets/{all-wallets-DmmDKWXL.js → all-wallets-BlmuWikl.js} +1 -1
- package/dist/web/assets/{app-store-Cre-E76Q.js → app-store-BOAtptal.js} +1 -1
- package/dist/web/assets/{apple-fIYVe0nN.js → apple-BVuGLQFf.js} +1 -1
- package/dist/web/assets/{arrow-bottom-Kopfs0-6.js → arrow-bottom-BfI_b_jU.js} +1 -1
- package/dist/web/assets/{arrow-bottom-circle-CU4k9b1A.js → arrow-bottom-circle-DXAZqR32.js} +1 -1
- package/dist/web/assets/{arrow-left-mr_ppX-p.js → arrow-left-D1QxsP5J.js} +1 -1
- package/dist/web/assets/{arrow-right-Bew01fau.js → arrow-right-B2aeprYS.js} +1 -1
- package/dist/web/assets/{arrow-top-CWfN1JL4.js → arrow-top-Dj0c55Fu.js} +1 -1
- package/dist/web/assets/{bank-CnNBH9bM.js → bank-Ds7QEe7p.js} +1 -1
- package/dist/web/assets/{basic-Clt2HmdF.js → basic-BMBwjKA8.js} +1 -1
- package/dist/web/assets/{browser-CD04A-NT.js → browser-BdmnWXof.js} +1 -1
- package/dist/web/assets/{card-CJM_iy90.js → card-C4Xu9wgL.js} +1 -1
- package/dist/web/assets/{ccip-CKdZm34I.js → ccip-B3uez93r.js} +1 -1
- package/dist/web/assets/{checkmark-BbXaH9ID.js → checkmark-BTF_TSmM.js} +1 -1
- package/dist/web/assets/{checkmark-bold-BMGtfUFs.js → checkmark-bold-u4pkEwJ7.js} +1 -1
- package/dist/web/assets/{chevron-bottom-5MjQrLUT.js → chevron-bottom-DUco1ORe.js} +1 -1
- package/dist/web/assets/{chevron-left-CEc38pDh.js → chevron-left-CiceTJIx.js} +1 -1
- package/dist/web/assets/{chevron-right-Clz7SByW.js → chevron-right-8Kfq0LM-.js} +1 -1
- package/dist/web/assets/{chevron-top-Do-Tj7of.js → chevron-top-CkE3raQU.js} +1 -1
- package/dist/web/assets/{chrome-store-DQtQ1vua.js → chrome-store-DgInc3Qf.js} +1 -1
- package/dist/web/assets/{clock-d29J4dye.js → clock-C0990J2j.js} +1 -1
- package/dist/web/assets/{close-BEoxynua.js → close-CHgHmpCY.js} +1 -1
- package/dist/web/assets/{coinPlaceholder-Dbovho4Y.js → coinPlaceholder-CSA6iapt.js} +1 -1
- package/dist/web/assets/{compass-Jl9uCsST.js → compass-DpaKQ2he.js} +1 -1
- package/dist/web/assets/{copy-BoAj4ZuP.js → copy-BaiECgly.js} +1 -1
- package/dist/web/assets/{core-Y_nUy5Fn.js → core-JRXsheka.js} +4 -4
- package/dist/web/assets/{cursor-CM_vmDSC.js → cursor-BZ6UxGan.js} +1 -1
- package/dist/web/assets/{cursor-transparent-D8Tmp0LW.js → cursor-transparent-Dcts1MI8.js} +1 -1
- package/dist/web/assets/{desktop-BI2Ia2fz.js → desktop-CfwszHBZ.js} +1 -1
- package/dist/web/assets/{disconnect-DPH7Jjp0.js → disconnect-DmImDVvy.js} +1 -1
- package/dist/web/assets/{discord-x48Wn-MS.js → discord-OLpEWZAC.js} +1 -1
- package/dist/web/assets/{etherscan-BNMLqc8R.js → etherscan-C07_6eky.js} +1 -1
- package/dist/web/assets/{exclamation-triangle-dcElk2KT.js → exclamation-triangle-BiswlrqT.js} +1 -1
- package/dist/web/assets/{extension-BQz-eCpL.js → extension-UwLquuzI.js} +1 -1
- package/dist/web/assets/{external-link-BklYjLeX.js → external-link-CSLm_-tJ.js} +1 -1
- package/dist/web/assets/{facebook-C3ydwYyK.js → facebook-BRCrfpVw.js} +1 -1
- package/dist/web/assets/{farcaster-4pVv__F4.js → farcaster-Bf9m2Otr.js} +1 -1
- package/dist/web/assets/{filters-0dm0tHTh.js → filters-DehzOxU1.js} +1 -1
- package/dist/web/assets/{github-y8SC70EN.js → github-hAkxsgoS.js} +1 -1
- package/dist/web/assets/{google-CEw94p-R.js → google-B3N5JDat.js} +1 -1
- package/dist/web/assets/{help-circle-DwS8Gd7c.js → help-circle-CNgVImeX.js} +1 -1
- package/dist/web/assets/{id-WThjNvqR.js → id-pw2EMpwA.js} +1 -1
- package/dist/web/assets/{image-D_J0HQaH.js → image-Cxyq8Cui.js} +1 -1
- package/dist/web/assets/{index-BPyq3E9X.js → index-Bft26p4H.js} +3 -3
- package/dist/web/assets/{index-Bj1D5yqj.js → index-DdCqo2iD.js} +1 -1
- package/dist/web/assets/{index-Cd4qk887.js → index-VjSCsmQ_.js} +1 -1
- package/dist/web/assets/{index--x5LBI1k.js → index-XFberJbs.js} +19 -19
- package/dist/web/assets/{index-D-gkn3Z7.js → index-j0nG5kdO.js} +1 -1
- package/dist/web/assets/{index.es-CozOSkF8.js → index.es-CgpmFgU-.js} +4 -4
- package/dist/web/assets/{info-DDgvkphb.js → info-CfJxZZH4.js} +1 -1
- package/dist/web/assets/{info-circle-R85HV4vQ.js → info-circle-UGz8nwSA.js} +1 -1
- package/dist/web/assets/{lightbulb-AmzwVGD2.js → lightbulb-1gMiuscj.js} +1 -1
- package/dist/web/assets/{mail-D6vwUtxV.js → mail-jUjUUbN_.js} +1 -1
- package/dist/web/assets/{metamask-sdk-CgdOvgfU.js → metamask-sdk-CbS0jbL-.js} +1 -1
- package/dist/web/assets/{mobile-CuiOjkej.js → mobile-Dt9xWNxt.js} +1 -1
- package/dist/web/assets/{more-C5kqzlsB.js → more-sXoh0fak.js} +1 -1
- package/dist/web/assets/{network-placeholder-CsDpNmF-.js → network-placeholder-Ci2QoxkE.js} +1 -1
- package/dist/web/assets/{nftPlaceholder-B_B8e6i8.js → nftPlaceholder-B9NpVZeo.js} +1 -1
- package/dist/web/assets/{off-BakrSbup.js → off-BTwuO7ia.js} +1 -1
- package/dist/web/assets/{play-store-D2FX6axg.js → play-store-C6pls6Vy.js} +1 -1
- package/dist/web/assets/{plus-Ca02XglK.js → plus-ClaLJgZu.js} +1 -1
- package/dist/web/assets/{qr-code-DnPY8dAb.js → qr-code-Kt3GafiB.js} +1 -1
- package/dist/web/assets/{recycle-horizontal-D-nFecBP.js → recycle-horizontal-abN1vhMK.js} +1 -1
- package/dist/web/assets/{refresh-DpLU2XUn.js → refresh-CVq5AhHc.js} +1 -1
- package/dist/web/assets/{reown-logo-C0p7srz7.js → reown-logo-St5b0D6C.js} +1 -1
- package/dist/web/assets/{search-BosdPcrh.js → search-Chk95Ojw.js} +1 -1
- package/dist/web/assets/{secp256k1-B6g4RAG-.js → secp256k1-BmewtLue.js} +1 -1
- package/dist/web/assets/{secp256k1-X3b68sLa.js → secp256k1-vayZNtsf.js} +1 -1
- package/dist/web/assets/{send-DBBzFiIw.js → send-Ck2m5AoO.js} +1 -1
- package/dist/web/assets/{swapHorizontal-DYjnmMgk.js → swapHorizontal-BPsXrF3L.js} +1 -1
- package/dist/web/assets/{swapHorizontalBold-D4wOaWgo.js → swapHorizontalBold-Dmm0fWxo.js} +1 -1
- package/dist/web/assets/{swapHorizontalMedium-BGfz50Nk.js → swapHorizontalMedium-C-h0SSuc.js} +1 -1
- package/dist/web/assets/{swapHorizontalRoundedBold-zeuk_21p.js → swapHorizontalRoundedBold-DusMAoQQ.js} +1 -1
- package/dist/web/assets/{swapVertical-Ce-am00s.js → swapVertical-CoqVXTTE.js} +1 -1
- package/dist/web/assets/{telegram-ClqjQUtA.js → telegram-BHBphLJM.js} +1 -1
- package/dist/web/assets/{three-dots-BN2pKe7K.js → three-dots-DVuU7rRQ.js} +1 -1
- package/dist/web/assets/{twitch-VFIf-UDA.js → twitch-D6KnDIGR.js} +1 -1
- package/dist/web/assets/{twitterIcon-GNHl_V1F.js → twitterIcon-Du8R03S8.js} +1 -1
- package/dist/web/assets/{verify-DCB_tvgl.js → verify-CKhkA-i9.js} +1 -1
- package/dist/web/assets/{verify-filled-BwL88TIA.js → verify-filled-CyZqNOkT.js} +1 -1
- package/dist/web/assets/{w3m-modal-BKlMwJuK.js → w3m-modal-BYx8cjX-.js} +1 -1
- package/dist/web/assets/{wallet-DOJfqp22.js → wallet-Das1gtZW.js} +1 -1
- package/dist/web/assets/{wallet-placeholder-Ex2CkkBE.js → wallet-placeholder-NXcPvC7U.js} +1 -1
- package/dist/web/assets/{walletconnect-aYOhjP81.js → walletconnect-DTAM9xN9.js} +1 -1
- package/dist/web/assets/{warning-circle-BOVfgnt-.js → warning-circle-B7irzO2l.js} +1 -1
- package/dist/web/assets/{x-Cnb5UoDo.js → x-zHzJxpDt.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-
|
|
2
|
-
import{n as Io,r as rl,_ as il,m as vt}from"./index
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-BmewtLue.js","assets/index-XFberJbs.js","assets/index-vhd6ZTWQ.css","assets/events-DQ172AOg.js","assets/core-JRXsheka.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{n as Io,r as rl,_ as il,m as vt}from"./index-XFberJbs.js";import{r as jd}from"./events-DQ172AOg.js";function dr(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function sl(r,e){let t;const i=()=>{if(t)return t;const s=indexedDB.open(r);return s.onupgradeneeded=()=>s.result.createObjectStore(e),t=dr(s),t.then(n=>{n.onclose=()=>t=void 0},()=>{}),t};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Hs;function xi(){return Hs||(Hs=sl("keyval-store","keyval")),Hs}function ea(r,e=xi()){return e("readonly",t=>dr(t.get(r)))}function Bd(r,e,t=xi()){return t("readwrite",i=>(i.put(e,r),dr(i.transaction)))}function Ud(r,e=xi()){return e("readwrite",t=>(t.delete(r),dr(t.transaction)))}function Fd(r=xi()){return r("readwrite",e=>(e.clear(),dr(e.transaction)))}function qd(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},dr(r.transaction)}function Ld(r=xi()){return r("readonly",e=>{if(e.getAllKeys)return dr(e.getAllKeys());const t=[];return qd(e,i=>t.push(i.key)).then(()=>t)})}var Ye=jd();const So=Io(Ye);var ta=function(r,e,t){if(t||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return r.concat(n||Array.prototype.slice.call(e))},kd=(function(){function r(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"}return r})(),Md=(function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r})(),zd=(function(){function r(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"}return r})(),Hd=(function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r})(),Vd=(function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r})(),Kd=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Wd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,ra=3,Gd=[["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",Kd]],ia=[["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 Yd(r){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Vd:typeof navigator<"u"?Zd(navigator.userAgent):Xd()}function Jd(r){return r!==""&&Gd.reduce(function(e,t){var i=t[0],s=t[1];if(e)return e;var n=s.exec(r);return!!n&&[i,n]},!1)}function Zd(r){var e=Jd(r);if(!e)return null;var t=e[0],i=e[1];if(t==="searchbot")return new Hd;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<ra&&(s=ta(ta([],s,!0),ep(ra-s.length),!0)):s=[];var n=s.join("."),o=Qd(r),a=Wd.exec(r);return a&&a[1]?new zd(t,n,o,a[1]):new kd(t,n,o)}function Qd(r){for(var e=0,t=ia.length;e<t;e++){var i=ia[e],s=i[0],n=i[1],o=n.exec(r);if(o)return s}return null}function Xd(){var r=typeof process<"u"&&process.version;return r?new Md(process.version.slice(1)):null}function ep(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var Vs={};/*! *****************************************************************************
|
|
3
3
|
Copyright (c) Microsoft Corporation.
|
|
4
4
|
|
|
5
5
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -13,7 +13,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
|
13
13
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
14
|
PERFORMANCE OF THIS SOFTWARE.
|
|
15
15
|
***************************************************************************** */var Rn=function(r,e){return Rn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])},Rn(r,e)};function tp(r,e){Rn(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Nn=function(){return Nn=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++){t=arguments[i];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},Nn.apply(this,arguments)};function rp(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(r);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(r,i[s])&&(t[i[s]]=r[i[s]]);return t}function ip(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(n=(s<3?o(n):s>3?o(e,t,n):o(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}function sp(r,e){return function(t,i){e(t,i,r)}}function np(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function op(r,e,t,i){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):s(l.value).then(a,c)}u((i=i.apply(r,e||[])).next())})}function ap(r,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,s=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){t.label=u[1];break}if(u[0]===6&&t.label<n[1]){t.label=n[1],n=u;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(u);break}n[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(l){u=[6,l],s=0}finally{i=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function cp(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function up(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function jn(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function nl(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return n}function lp(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(nl(arguments[e]));return r}function hp(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),s=0,e=0;e<t;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function _i(r){return this instanceof _i?(this.v=r,this):new _i(r)}function dp(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(p){return new Promise(function(f,g){n.push([d,p,f,g])>1||a(d,p)})})}function a(d,p){try{c(i[d](p))}catch(f){h(n[0][3],f)}}function c(d){d.value instanceof _i?Promise.resolve(d.value.v).then(u,l):h(n[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function pp(r){var e,t;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=r[s]?function(o){return(t=!t)?{value:_i(r[s](o)),done:s==="return"}:n?n(o):o}:n}}function fp(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof jn=="function"?jn(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=r[n]&&function(o){return new Promise(function(a,c){o=r[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function gp(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function yp(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function mp(r){return r&&r.__esModule?r:{default:r}}function wp(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function bp(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const vp=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Nn},__asyncDelegator:pp,__asyncGenerator:dp,__asyncValues:fp,__await:_i,__awaiter:op,__classPrivateFieldGet:wp,__classPrivateFieldSet:bp,__createBinding:cp,__decorate:ip,__exportStar:up,__extends:tp,__generator:ap,__importDefault:mp,__importStar:yp,__makeTemplateObject:gp,__metadata:np,__param:sp,__read:nl,__rest:rp,__spread:lp,__spreadArrays:hp,__values:jn},Symbol.toStringTag,{value:"Module"})),Ss=rl(vp);var Ks={},ri={},sa;function Ep(){if(sa)return ri;sa=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.delay=void 0;function r(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}return ri.delay=r,ri}var Gt={},Ws={},Yt={},na;function _p(){return na||(na=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.ONE_THOUSAND=Yt.ONE_HUNDRED=void 0,Yt.ONE_HUNDRED=100,Yt.ONE_THOUSAND=1e3),Yt}var Gs={},oa;function Ip(){return oa||(oa=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.ONE_YEAR=r.FOUR_WEEKS=r.THREE_WEEKS=r.TWO_WEEKS=r.ONE_WEEK=r.THIRTY_DAYS=r.SEVEN_DAYS=r.FIVE_DAYS=r.THREE_DAYS=r.ONE_DAY=r.TWENTY_FOUR_HOURS=r.TWELVE_HOURS=r.SIX_HOURS=r.THREE_HOURS=r.ONE_HOUR=r.SIXTY_MINUTES=r.THIRTY_MINUTES=r.TEN_MINUTES=r.FIVE_MINUTES=r.ONE_MINUTE=r.SIXTY_SECONDS=r.THIRTY_SECONDS=r.TEN_SECONDS=r.FIVE_SECONDS=r.ONE_SECOND=void 0,r.ONE_SECOND=1,r.FIVE_SECONDS=5,r.TEN_SECONDS=10,r.THIRTY_SECONDS=30,r.SIXTY_SECONDS=60,r.ONE_MINUTE=r.SIXTY_SECONDS,r.FIVE_MINUTES=r.ONE_MINUTE*5,r.TEN_MINUTES=r.ONE_MINUTE*10,r.THIRTY_MINUTES=r.ONE_MINUTE*30,r.SIXTY_MINUTES=r.ONE_MINUTE*60,r.ONE_HOUR=r.SIXTY_MINUTES,r.THREE_HOURS=r.ONE_HOUR*3,r.SIX_HOURS=r.ONE_HOUR*6,r.TWELVE_HOURS=r.ONE_HOUR*12,r.TWENTY_FOUR_HOURS=r.ONE_HOUR*24,r.ONE_DAY=r.TWENTY_FOUR_HOURS,r.THREE_DAYS=r.ONE_DAY*3,r.FIVE_DAYS=r.ONE_DAY*5,r.SEVEN_DAYS=r.ONE_DAY*7,r.THIRTY_DAYS=r.ONE_DAY*30,r.ONE_WEEK=r.SEVEN_DAYS,r.TWO_WEEKS=r.ONE_WEEK*2,r.THREE_WEEKS=r.ONE_WEEK*3,r.FOUR_WEEKS=r.ONE_WEEK*4,r.ONE_YEAR=r.ONE_DAY*365})(Gs)),Gs}var aa;function ol(){return aa||(aa=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Ss;e.__exportStar(_p(),r),e.__exportStar(Ip(),r)})(Ws)),Ws}var ca;function Sp(){if(ca)return Gt;ca=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.fromMiliseconds=Gt.toMiliseconds=void 0;const r=ol();function e(i){return i*r.ONE_THOUSAND}Gt.toMiliseconds=e;function t(i){return Math.floor(i/r.ONE_THOUSAND)}return Gt.fromMiliseconds=t,Gt}var ua;function Dp(){return ua||(ua=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Ss;e.__exportStar(Ep(),r),e.__exportStar(Sp(),r)})(Ks)),Ks}var wr={},la;function Op(){if(la)return wr;la=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){const i=this.get(t);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);const s=Date.now()-i.started;this.timestamps.set(t,{started:i.started,elapsed:s})}get(t){const i=this.timestamps.get(t);if(typeof i>"u")throw new Error(`No timestamp found for label: ${t}`);return i}elapsed(t){const i=this.get(t);return i.elapsed||Date.now()-i.started}}return wr.Watch=r,wr.default=r,wr}var Ys={},ii={},ha;function Pp(){if(ha)return ii;ha=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.IWatch=void 0;class r{}return ii.IWatch=r,ii}var da;function $p(){return da||(da=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0}),Ss.__exportStar(Pp(),r)})(Ys)),Ys}var pa;function Ap(){return pa||(pa=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Ss;e.__exportStar(Dp(),r),e.__exportStar(Op(),r),e.__exportStar($p(),r),e.__exportStar(ol(),r)})(Vs)),Vs}var U=Ap(),re={},fa;function al(){if(fa)return re;fa=1,Object.defineProperty(re,"__esModule",{value:!0}),re.getLocalStorage=re.getLocalStorageOrThrow=re.getCrypto=re.getCryptoOrThrow=re.getLocation=re.getLocationOrThrow=re.getNavigator=re.getNavigatorOrThrow=re.getDocument=re.getDocumentOrThrow=re.getFromWindowOrThrow=re.getFromWindow=void 0;function r(d){let p;return typeof window<"u"&&typeof window[d]<"u"&&(p=window[d]),p}re.getFromWindow=r;function e(d){const p=r(d);if(!p)throw new Error(`${d} is not defined in Window`);return p}re.getFromWindowOrThrow=e;function t(){return e("document")}re.getDocumentOrThrow=t;function i(){return r("document")}re.getDocument=i;function s(){return e("navigator")}re.getNavigatorOrThrow=s;function n(){return r("navigator")}re.getNavigator=n;function o(){return e("location")}re.getLocationOrThrow=o;function a(){return r("location")}re.getLocation=a;function c(){return e("crypto")}re.getCryptoOrThrow=c;function u(){return r("crypto")}re.getCrypto=u;function l(){return e("localStorage")}re.getLocalStorageOrThrow=l;function h(){return r("localStorage")}return re.getLocalStorage=h,re}var jt=al(),si={},ga;function xp(){if(ga)return si;ga=1,Object.defineProperty(si,"__esModule",{value:!0}),si.getWindowMetadata=void 0;const r=al();function e(){let t,i;try{t=r.getDocumentOrThrow(),i=r.getLocationOrThrow()}catch{return null}function s(){const p=t.getElementsByTagName("link"),f=[];for(let g=0;g<p.length;g++){const w=p[g],E=w.getAttribute("rel");if(E&&E.toLowerCase().indexOf("icon")>-1){const b=w.getAttribute("href");if(b)if(b.toLowerCase().indexOf("https:")===-1&&b.toLowerCase().indexOf("http:")===-1&&b.indexOf("//")!==0){let _=i.protocol+"//"+i.host;if(b.indexOf("/")===0)_+=b;else{const A=i.pathname.split("/");A.pop();const T=A.join("/");_+=T+"/"+b}f.push(_)}else if(b.indexOf("//")===0){const _=i.protocol+b;f.push(_)}else f.push(b)}}return f}function n(...p){const f=t.getElementsByTagName("meta");for(let g=0;g<f.length;g++){const w=f[g],E=["itemprop","property","name"].map(b=>w.getAttribute(b)).filter(b=>b?p.includes(b):!1);if(E.length&&E){const b=w.getAttribute("content");if(b)return b}}return""}function o(){let p=n("name","og:site_name","og:title","twitter:title");return p||(p=t.title),p}function a(){return n("description","og:description","twitter:description","keywords")}const c=o(),u=a(),l=i.origin,h=s();return{description:u,url:l,icons:h,name:c}}return si.getWindowMetadata=e,si}var Cp=xp();function Ii(r,{strict:e=!0}={}){return!r||typeof r!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(r):r.startsWith("0x")}function ya(r){return Ii(r,{strict:!1})?Math.ceil((r.length-2)/2):r.length}const cl="2.23.2";let ni={getDocsUrl:({docsBaseUrl:r,docsPath:e="",docsSlug:t})=>e?`${r??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${cl}`};class ar extends Error{constructor(e,t={}){var a;const i=(()=>{var c;return t.cause instanceof ar?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),s=t.cause instanceof ar&&t.cause.docsPath||t.docsPath,n=(a=ni.getDocsUrl)==null?void 0:a.call(ni,{...t,docsPath:s}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...ni.version?[`Version: ${ni.version}`]:[]].join(`
|
|
16
|
-
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=s,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=cl}walk(e){return ul(this,e)}}function ul(r,e){return e!=null&&e(r)?r:r&&typeof r=="object"&&"cause"in r&&r.cause!==void 0?ul(r.cause,e):e?null:r}class ll extends ar{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Yr(r,{dir:e,size:t=32}={}){return typeof r=="string"?Tp(r,{dir:e,size:t}):Rp(r,{dir:e,size:t})}function Tp(r,{dir:e,size:t=32}={}){if(t===null)return r;const i=r.replace("0x","");if(i.length>t*2)throw new ll({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Rp(r,{dir:e,size:t=32}={}){if(t===null)return r;if(r.length>t)throw new ll({size:r.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let s=0;s<t;s++){const n=e==="right";i[n?s:t-s-1]=r[n?s:r.length-s-1]}return i}class Np extends ar{constructor({max:e,min:t,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class jp extends ar{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Jr(r,{size:e}){if(ya(r)>e)throw new jp({givenSize:ya(r),maxSize:e})}function Bn(r,e={}){const{signed:t}=e;e.size&&Jr(r,{size:e.size});const i=BigInt(r);if(!t)return i;const s=(r.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function Bp(r,e={}){return Number(Bn(r,e))}const Up=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Un(r,e={}){return typeof r=="number"||typeof r=="bigint"?dl(r,e):typeof r=="string"?Lp(r,e):typeof r=="boolean"?Fp(r,e):hl(r,e)}function Fp(r,e={}){const t=`0x${Number(r)}`;return typeof e.size=="number"?(Jr(t,{size:e.size}),Yr(t,{size:e.size})):t}function hl(r,e={}){let t="";for(let s=0;s<r.length;s++)t+=Up[r[s]];const i=`0x${t}`;return typeof e.size=="number"?(Jr(i,{size:e.size}),Yr(i,{dir:"right",size:e.size})):i}function dl(r,e={}){const{signed:t,size:i}=e,s=BigInt(r);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof r=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&s>n||s<o){const c=typeof r=="bigint"?"n":"";throw new Np({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${r}${c}`})}const a=`0x${(t&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?Yr(a,{size:i}):a}const qp=new TextEncoder;function Lp(r,e={}){const t=qp.encode(r);return hl(t,e)}const kp=new TextEncoder;function Mp(r,e={}){return typeof r=="number"||typeof r=="bigint"?Hp(r,e):typeof r=="boolean"?zp(r,e):Ii(r)?pl(r,e):fl(r,e)}function zp(r,e={}){const t=new Uint8Array(1);return t[0]=Number(r),typeof e.size=="number"?(Jr(t,{size:e.size}),Yr(t,{size:e.size})):t}const St={zero:48,nine:57,A:65,F:70,a:97,f:102};function ma(r){if(r>=St.zero&&r<=St.nine)return r-St.zero;if(r>=St.A&&r<=St.F)return r-(St.A-10);if(r>=St.a&&r<=St.f)return r-(St.a-10)}function pl(r,e={}){let t=r;e.size&&(Jr(t,{size:e.size}),t=Yr(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=ma(i.charCodeAt(a++)),u=ma(i.charCodeAt(a++));if(c===void 0||u===void 0)throw new ar(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+u}return n}function Hp(r,e){const t=dl(r,e);return pl(t)}function fl(r,e={}){const t=kp.encode(r);return typeof e.size=="number"?(Jr(t,{size:e.size}),Yr(t,{dir:"right",size:e.size})):t}function ds(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Vp(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ds(r,...e){if(!Vp(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function EP(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ds(r.outputLen),ds(r.blockLen)}function wa(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Kp(r,e){Ds(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Mi=BigInt(2**32-1),ba=BigInt(32);function Wp(r,e=!1){return e?{h:Number(r&Mi),l:Number(r>>ba&Mi)}:{h:Number(r>>ba&Mi)|0,l:Number(r&Mi)|0}}function Gp(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Wp(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Yp=(r,e,t)=>r<<t|e>>>32-t,Jp=(r,e,t)=>e<<t|r>>>32-t,Zp=(r,e,t)=>e<<t-32|r>>>64-t,Qp=(r,e,t)=>r<<t-32|e>>>64-t,br=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Xp(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function _P(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function IP(r,e){return r<<32-e|r>>>e}const va=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ef(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Ea(r){for(let e=0;e<r.length;e++)r[e]=ef(r[e])}function tf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function gl(r){return typeof r=="string"&&(r=tf(r)),Ds(r),r}function SP(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Ds(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}class rf{clone(){return this._cloneInto()}}function sf(r){const e=i=>r().update(gl(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function DP(r=32){if(br&&typeof br.getRandomValues=="function")return br.getRandomValues(new Uint8Array(r));if(br&&typeof br.randomBytes=="function")return br.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}const yl=[],ml=[],wl=[],nf=BigInt(0),oi=BigInt(1),of=BigInt(2),af=BigInt(7),cf=BigInt(256),uf=BigInt(113);for(let r=0,e=oi,t=1,i=0;r<24;r++){[t,i]=[i,(2*t+3*i)%5],yl.push(2*(5*i+t)),ml.push((r+1)*(r+2)/2%64);let s=nf;for(let n=0;n<7;n++)e=(e<<oi^(e>>af)*uf)%cf,e&of&&(s^=oi<<(oi<<BigInt(n))-oi);wl.push(s)}const[lf,hf]=Gp(wl,!0),_a=(r,e,t)=>t>32?Zp(r,e,t):Yp(r,e,t),Ia=(r,e,t)=>t>32?Qp(r,e,t):Jp(r,e,t);function df(r,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],l=t[c+1],h=_a(u,l,1)^t[a],d=Ia(u,l,1)^t[a+1];for(let p=0;p<50;p+=10)r[o+p]^=h,r[o+p+1]^=d}let s=r[2],n=r[3];for(let o=0;o<24;o++){const a=ml[o],c=_a(s,n,a),u=Ia(s,n,a),l=yl[o];s=r[l],n=r[l+1],r[l]=c,r[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}r[0]^=lf[i],r[1]^=hf[i]}t.fill(0)}class Do extends rf{constructor(e,t,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ds(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Xp(this.state)}keccak(){va||Ea(this.state32),df(this.state32,this.rounds),va||Ea(this.state32),this.posOut=0,this.pos=0}update(e){wa(this);const{blockLen:t,state:i}=this;e=gl(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(t-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,(t&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){wa(this,!1),Ds(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(t.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ds(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Kp(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Do(t,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const pf=(r,e,t)=>sf(()=>new Do(e,r,t)),ff=pf(1,136,256/8);function bl(r,e){const t=e||"hex",i=ff(Ii(r,{strict:!1})?Mp(r):r);return t==="bytes"?i:Un(i)}class gf extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Js=new gf(8192);function yf(r,e){if(Js.has(`${r}.${e}`))return Js.get(`${r}.${e}`);const t=r.substring(2).toLowerCase(),i=bl(fl(t),"bytes"),s=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return Js.set(`${r}.${e}`,n),n}function mf(r){const e=bl(`0x${r.substring(4)}`).substring(26);return yf(`0x${e}`)}async function wf({hash:r,signature:e}){const t=Ii(r)?r:Un(r),{secp256k1:i}=await il(async()=>{const{secp256k1:o}=await import("./secp256k1-B6g4RAG-.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:d}=e,p=Number(d??h),f=Sa(p);return new i.Signature(Bn(u),Bn(l)).addRecoveryBit(f)}const o=Ii(e)?e:Un(e),a=Bp(`0x${o.slice(130)}`),c=Sa(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Sa(r){if(r===0||r===1)return r;if(r===27)return 0;if(r===28)return 1;throw new Error("Invalid yParityOrV value")}async function bf({hash:r,signature:e}){return mf(await wf({hash:r,signature:e}))}function vf(r){if(r.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<r.length;u++){const l=r.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const t=r.length,i=r.charAt(0),s=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,d=0;const p=u.length;for(;d!==p&&u[d]===0;)d++,l++;const f=(p-d)*n+1>>>0,g=new Uint8Array(f);for(;d!==p;){let b=u[d],_=0;for(let A=f-1;(b!==0||_<h)&&A!==-1;A--,_++)b+=256*g[A]>>>0,g[A]=b%t>>>0,b=b/t>>>0;if(b!==0)throw new Error("Non-zero carry");h=_,d++}let w=f-h;for(;w!==f&&g[w]===0;)w++;let E=i.repeat(l);for(;w<f;++w)E+=r.charAt(g[w]);return E}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,d=0;for(;u[l]===i;)h++,l++;const p=(u.length-l)*s+1>>>0,f=new Uint8Array(p);for(;l<u.length;){const b=u.charCodeAt(l);if(b>255)return;let _=e[b];if(_===255)return;let A=0;for(let T=p-1;(_!==0||A<d)&&T!==-1;T--,A++)_+=t*f[T]>>>0,f[T]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");d=A,l++}let g=p-d;for(;g!==p&&f[g]===0;)g++;const w=new Uint8Array(h+(p-g));let E=h;for(;g!==p;)w[E++]=f[g++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Ef="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const _f=vf(Ef),If=r=>JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),Sf=r=>{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,t=r.replace(e,'$1"$2n"$3');return JSON.parse(t,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function cr(r){if(typeof r!="string")throw new Error(`Cannot safe json parse value of type ${typeof r}`);try{return Sf(r)}catch{return r}}function Bt(r){return typeof r=="string"?r:If(r)||""}function Df(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function vl(r,...e){if(!Df(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Da(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Of(r,e){vl(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const vr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength);function Pf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function El(r){return typeof r=="string"&&(r=Pf(r)),vl(r),r}let $f=class{clone(){return this._cloneInto()}};function Af(r){const e=i=>r().update(El(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function _l(r=32){if(vr&&typeof vr.getRandomValues=="function")return vr.getRandomValues(new Uint8Array(r));if(vr&&typeof vr.randomBytes=="function")return vr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function xf(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=i?4:0,u=i?0:4;r.setUint32(e+c,o,i),r.setUint32(e+u,a,i)}let Cf=class extends $f{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Zs(this.buffer)}update(e){Da(this);const{view:t,buffer:i,blockLen:s}=this;e=El(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=Zs(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Da(this),Of(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)t[h]=0;xf(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Zs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(i),e}};const zi=BigInt(2**32-1),Fn=BigInt(32);function Il(r,e=!1){return e?{h:Number(r&zi),l:Number(r>>Fn&zi)}:{h:Number(r>>Fn&zi)|0,l:Number(r&zi)|0}}function Tf(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Il(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Rf=(r,e)=>BigInt(r>>>0)<<Fn|BigInt(e>>>0),Nf=(r,e,t)=>r>>>t,jf=(r,e,t)=>r<<32-t|e>>>t,Bf=(r,e,t)=>r>>>t|e<<32-t,Uf=(r,e,t)=>r<<32-t|e>>>t,Ff=(r,e,t)=>r<<64-t|e>>>t-32,qf=(r,e,t)=>r>>>t-32|e<<64-t,Lf=(r,e)=>e,kf=(r,e)=>r,Mf=(r,e,t)=>r<<t|e>>>32-t,zf=(r,e,t)=>e<<t|r>>>32-t,Hf=(r,e,t)=>e<<t-32|r>>>64-t,Vf=(r,e,t)=>r<<t-32|e>>>64-t;function Kf(r,e,t,i){const s=(e>>>0)+(i>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}const Wf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Gf=(r,e,t,i)=>e+t+i+(r/2**32|0)|0,Yf=(r,e,t,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(i>>>0),Jf=(r,e,t,i,s)=>e+t+i+s+(r/2**32|0)|0,Zf=(r,e,t,i,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),Qf=(r,e,t,i,s,n)=>e+t+i+s+n+(r/2**32|0)|0,K={fromBig:Il,split:Tf,toBig:Rf,shrSH:Nf,shrSL:jf,rotrSH:Bf,rotrSL:Uf,rotrBH:Ff,rotrBL:qf,rotr32H:Lf,rotr32L:kf,rotlSH:Mf,rotlSL:zf,rotlBH:Hf,rotlBL:Vf,add:Kf,add3L:Wf,add3H:Gf,add4L:Yf,add4H:Jf,add5H:Qf,add5L:Zf},[Xf,eg]=K.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(r=>BigInt(r))),Ut=new Uint32Array(80),Ft=new Uint32Array(80);let tg=class extends Cf{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:t,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:d,Gh:p,Gl:f,Hh:g,Hl:w}=this;return[e,t,i,s,n,o,a,c,u,l,h,d,p,f,g,w]}set(e,t,i,s,n,o,a,c,u,l,h,d,p,f,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=w|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ut[_]=e.getUint32(t),Ft[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){const A=Ut[_-15]|0,T=Ft[_-15]|0,v=K.rotrSH(A,T,1)^K.rotrSH(A,T,8)^K.shrSH(A,T,7),I=K.rotrSL(A,T,1)^K.rotrSL(A,T,8)^K.shrSL(A,T,7),P=Ut[_-2]|0,D=Ft[_-2]|0,j=K.rotrSH(P,D,19)^K.rotrBH(P,D,61)^K.shrSH(P,D,6),N=K.rotrSL(P,D,19)^K.rotrBL(P,D,61)^K.shrSL(P,D,6),B=K.add4L(I,N,Ft[_-7],Ft[_-16]),M=K.add4H(B,v,j,Ut[_-7],Ut[_-16]);Ut[_]=M|0,Ft[_]=B|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:d,Fh:p,Fl:f,Gh:g,Gl:w,Hh:E,Hl:b}=this;for(let _=0;_<80;_++){const A=K.rotrSH(h,d,14)^K.rotrSH(h,d,18)^K.rotrBH(h,d,41),T=K.rotrSL(h,d,14)^K.rotrSL(h,d,18)^K.rotrBL(h,d,41),v=h&p^~h&g,I=d&f^~d&w,P=K.add5L(b,T,I,eg[_],Ft[_]),D=K.add5H(P,E,A,v,Xf[_],Ut[_]),j=P|0,N=K.rotrSH(i,s,28)^K.rotrBH(i,s,34)^K.rotrBH(i,s,39),B=K.rotrSL(i,s,28)^K.rotrBL(i,s,34)^K.rotrBL(i,s,39),M=i&n^i&a^n&a,$=s&o^s&c^o&c;E=g|0,b=w|0,g=p|0,w=f|0,p=h|0,f=d|0,{h,l:d}=K.add(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const y=K.add3L(j,B,$);i=K.add3H(y,D,N,M),s=y|0}({h:i,l:s}=K.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=K.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=K.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=K.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:d}=K.add(this.Eh|0,this.El|0,h|0,d|0),{h:p,l:f}=K.add(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:w}=K.add(this.Gh|0,this.Gl|0,g|0,w|0),{h:E,l:b}=K.add(this.Hh|0,this.Hl|0,E|0,b|0),this.set(i,s,n,o,a,c,u,l,h,d,p,f,g,w,E,b)}roundClean(){Ut.fill(0),Ft.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 rg=Af(()=>new tg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oo=BigInt(0),Sl=BigInt(1),ig=BigInt(2);function Po(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $o(r){if(!Po(r))throw new Error("Uint8Array expected")}function Qs(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}const sg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ao(r){$o(r);let e="";for(let t=0;t<r.length;t++)e+=sg[r[t]];return e}function Dl(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Oo:BigInt("0x"+r)}const Dt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oa(r){if(r>=Dt._0&&r<=Dt._9)return r-Dt._0;if(r>=Dt.A&&r<=Dt.F)return r-(Dt.A-10);if(r>=Dt.a&&r<=Dt.f)return r-(Dt.a-10)}function Ol(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);const e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=Oa(r.charCodeAt(n)),a=Oa(r.charCodeAt(n+1));if(o===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function ng(r){return Dl(Ao(r))}function ns(r){return $o(r),Dl(Ao(Uint8Array.from(r).reverse()))}function Pl(r,e){return Ol(r.toString(16).padStart(e*2,"0"))}function qn(r,e){return Pl(r,e).reverse()}function Ot(r,e,t){let i;if(typeof e=="string")try{i=Ol(e)}catch(n){throw new Error(r+" must be hex string or Uint8Array, cause: "+n)}else if(Po(e))i=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");const s=i.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return i}function Pa(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];$o(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}const Xs=r=>typeof r=="bigint"&&Oo<=r;function og(r,e,t){return Xs(r)&&Xs(e)&&Xs(t)&&e<=r&&r<t}function ai(r,e,t,i){if(!og(e,t,i))throw new Error("expected valid "+r+": "+t+" <= n < "+i+", got "+e)}function ag(r){let e;for(e=0;r>Oo;r>>=Sl,e+=1);return e}const cg=r=>(ig<<BigInt(r-1))-Sl,ug={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Po(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function xo(r,e,t={}){const i=(s,n,o)=>{const a=ug[n];if(typeof a!="function")throw new Error("invalid validator function");const c=r[s];if(!(o&&c===void 0)&&!a(c,r))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(t))i(s,n,!0);return r}function $a(r){const e=new WeakMap;return(t,...i)=>{const s=e.get(t);if(s!==void 0)return s;const n=r(t,...i);return e.set(t,n),n}}const be=BigInt(0),ce=BigInt(1),er=BigInt(2),lg=BigInt(3),Ln=BigInt(4),Aa=BigInt(5),xa=BigInt(8);function pe(r,e){const t=r%e;return t>=be?t:e+t}function hg(r,e,t){if(e<be)throw new Error("invalid exponent, negatives unsupported");if(t<=be)throw new Error("invalid modulus");if(t===ce)return be;let i=ce;for(;e>be;)e&ce&&(i=i*r%t),r=r*r%t,e>>=ce;return i}function pt(r,e,t){let i=r;for(;e-- >be;)i*=i,i%=t;return i}function Ca(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=pe(r,e),i=e,s=be,n=ce;for(;t!==be;){const o=i/t,a=i%t,c=s-n*o;i=t,t=a,s=n,n=c}if(i!==ce)throw new Error("invert: does not exist");return pe(s,e)}function dg(r){const e=(r-ce)/er;let t,i,s;for(t=r-ce,i=0;t%er===be;t/=er,i++);for(s=er;s<r&&hg(s,e,r)!==r-ce;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(r+ce)/Ln;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(t+ce)/er;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),t),l=o.pow(a,n),h=o.pow(a,t);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,ce<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function pg(r){if(r%Ln===lg){const e=(r+ce)/Ln;return function(t,i){const s=t.pow(i,e);if(!t.eql(t.sqr(s),i))throw new Error("Cannot find square root");return s}}if(r%xa===Aa){const e=(r-Aa)/xa;return function(t,i){const s=t.mul(i,er),n=t.pow(s,e),o=t.mul(i,n),a=t.mul(t.mul(o,er),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),i))throw new Error("Cannot find square root");return c}}return dg(r)}const fg=(r,e)=>(pe(r,e)&ce)===ce,gg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function yg(r){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=gg.reduce((i,s)=>(i[s]="function",i),e);return xo(r,t)}function mg(r,e,t){if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return r.ONE;if(t===ce)return e;let i=r.ONE,s=e;for(;t>be;)t&ce&&(i=r.mul(i,s)),s=r.sqr(s),t>>=ce;return i}function wg(r,e){const t=new Array(e.length),i=e.reduce((n,o,a)=>r.is0(o)?n:(t[a]=n,r.mul(n,o)),r.ONE),s=r.inv(i);return e.reduceRight((n,o,a)=>r.is0(o)?n:(t[a]=r.mul(n,t[a]),r.mul(n,o)),s),t}function $l(r,e){const t=e!==void 0?e:r.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function Al(r,e,t=!1,i={}){if(r<=be)throw new Error("invalid field: expected ORDER > 0, got "+r);const{nBitLength:s,nByteLength:n}=$l(r,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:r,isLE:t,BITS:s,BYTES:n,MASK:cg(s),ZERO:be,ONE:ce,create:c=>pe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return be<=c&&c<r},is0:c=>c===be,isOdd:c=>(c&ce)===ce,neg:c=>pe(-c,r),eql:(c,u)=>c===u,sqr:c=>pe(c*c,r),add:(c,u)=>pe(c+u,r),sub:(c,u)=>pe(c-u,r),mul:(c,u)=>pe(c*u,r),pow:(c,u)=>mg(a,c,u),div:(c,u)=>pe(c*Ca(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ca(c,r),sqrt:i.sqrt||(c=>(o||(o=pg(r)),o(a,c))),invertBatch:c=>wg(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>t?qn(c,n):Pl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?ns(c):ng(c)}});return Object.freeze(a)}const Ta=BigInt(0),Hi=BigInt(1);function en(r,e){const t=e.negate();return r?t:e}function xl(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tn(r,e){xl(r,e);const t=Math.ceil(e/r)+1,i=2**(r-1);return{windows:t,windowSize:i}}function bg(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function vg(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const rn=new WeakMap,Cl=new WeakMap;function sn(r){return Cl.get(r)||1}function Eg(r,e){return{constTimeNegate:en,hasPrecomputes(t){return sn(t)!==1},unsafeLadder(t,i,s=r.ZERO){let n=t;for(;i>Ta;)i&Hi&&(s=s.add(n)),n=n.double(),i>>=Hi;return s},precomputeWindow(t,i){const{windows:s,windowSize:n}=tn(i,e),o=[];let a=t,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,i,s){const{windows:n,windowSize:o}=tn(t,e);let a=r.ZERO,c=r.BASE;const u=BigInt(2**t-1),l=2**t,h=BigInt(t);for(let d=0;d<n;d++){const p=d*o;let f=Number(s&u);s>>=h,f>o&&(f-=l,s+=Hi);const g=p,w=p+Math.abs(f)-1,E=d%2!==0,b=f<0;f===0?c=c.add(en(E,i[g])):a=a.add(en(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(t,i,s,n=r.ZERO){const{windows:o,windowSize:a}=tn(t,e),c=BigInt(2**t-1),u=2**t,l=BigInt(t);for(let h=0;h<o;h++){const d=h*a;if(s===Ta)break;let p=Number(s&c);if(s>>=l,p>a&&(p-=u,s+=Hi),p===0)continue;let f=i[d+Math.abs(p)-1];p<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(t,i,s){let n=rn.get(i);return n||(n=this.precomputeWindow(i,t),t!==1&&rn.set(i,s(n))),n},wNAFCached(t,i,s){const n=sn(t);return this.wNAF(n,this.getPrecomputes(n,t,s),i)},wNAFCachedUnsafe(t,i,s,n){const o=sn(t);return o===1?this.unsafeLadder(t,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),i,n)},setWindowSize(t,i){xl(i,e),Cl.set(t,i),rn.delete(t)}}}function _g(r,e,t,i){if(bg(t,r),vg(i,e),t.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=r.ZERO,n=ag(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let p=0;p<i.length;p++){const f=i[p],g=Number(f>>BigInt(h)&BigInt(a));c[g]=c[g].add(t[p])}let d=s;for(let p=c.length-1,f=s;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Ig(r){return yg(r.Fp),xo(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$l(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}const nt=BigInt(0),je=BigInt(1),Vi=BigInt(2),Sg=BigInt(8),Dg={zip215:!0};function Og(r){const e=Ig(r);return xo(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Pg(r){const e=Og(r),{Fp:t,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=Vi<<BigInt(a*8)-je,l=t.create,h=Al(e.n,e.nBitLength),d=e.uvRatio||((y,m)=>{try{return{isValid:!0,value:t.sqrt(y*t.inv(m))}}catch{return{isValid:!1,value:nt}}}),p=e.adjustScalarBytes||(y=>y),f=e.domain||((y,m,S)=>{if(Qs("phflag",S),m.length||S)throw new Error("Contexts/pre-hash are not supported");return y});function g(y,m){ai("coordinate "+y,m,nt,u)}function w(y){if(!(y instanceof _))throw new Error("ExtendedPoint expected")}const E=$a((y,m)=>{const{ex:S,ey:x,ez:O}=y,C=y.is0();m==null&&(m=C?Sg:t.inv(O));const q=l(S*m),k=l(x*m),z=l(O*m);if(C)return{x:nt,y:je};if(z!==je)throw new Error("invZ was invalid");return{x:q,y:k}}),b=$a(y=>{const{a:m,d:S}=e;if(y.is0())throw new Error("bad point: ZERO");const{ex:x,ey:O,ez:C,et:q}=y,k=l(x*x),z=l(O*O),L=l(C*C),H=l(L*L),V=l(k*m),ne=l(L*l(V+z)),ee=l(H+l(S*l(k*z)));if(ne!==ee)throw new Error("bad point: equation left != right (1)");const Y=l(x*O),Ae=l(C*q);if(Y!==Ae)throw new Error("bad point: equation left != right (2)");return!0});class _{constructor(m,S,x,O){this.ex=m,this.ey=S,this.ez=x,this.et=O,g("x",m),g("y",S),g("z",x),g("t",O),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof _)throw new Error("extended point not allowed");const{x:S,y:x}=m||{};return g("x",S),g("y",x),new _(S,x,je,l(S*x))}static normalizeZ(m){const S=t.invertBatch(m.map(x=>x.ez));return m.map((x,O)=>x.toAffine(S[O])).map(_.fromAffine)}static msm(m,S){return _g(_,h,m,S)}_setWindowSize(m){v.setWindowSize(this,m)}assertValidity(){b(this)}equals(m){w(m);const{ex:S,ey:x,ez:O}=this,{ex:C,ey:q,ez:k}=m,z=l(S*k),L=l(C*O),H=l(x*k),V=l(q*O);return z===L&&H===V}is0(){return this.equals(_.ZERO)}negate(){return new _(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:S,ey:x,ez:O}=this,C=l(S*S),q=l(x*x),k=l(Vi*l(O*O)),z=l(m*C),L=S+x,H=l(l(L*L)-C-q),V=z+q,ne=V-k,ee=z-q,Y=l(H*ne),Ae=l(V*ee),Ee=l(H*ee),Ce=l(ne*V);return new _(Y,Ae,Ce,Ee)}add(m){w(m);const{a:S,d:x}=e,{ex:O,ey:C,ez:q,et:k}=this,{ex:z,ey:L,ez:H,et:V}=m;if(S===BigInt(-1)){const Wo=l((C-O)*(L+z)),Go=l((C+O)*(L-z)),zs=l(Go-Wo);if(zs===nt)return this.double();const Yo=l(q*Vi*V),Jo=l(k*Vi*H),Zo=Jo+Yo,Qo=Go+Wo,Xo=Jo-Yo,Cd=l(Zo*zs),Td=l(Qo*Xo),Rd=l(Zo*Xo),Nd=l(zs*Qo);return new _(Cd,Td,Nd,Rd)}const ne=l(O*z),ee=l(C*L),Y=l(k*x*V),Ae=l(q*H),Ee=l((O+C)*(z+L)-ne-ee),Ce=Ae-Y,Je=Ae+Y,Ze=l(ee-S*ne),mr=l(Ee*Ce),$d=l(Je*Ze),Ad=l(Ee*Ze),xd=l(Ce*Je);return new _(mr,$d,xd,Ad)}subtract(m){return this.add(m.negate())}wNAF(m){return v.wNAFCached(this,m,_.normalizeZ)}multiply(m){const S=m;ai("scalar",S,je,i);const{p:x,f:O}=this.wNAF(S);return _.normalizeZ([x,O])[0]}multiplyUnsafe(m,S=_.ZERO){const x=m;return ai("scalar",x,nt,i),x===nt?T:this.is0()||x===je?this:v.wNAFCachedUnsafe(this,x,_.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return v.unsafeLadder(this,i).is0()}toAffine(m){return E(this,m)}clearCofactor(){const{h:m}=e;return m===je?this:this.multiplyUnsafe(m)}static fromHex(m,S=!1){const{d:x,a:O}=e,C=t.BYTES;m=Ot("pointHex",m,C),Qs("zip215",S);const q=m.slice(),k=m[C-1];q[C-1]=k&-129;const z=ns(q),L=S?u:t.ORDER;ai("pointHex.y",z,nt,L);const H=l(z*z),V=l(H-je),ne=l(x*H-O);let{isValid:ee,value:Y}=d(V,ne);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const Ae=(Y&je)===je,Ee=(k&128)!==0;if(!S&&Y===nt&&Ee)throw new Error("Point.fromHex: x=0 and x_0=1");return Ee!==Ae&&(Y=l(-Y)),_.fromAffine({x:Y,y:z})}static fromPrivateKey(m){return D(m).point}toRawBytes(){const{x:m,y:S}=this.toAffine(),x=qn(S,t.BYTES);return x[x.length-1]|=m&je?128:0,x}toHex(){return Ao(this.toRawBytes())}}_.BASE=new _(e.Gx,e.Gy,je,l(e.Gx*e.Gy)),_.ZERO=new _(nt,je,je,nt);const{BASE:A,ZERO:T}=_,v=Eg(_,a*8);function I(y){return pe(y,i)}function P(y){return I(ns(y))}function D(y){const m=t.BYTES;y=Ot("private key",y,m);const S=Ot("hashed private key",n(y),2*m),x=p(S.slice(0,m)),O=S.slice(m,2*m),C=P(x),q=A.multiply(C),k=q.toRawBytes();return{head:x,prefix:O,scalar:C,point:q,pointBytes:k}}function j(y){return D(y).pointBytes}function N(y=new Uint8Array,...m){const S=Pa(...m);return P(n(f(S,Ot("context",y),!!s)))}function B(y,m,S={}){y=Ot("message",y),s&&(y=s(y));const{prefix:x,scalar:O,pointBytes:C}=D(m),q=N(S.context,x,y),k=A.multiply(q).toRawBytes(),z=N(S.context,k,C,y),L=I(q+z*O);ai("signature.s",L,nt,i);const H=Pa(k,qn(L,t.BYTES));return Ot("result",H,t.BYTES*2)}const M=Dg;function $(y,m,S,x=M){const{context:O,zip215:C}=x,q=t.BYTES;y=Ot("signature",y,2*q),m=Ot("message",m),S=Ot("publicKey",S,q),C!==void 0&&Qs("zip215",C),s&&(m=s(m));const k=ns(y.slice(q,2*q));let z,L,H;try{z=_.fromHex(S,C),L=_.fromHex(y.slice(0,q),C),H=A.multiplyUnsafe(k)}catch{return!1}if(!C&&z.isSmallOrder())return!1;const V=N(O,L.toRawBytes(),z.toRawBytes(),m);return L.add(z.multiplyUnsafe(V)).subtract(H).clearCofactor().equals(_.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:B,verify:$,ExtendedPoint:_,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(t.BYTES),precompute(y=8,m=_.BASE){return m._setWindowSize(y),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const Co=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ra=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const $g=BigInt(1),Na=BigInt(2);BigInt(3);const Ag=BigInt(5),xg=BigInt(8);function Cg(r){const e=BigInt(10),t=BigInt(20),i=BigInt(40),s=BigInt(80),n=Co,o=r*r%n*r%n,a=pt(o,Na,n)*o%n,c=pt(a,$g,n)*r%n,u=pt(c,Ag,n)*c%n,l=pt(u,e,n)*u%n,h=pt(l,t,n)*l%n,d=pt(h,i,n)*h%n,p=pt(d,s,n)*d%n,f=pt(p,s,n)*d%n,g=pt(f,e,n)*u%n;return{pow_p_5_8:pt(g,Na,n)*r%n,b2:o}}function Tg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Rg(r,e){const t=Co,i=pe(e*e*e,t),s=pe(i*i*e,t),n=Cg(r*s).pow_p_5_8;let o=pe(r*i*n,t);const a=pe(e*o*o,t),c=o,u=pe(o*Ra,t),l=a===r,h=a===pe(-r,t),d=a===pe(-r*Ra,t);return l&&(o=c),(h||d)&&(o=u),fg(o,t)&&(o=pe(-o,t)),{isValid:l||h,value:o}}const Ng=Al(Co,void 0,!0),jg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ng,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:xg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:rg,randomBytes:_l,adjustScalarBytes:Tg,uvRatio:Rg},Tl=Pg(jg),Bg="EdDSA",Ug="JWT",ps=".",Os="base64url",Rl="utf8",Nl="utf8",Fg=":",qg="did",Lg="key",ja="base58btc",kg="z",Mg="K36",zg=32;function To(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function jl(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?To(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Bl(r,e){e||(e=r.reduce((s,n)=>s+n.length,0));const t=jl(e);let i=0;for(const s of r)t.set(s,i),i+=s.length;return To(t)}function Hg(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,w=0,E=0,b=f.length;E!==b&&f[E]===0;)E++,g++;for(var _=(b-E)*l+1>>>0,A=new Uint8Array(_);E!==b;){for(var T=f[E],v=0,I=_-1;(T!==0||v<w)&&I!==-1;I--,v++)T+=256*A[I]>>>0,A[I]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=v,E++}for(var P=_-w;P!==_&&A[P]===0;)P++;for(var D=c.repeat(g);P<_;++P)D+=r.charAt(A[P]);return D}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var w=0,E=0;f[g]===c;)w++,g++;for(var b=(f.length-g)*u+1>>>0,_=new Uint8Array(b);f[g];){var A=t[f.charCodeAt(g)];if(A===255)return;for(var T=0,v=b-1;(A!==0||T<E)&&v!==-1;v--,T++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}if(f[g]!==" "){for(var I=b-E;I!==b&&_[I]===0;)I++;for(var P=new Uint8Array(w+(b-I)),D=w;I!==b;)P[D++]=_[I++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var Vg=Hg,Kg=Vg;const Ul=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},Wg=r=>new TextEncoder().encode(r),Gg=r=>new TextDecoder().decode(r);let Yg=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Jg=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Fl(this,e)}},Zg=class{constructor(e){this.decoders=e}or(e){return Fl(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 Fl=(r,e)=>new Zg({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});let Qg=class{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Yg(e,t,i),this.decoder=new Jg(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ps=({name:r,prefix:e,encode:t,decode:i})=>new Qg(r,e,t,i),Ci=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=Kg(t,e);return Ps({prefix:r,name:e,encode:i,decode:n=>Ul(s(n))})},Xg=(r,e,t,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[r[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ey=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Oe=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Ps({prefix:e,name:r,encode(s){return ey(s,i,t)},decode(s){return Xg(s,i,t,r)}}),ty=Ps({prefix:"\0",name:"identity",encode:r=>Gg(r),decode:r=>Wg(r)});var ry=Object.freeze({__proto__:null,identity:ty});const iy=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sy=Object.freeze({__proto__:null,base2:iy});const ny=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var oy=Object.freeze({__proto__:null,base8:ny});const ay=Ci({prefix:"9",name:"base10",alphabet:"0123456789"});var cy=Object.freeze({__proto__:null,base10:ay});const uy=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ly=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hy=Object.freeze({__proto__:null,base16:uy,base16upper:ly});const dy=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),py=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fy=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),gy=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yy=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),my=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wy=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),by=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vy=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ey=Object.freeze({__proto__:null,base32:dy,base32upper:py,base32pad:fy,base32padupper:gy,base32hex:yy,base32hexupper:my,base32hexpad:wy,base32hexpadupper:by,base32z:vy});const _y=Ci({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iy=Ci({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sy=Object.freeze({__proto__:null,base36:_y,base36upper:Iy});const Dy=Ci({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Oy=Ci({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Py=Object.freeze({__proto__:null,base58btc:Dy,base58flickr:Oy});const $y=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ay=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xy=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cy=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ty=Object.freeze({__proto__:null,base64:$y,base64pad:Ay,base64url:xy,base64urlpad:Cy});const ql=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Ry=ql.reduce((r,e,t)=>(r[t]=e,r),[]),Ny=ql.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function jy(r){return r.reduce((e,t)=>(e+=Ry[t],e),"")}function By(r){const e=[];for(const t of r){const i=Ny[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const Uy=Ps({prefix:"🚀",name:"base256emoji",encode:jy,decode:By});var Fy=Object.freeze({__proto__:null,base256emoji:Uy}),qy=Ll,Ba=128,Ly=-128,ky=Math.pow(2,31);function Ll(r,e,t){e=e||[],t=t||0;for(var i=t;r>=ky;)e[t++]=r&255|Ba,r/=128;for(;r&Ly;)e[t++]=r&255|Ba,r>>>=7;return e[t]=r|0,Ll.bytes=t-i+1,e}var My=kn,zy=128,Ua=127;function kn(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw kn.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&Ua)<<s:(o&Ua)*Math.pow(2,s),s+=7}while(o>=zy);return kn.bytes=n-i,t}var Hy=Math.pow(2,7),Vy=Math.pow(2,14),Ky=Math.pow(2,21),Wy=Math.pow(2,28),Gy=Math.pow(2,35),Yy=Math.pow(2,42),Jy=Math.pow(2,49),Zy=Math.pow(2,56),Qy=Math.pow(2,63),Xy=function(r){return r<Hy?1:r<Vy?2:r<Ky?3:r<Wy?4:r<Gy?5:r<Yy?6:r<Jy?7:r<Zy?8:r<Qy?9:10},em={encode:qy,decode:My,encodingLength:Xy},kl=em;const Fa=(r,e,t=0)=>(kl.encode(r,e,t),e),qa=r=>kl.encodingLength(r),Mn=(r,e)=>{const t=e.byteLength,i=qa(r),s=i+qa(t),n=new Uint8Array(s+t);return Fa(r,n,0),Fa(t,n,i),n.set(e,s),new tm(r,t,e,n)};let tm=class{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}};const Ml=({name:r,code:e,encode:t})=>new rm(r,e,t);let rm=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Mn(this.code,t):t.then(i=>Mn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const zl=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),im=Ml({name:"sha2-256",code:18,encode:zl("SHA-256")}),sm=Ml({name:"sha2-512",code:19,encode:zl("SHA-512")});var nm=Object.freeze({__proto__:null,sha256:im,sha512:sm});const Hl=0,om="identity",Vl=Ul,am=r=>Mn(Hl,Vl(r)),cm={code:Hl,name:om,encode:Vl,digest:am};var um=Object.freeze({__proto__:null,identity:cm});new TextEncoder,new TextDecoder;const La={...ry,...sy,...oy,...cy,...hy,...Ey,...Sy,...Py,...Ty,...Fy};({...nm,...um});function Kl(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const ka=Kl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),nn=Kl("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=jl(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Wl={utf8:ka,"utf-8":ka,hex:La.base16,latin1:nn,ascii:nn,binary:nn,...La};function $s(r,e="utf8"){const t=Wl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}function Zr(r,e="utf8"){const t=Wl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?To(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function Ma(r){return cr($s(Zr(r,Os),Rl))}function fs(r){return $s(Zr(Bt(r),Rl),Os)}function Gl(r){const e=Zr(Mg,ja),t=kg+$s(Bl([e,r]),ja);return[qg,Lg,t].join(Fg)}function lm(r){return $s(r,Os)}function hm(r){return Zr(r,Os)}function dm(r){return Zr([fs(r.header),fs(r.payload)].join(ps),Nl)}function pm(r){return[fs(r.header),fs(r.payload),lm(r.signature)].join(ps)}function zn(r){const e=r.split(ps),t=Ma(e[0]),i=Ma(e[1]),s=hm(e[2]),n=Zr(e.slice(0,2).join(ps),Nl);return{header:t,payload:i,signature:s,data:n}}function za(r=_l(zg)){const e=Tl.getPublicKey(r);return{secretKey:Bl([r,e]),publicKey:e}}async function fm(r,e,t,i,s=U.fromMiliseconds(Date.now())){const n={alg:Bg,typ:Ug},o=Gl(i.publicKey),a=s+t,c={iss:o,sub:r,aud:e,iat:s,exp:a},u=dm({header:n,payload:c}),l=Tl.sign(u,i.secretKey.slice(0,32));return pm({header:n,payload:c,signature:l})}function Yl(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function mi(r,e){e||(e=r.reduce((s,n)=>s+n.length,0));const t=Yl(e);let i=0;for(const s of r)t.set(s,i),i+=s.length;return t}function gm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,w=0,E=0,b=f.length;E!==b&&f[E]===0;)E++,g++;for(var _=(b-E)*l+1>>>0,A=new Uint8Array(_);E!==b;){for(var T=f[E],v=0,I=_-1;(T!==0||v<w)&&I!==-1;I--,v++)T+=256*A[I]>>>0,A[I]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=v,E++}for(var P=_-w;P!==_&&A[P]===0;)P++;for(var D=c.repeat(g);P<_;++P)D+=r.charAt(A[P]);return D}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var w=0,E=0;f[g]===c;)w++,g++;for(var b=(f.length-g)*u+1>>>0,_=new Uint8Array(b);f[g];){var A=t[f.charCodeAt(g)];if(A===255)return;for(var T=0,v=b-1;(A!==0||T<E)&&v!==-1;v--,T++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}if(f[g]!==" "){for(var I=b-E;I!==b&&_[I]===0;)I++;for(var P=new Uint8Array(w+(b-I)),D=w;I!==b;)P[D++]=_[I++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var ym=gm,mm=ym;const wm=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},bm=r=>new TextEncoder().encode(r),vm=r=>new TextDecoder().decode(r);class Em{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class _m{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Jl(this,e)}}class Im{constructor(e){this.decoders=e}or(e){return Jl(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 Jl=(r,e)=>new Im({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class Sm{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Em(e,t,i),this.decoder=new _m(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const As=({name:r,prefix:e,encode:t,decode:i})=>new Sm(r,e,t,i),Ti=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=mm(t,e);return As({prefix:r,name:e,encode:i,decode:n=>wm(s(n))})},Dm=(r,e,t,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[r[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Om=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Pe=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>As({prefix:e,name:r,encode(s){return Om(s,i,t)},decode(s){return Dm(s,i,t,r)}}),Pm=As({prefix:"\0",name:"identity",encode:r=>vm(r),decode:r=>bm(r)}),$m=Object.freeze(Object.defineProperty({__proto__:null,identity:Pm},Symbol.toStringTag,{value:"Module"})),Am=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),xm=Object.freeze(Object.defineProperty({__proto__:null,base2:Am},Symbol.toStringTag,{value:"Module"})),Cm=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Tm=Object.freeze(Object.defineProperty({__proto__:null,base8:Cm},Symbol.toStringTag,{value:"Module"})),Rm=Ti({prefix:"9",name:"base10",alphabet:"0123456789"}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base10:Rm},Symbol.toStringTag,{value:"Module"})),jm=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bm=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Um=Object.freeze(Object.defineProperty({__proto__:null,base16:jm,base16upper:Bm},Symbol.toStringTag,{value:"Module"})),Fm=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qm=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Lm=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),km=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mm=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zm=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hm=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vm=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Km=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Wm=Object.freeze(Object.defineProperty({__proto__:null,base32:Fm,base32hex:Mm,base32hexpad:Hm,base32hexpadupper:Vm,base32hexupper:zm,base32pad:Lm,base32padupper:km,base32upper:qm,base32z:Km},Symbol.toStringTag,{value:"Module"})),Gm=Ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ym=Ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Jm=Object.freeze(Object.defineProperty({__proto__:null,base36:Gm,base36upper:Ym},Symbol.toStringTag,{value:"Module"})),Zm=Ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qm=Ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Xm=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Zm,base58flickr:Qm},Symbol.toStringTag,{value:"Module"})),ew=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tw=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rw=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iw=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),sw=Object.freeze(Object.defineProperty({__proto__:null,base64:ew,base64pad:tw,base64url:rw,base64urlpad:iw},Symbol.toStringTag,{value:"Module"})),Zl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),nw=Zl.reduce((r,e,t)=>(r[t]=e,r),[]),ow=Zl.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function aw(r){return r.reduce((e,t)=>(e+=nw[t],e),"")}function cw(r){const e=[];for(const t of r){const i=ow[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const uw=As({prefix:"🚀",name:"base256emoji",encode:aw,decode:cw}),lw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:uw},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Ha={...$m,...xm,...Tm,...Nm,...Um,...Wm,...Jm,...Xm,...sw,...lw};function Ql(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Va=Ql("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),on=Ql("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=Yl(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Xl={utf8:Va,"utf-8":Va,hex:Ha.base16,latin1:on,ascii:on,binary:on,...Ha};function rt(r,e="utf8"){const t=Xl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}function Le(r,e="utf8"){const t=Xl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}const hw={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var dw={};const pw=":";function kr(r){const[e,t]=r.split(pw);return{namespace:e,reference:t}}function Ka(r,e=[]){const t=[];return Object.keys(r).forEach(i=>{if(e.length&&!e.includes(i))return;const s=r[i];t.push(...s.accounts)}),t}function eh(r,e){return r.includes(":")?[r]:e.chains||[]}var fw=Object.defineProperty,gw=Object.defineProperties,yw=Object.getOwnPropertyDescriptors,Wa=Object.getOwnPropertySymbols,mw=Object.prototype.hasOwnProperty,ww=Object.prototype.propertyIsEnumerable,Ga=(r,e,t)=>e in r?fw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ya=(r,e)=>{for(var t in e||(e={}))mw.call(e,t)&&Ga(r,t,e[t]);if(Wa)for(var t of Wa(e))ww.call(e,t)&&Ga(r,t,e[t]);return r},bw=(r,e)=>gw(r,yw(e));const vw="ReactNative",We={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Ew="js";function gs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Wt(){return!jt.getDocument()&&!!jt.getNavigator()&&navigator.product===vw}function _w(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Iw(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Qr(){return!gs()&&!!jt.getNavigator()&&!!jt.getDocument()}function Ri(){return Wt()?We.reactNative:gs()?We.node:Qr()?We.browser:We.unknown}function Ja(){var r;try{return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(r=global.Application)==null?void 0:r.applicationId:void 0}catch{return}}function Sw(r,e){const t=new URLSearchParams(r);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&t.set(i,s)}return t.toString()}function Dw(r){var e,t;const i=th();try{return r!=null&&r.url&&i.url&&new URL(r.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${r.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),r.url=i.url),(e=r==null?void 0:r.icons)!=null&&e.length&&r.icons.length>0&&(r.icons=r.icons.filter(s=>s!=="")),bw(Ya(Ya({},i),r),{url:(r==null?void 0:r.url)||i.url,name:(r==null?void 0:r.name)||i.name,description:(r==null?void 0:r.description)||i.description,icons:(t=r==null?void 0:r.icons)!=null&&t.length&&r.icons.length>0?r.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),r||i}}function th(){return Cp.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Ow(){if(Ri()===We.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:i}=global.Platform;return[t,i].join("-")}const r=Yd();if(r===null)return"unknown";const e=r.os?r.os.replace(" ","").toLowerCase():"unknown";return r.type==="browser"?[e,r.name,r.version].join("-"):[e,r.version].join("-")}function Pw(){var r;const e=Ri();return e===We.browser?[e,((r=jt.getLocation())==null?void 0:r.host)||"unknown"].join(":"):e}function rh(r,e,t){const i=Ow(),s=Pw();return[[r,e].join("-"),[Ew,t].join("-"),i,s].join("/")}function $w({protocol:r,version:e,relayUrl:t,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=t.split("?"),l=rh(r,e,i),h={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Sw(u[1]||"",h);return u[0]+"?"+d}function sr(r,e){return r.filter(t=>e.includes(t)).length===r.length}function Hn(r){return Object.fromEntries(r.entries())}function Vn(r){return new Map(Object.entries(r))}function Qt(r=U.FIVE_MINUTES,e){const t=U.toMiliseconds(r||U.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},t),i=a,s=c})}}function zt(r,e,t){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(t)),e);try{const o=await r;i(o)}catch(o){s(o)}clearTimeout(n)})}function ih(r,e){if(typeof e=="string"&&e.startsWith(`${r}:`))return e;if(r.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(r.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: ${r}`)}function Aw(r){return ih("topic",r)}function xw(r){return ih("id",r)}function sh(r){const[e,t]=r.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function de(r,e){return U.fromMiliseconds(Date.now()+U.toMiliseconds(r))}function kt(r){return Date.now()>=U.toMiliseconds(r)}function X(r,e){return`${r}${e?`:${e}`:""}`}function _t(r=[],e=[]){return[...new Set([...r,...e])]}async function Cw({id:r,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const s=typeof t=="string"?JSON.parse(t):t,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=Tw(n,r,e),a=Ri();if(a===We.browser){if(!((i=jt.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Rw(o)}else a===We.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function Tw(r,e,t){const i=`requestId=${e}&sessionTopic=${t}`;r.endsWith("/")&&(r=r.slice(0,-1));let s=`${r}`;if(r.startsWith("https://t.me")){const n=r.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Uw(i,!0)}`}else s=`${s}/wc?${i}`;return s}function Rw(r){let e="_self";Bw()?e="_top":(jw()||r.startsWith("https://")||r.startsWith("http://"))&&(e="_blank"),window.open(r,e,"noreferrer noopener")}async function Nw(r,e){let t="";try{if(Qr()&&(t=localStorage.getItem(e),t))return t;t=await r.getItem(e)}catch(i){console.error(i)}return t}function Za(r,e){if(!r.includes(e))return null;const t=r.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Qa(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Ro(){return typeof process<"u"&&dw.IS_VITEST==="true"}function jw(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Bw(){try{return window.self!==window.top}catch{return!1}}function Uw(r,e=!1){const t=Buffer.from(r).toString("base64");return e?t.replace(/[=]/g,""):t}function nh(r){return Buffer.from(r,"base64").toString("utf-8")}function Fw(r){return new Promise(e=>setTimeout(e,r))}function Si(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function qw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ni(r,...e){if(!qw(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function No(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Si(r.outputLen),Si(r.blockLen)}function Mr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function oh(r,e){Ni(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ki=BigInt(2**32-1),Xa=BigInt(32);function Lw(r,e=!1){return e?{h:Number(r&Ki),l:Number(r>>Xa&Ki)}:{h:Number(r>>Xa&Ki)|0,l:Number(r&Ki)|0}}function kw(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Lw(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Mw=(r,e,t)=>r<<t|e>>>32-t,zw=(r,e,t)=>e<<t|r>>>32-t,Hw=(r,e,t)=>e<<t-32|r>>>64-t,Vw=(r,e,t)=>r<<t-32|e>>>64-t,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Kw(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function an(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ft(r,e){return r<<32-e|r>>>e}const ec=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ww(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function tc(r){for(let e=0;e<r.length;e++)r[e]=Ww(r[e])}function Gw(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function zr(r){return typeof r=="string"&&(r=Gw(r)),Ni(r),r}function Yw(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Ni(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}let jo=class{clone(){return this._cloneInto()}};function ah(r){const e=i=>r().update(zr(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xr(r=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(r));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}const ch=[],uh=[],lh=[],Jw=BigInt(0),ci=BigInt(1),Zw=BigInt(2),Qw=BigInt(7),Xw=BigInt(256),eb=BigInt(113);for(let r=0,e=ci,t=1,i=0;r<24;r++){[t,i]=[i,(2*t+3*i)%5],ch.push(2*(5*i+t)),uh.push((r+1)*(r+2)/2%64);let s=Jw;for(let n=0;n<7;n++)e=(e<<ci^(e>>Qw)*eb)%Xw,e&Zw&&(s^=ci<<(ci<<BigInt(n))-ci);lh.push(s)}const[tb,rb]=kw(lh,!0),rc=(r,e,t)=>t>32?Hw(r,e,t):Mw(r,e,t),ic=(r,e,t)=>t>32?Vw(r,e,t):zw(r,e,t);function ib(r,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],l=t[c+1],h=rc(u,l,1)^t[a],d=ic(u,l,1)^t[a+1];for(let p=0;p<50;p+=10)r[o+p]^=h,r[o+p+1]^=d}let s=r[2],n=r[3];for(let o=0;o<24;o++){const a=uh[o],c=rc(s,n,a),u=ic(s,n,a),l=ch[o];s=r[l],n=r[l+1],r[l]=c,r[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}r[0]^=tb[i],r[1]^=rb[i]}t.fill(0)}let sb=class hh extends jo{constructor(e,t,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Si(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Kw(this.state)}keccak(){ec||tc(this.state32),ib(this.state32,this.rounds),ec||tc(this.state32),this.posOut=0,this.pos=0}update(e){Mr(this);const{blockLen:t,state:i}=this;e=zr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(t-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,(t&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Mr(this,!1),Ni(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(t.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Si(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(oh(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new hh(t,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const nb=(r,e,t)=>ah(()=>new sb(e,r,t)),ob=nb(1,136,256/8),ab="https://rpc.walletconnect.org/v1";function dh(r){const e=`Ethereum Signed Message:
|
|
16
|
+
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=s,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=cl}walk(e){return ul(this,e)}}function ul(r,e){return e!=null&&e(r)?r:r&&typeof r=="object"&&"cause"in r&&r.cause!==void 0?ul(r.cause,e):e?null:r}class ll extends ar{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Yr(r,{dir:e,size:t=32}={}){return typeof r=="string"?Tp(r,{dir:e,size:t}):Rp(r,{dir:e,size:t})}function Tp(r,{dir:e,size:t=32}={}){if(t===null)return r;const i=r.replace("0x","");if(i.length>t*2)throw new ll({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Rp(r,{dir:e,size:t=32}={}){if(t===null)return r;if(r.length>t)throw new ll({size:r.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let s=0;s<t;s++){const n=e==="right";i[n?s:t-s-1]=r[n?s:r.length-s-1]}return i}class Np extends ar{constructor({max:e,min:t,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class jp extends ar{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Jr(r,{size:e}){if(ya(r)>e)throw new jp({givenSize:ya(r),maxSize:e})}function Bn(r,e={}){const{signed:t}=e;e.size&&Jr(r,{size:e.size});const i=BigInt(r);if(!t)return i;const s=(r.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function Bp(r,e={}){return Number(Bn(r,e))}const Up=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Un(r,e={}){return typeof r=="number"||typeof r=="bigint"?dl(r,e):typeof r=="string"?Lp(r,e):typeof r=="boolean"?Fp(r,e):hl(r,e)}function Fp(r,e={}){const t=`0x${Number(r)}`;return typeof e.size=="number"?(Jr(t,{size:e.size}),Yr(t,{size:e.size})):t}function hl(r,e={}){let t="";for(let s=0;s<r.length;s++)t+=Up[r[s]];const i=`0x${t}`;return typeof e.size=="number"?(Jr(i,{size:e.size}),Yr(i,{dir:"right",size:e.size})):i}function dl(r,e={}){const{signed:t,size:i}=e,s=BigInt(r);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof r=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&s>n||s<o){const c=typeof r=="bigint"?"n":"";throw new Np({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${r}${c}`})}const a=`0x${(t&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?Yr(a,{size:i}):a}const qp=new TextEncoder;function Lp(r,e={}){const t=qp.encode(r);return hl(t,e)}const kp=new TextEncoder;function Mp(r,e={}){return typeof r=="number"||typeof r=="bigint"?Hp(r,e):typeof r=="boolean"?zp(r,e):Ii(r)?pl(r,e):fl(r,e)}function zp(r,e={}){const t=new Uint8Array(1);return t[0]=Number(r),typeof e.size=="number"?(Jr(t,{size:e.size}),Yr(t,{size:e.size})):t}const St={zero:48,nine:57,A:65,F:70,a:97,f:102};function ma(r){if(r>=St.zero&&r<=St.nine)return r-St.zero;if(r>=St.A&&r<=St.F)return r-(St.A-10);if(r>=St.a&&r<=St.f)return r-(St.a-10)}function pl(r,e={}){let t=r;e.size&&(Jr(t,{size:e.size}),t=Yr(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=ma(i.charCodeAt(a++)),u=ma(i.charCodeAt(a++));if(c===void 0||u===void 0)throw new ar(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+u}return n}function Hp(r,e){const t=dl(r,e);return pl(t)}function fl(r,e={}){const t=kp.encode(r);return typeof e.size=="number"?(Jr(t,{size:e.size}),Yr(t,{dir:"right",size:e.size})):t}function ds(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Vp(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ds(r,...e){if(!Vp(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function EP(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ds(r.outputLen),ds(r.blockLen)}function wa(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Kp(r,e){Ds(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Mi=BigInt(2**32-1),ba=BigInt(32);function Wp(r,e=!1){return e?{h:Number(r&Mi),l:Number(r>>ba&Mi)}:{h:Number(r>>ba&Mi)|0,l:Number(r&Mi)|0}}function Gp(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Wp(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Yp=(r,e,t)=>r<<t|e>>>32-t,Jp=(r,e,t)=>e<<t|r>>>32-t,Zp=(r,e,t)=>e<<t-32|r>>>64-t,Qp=(r,e,t)=>r<<t-32|e>>>64-t,br=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Xp(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function _P(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function IP(r,e){return r<<32-e|r>>>e}const va=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ef(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Ea(r){for(let e=0;e<r.length;e++)r[e]=ef(r[e])}function tf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function gl(r){return typeof r=="string"&&(r=tf(r)),Ds(r),r}function SP(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Ds(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}class rf{clone(){return this._cloneInto()}}function sf(r){const e=i=>r().update(gl(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function DP(r=32){if(br&&typeof br.getRandomValues=="function")return br.getRandomValues(new Uint8Array(r));if(br&&typeof br.randomBytes=="function")return br.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}const yl=[],ml=[],wl=[],nf=BigInt(0),oi=BigInt(1),of=BigInt(2),af=BigInt(7),cf=BigInt(256),uf=BigInt(113);for(let r=0,e=oi,t=1,i=0;r<24;r++){[t,i]=[i,(2*t+3*i)%5],yl.push(2*(5*i+t)),ml.push((r+1)*(r+2)/2%64);let s=nf;for(let n=0;n<7;n++)e=(e<<oi^(e>>af)*uf)%cf,e&of&&(s^=oi<<(oi<<BigInt(n))-oi);wl.push(s)}const[lf,hf]=Gp(wl,!0),_a=(r,e,t)=>t>32?Zp(r,e,t):Yp(r,e,t),Ia=(r,e,t)=>t>32?Qp(r,e,t):Jp(r,e,t);function df(r,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],l=t[c+1],h=_a(u,l,1)^t[a],d=Ia(u,l,1)^t[a+1];for(let p=0;p<50;p+=10)r[o+p]^=h,r[o+p+1]^=d}let s=r[2],n=r[3];for(let o=0;o<24;o++){const a=ml[o],c=_a(s,n,a),u=Ia(s,n,a),l=yl[o];s=r[l],n=r[l+1],r[l]=c,r[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}r[0]^=lf[i],r[1]^=hf[i]}t.fill(0)}class Do extends rf{constructor(e,t,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ds(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Xp(this.state)}keccak(){va||Ea(this.state32),df(this.state32,this.rounds),va||Ea(this.state32),this.posOut=0,this.pos=0}update(e){wa(this);const{blockLen:t,state:i}=this;e=gl(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(t-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,(t&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){wa(this,!1),Ds(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(t.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ds(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Kp(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Do(t,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const pf=(r,e,t)=>sf(()=>new Do(e,r,t)),ff=pf(1,136,256/8);function bl(r,e){const t=e||"hex",i=ff(Ii(r,{strict:!1})?Mp(r):r);return t==="bytes"?i:Un(i)}class gf extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Js=new gf(8192);function yf(r,e){if(Js.has(`${r}.${e}`))return Js.get(`${r}.${e}`);const t=r.substring(2).toLowerCase(),i=bl(fl(t),"bytes"),s=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return Js.set(`${r}.${e}`,n),n}function mf(r){const e=bl(`0x${r.substring(4)}`).substring(26);return yf(`0x${e}`)}async function wf({hash:r,signature:e}){const t=Ii(r)?r:Un(r),{secp256k1:i}=await il(async()=>{const{secp256k1:o}=await import("./secp256k1-BmewtLue.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:d}=e,p=Number(d??h),f=Sa(p);return new i.Signature(Bn(u),Bn(l)).addRecoveryBit(f)}const o=Ii(e)?e:Un(e),a=Bp(`0x${o.slice(130)}`),c=Sa(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Sa(r){if(r===0||r===1)return r;if(r===27)return 0;if(r===28)return 1;throw new Error("Invalid yParityOrV value")}async function bf({hash:r,signature:e}){return mf(await wf({hash:r,signature:e}))}function vf(r){if(r.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<r.length;u++){const l=r.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const t=r.length,i=r.charAt(0),s=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,d=0;const p=u.length;for(;d!==p&&u[d]===0;)d++,l++;const f=(p-d)*n+1>>>0,g=new Uint8Array(f);for(;d!==p;){let b=u[d],_=0;for(let A=f-1;(b!==0||_<h)&&A!==-1;A--,_++)b+=256*g[A]>>>0,g[A]=b%t>>>0,b=b/t>>>0;if(b!==0)throw new Error("Non-zero carry");h=_,d++}let w=f-h;for(;w!==f&&g[w]===0;)w++;let E=i.repeat(l);for(;w<f;++w)E+=r.charAt(g[w]);return E}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,d=0;for(;u[l]===i;)h++,l++;const p=(u.length-l)*s+1>>>0,f=new Uint8Array(p);for(;l<u.length;){const b=u.charCodeAt(l);if(b>255)return;let _=e[b];if(_===255)return;let A=0;for(let T=p-1;(_!==0||A<d)&&T!==-1;T--,A++)_+=t*f[T]>>>0,f[T]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");d=A,l++}let g=p-d;for(;g!==p&&f[g]===0;)g++;const w=new Uint8Array(h+(p-g));let E=h;for(;g!==p;)w[E++]=f[g++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Ef="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const _f=vf(Ef),If=r=>JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),Sf=r=>{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,t=r.replace(e,'$1"$2n"$3');return JSON.parse(t,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function cr(r){if(typeof r!="string")throw new Error(`Cannot safe json parse value of type ${typeof r}`);try{return Sf(r)}catch{return r}}function Bt(r){return typeof r=="string"?r:If(r)||""}function Df(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function vl(r,...e){if(!Df(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Da(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Of(r,e){vl(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const vr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength);function Pf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function El(r){return typeof r=="string"&&(r=Pf(r)),vl(r),r}let $f=class{clone(){return this._cloneInto()}};function Af(r){const e=i=>r().update(El(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function _l(r=32){if(vr&&typeof vr.getRandomValues=="function")return vr.getRandomValues(new Uint8Array(r));if(vr&&typeof vr.randomBytes=="function")return vr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function xf(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=i?4:0,u=i?0:4;r.setUint32(e+c,o,i),r.setUint32(e+u,a,i)}let Cf=class extends $f{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Zs(this.buffer)}update(e){Da(this);const{view:t,buffer:i,blockLen:s}=this;e=El(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=Zs(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Da(this),Of(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)t[h]=0;xf(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Zs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(i),e}};const zi=BigInt(2**32-1),Fn=BigInt(32);function Il(r,e=!1){return e?{h:Number(r&zi),l:Number(r>>Fn&zi)}:{h:Number(r>>Fn&zi)|0,l:Number(r&zi)|0}}function Tf(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Il(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Rf=(r,e)=>BigInt(r>>>0)<<Fn|BigInt(e>>>0),Nf=(r,e,t)=>r>>>t,jf=(r,e,t)=>r<<32-t|e>>>t,Bf=(r,e,t)=>r>>>t|e<<32-t,Uf=(r,e,t)=>r<<32-t|e>>>t,Ff=(r,e,t)=>r<<64-t|e>>>t-32,qf=(r,e,t)=>r>>>t-32|e<<64-t,Lf=(r,e)=>e,kf=(r,e)=>r,Mf=(r,e,t)=>r<<t|e>>>32-t,zf=(r,e,t)=>e<<t|r>>>32-t,Hf=(r,e,t)=>e<<t-32|r>>>64-t,Vf=(r,e,t)=>r<<t-32|e>>>64-t;function Kf(r,e,t,i){const s=(e>>>0)+(i>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}const Wf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Gf=(r,e,t,i)=>e+t+i+(r/2**32|0)|0,Yf=(r,e,t,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(i>>>0),Jf=(r,e,t,i,s)=>e+t+i+s+(r/2**32|0)|0,Zf=(r,e,t,i,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),Qf=(r,e,t,i,s,n)=>e+t+i+s+n+(r/2**32|0)|0,K={fromBig:Il,split:Tf,toBig:Rf,shrSH:Nf,shrSL:jf,rotrSH:Bf,rotrSL:Uf,rotrBH:Ff,rotrBL:qf,rotr32H:Lf,rotr32L:kf,rotlSH:Mf,rotlSL:zf,rotlBH:Hf,rotlBL:Vf,add:Kf,add3L:Wf,add3H:Gf,add4L:Yf,add4H:Jf,add5H:Qf,add5L:Zf},[Xf,eg]=K.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(r=>BigInt(r))),Ut=new Uint32Array(80),Ft=new Uint32Array(80);let tg=class extends Cf{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:t,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:d,Gh:p,Gl:f,Hh:g,Hl:w}=this;return[e,t,i,s,n,o,a,c,u,l,h,d,p,f,g,w]}set(e,t,i,s,n,o,a,c,u,l,h,d,p,f,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=w|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ut[_]=e.getUint32(t),Ft[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){const A=Ut[_-15]|0,T=Ft[_-15]|0,v=K.rotrSH(A,T,1)^K.rotrSH(A,T,8)^K.shrSH(A,T,7),I=K.rotrSL(A,T,1)^K.rotrSL(A,T,8)^K.shrSL(A,T,7),P=Ut[_-2]|0,D=Ft[_-2]|0,j=K.rotrSH(P,D,19)^K.rotrBH(P,D,61)^K.shrSH(P,D,6),N=K.rotrSL(P,D,19)^K.rotrBL(P,D,61)^K.shrSL(P,D,6),B=K.add4L(I,N,Ft[_-7],Ft[_-16]),M=K.add4H(B,v,j,Ut[_-7],Ut[_-16]);Ut[_]=M|0,Ft[_]=B|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:d,Fh:p,Fl:f,Gh:g,Gl:w,Hh:E,Hl:b}=this;for(let _=0;_<80;_++){const A=K.rotrSH(h,d,14)^K.rotrSH(h,d,18)^K.rotrBH(h,d,41),T=K.rotrSL(h,d,14)^K.rotrSL(h,d,18)^K.rotrBL(h,d,41),v=h&p^~h&g,I=d&f^~d&w,P=K.add5L(b,T,I,eg[_],Ft[_]),D=K.add5H(P,E,A,v,Xf[_],Ut[_]),j=P|0,N=K.rotrSH(i,s,28)^K.rotrBH(i,s,34)^K.rotrBH(i,s,39),B=K.rotrSL(i,s,28)^K.rotrBL(i,s,34)^K.rotrBL(i,s,39),M=i&n^i&a^n&a,$=s&o^s&c^o&c;E=g|0,b=w|0,g=p|0,w=f|0,p=h|0,f=d|0,{h,l:d}=K.add(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const y=K.add3L(j,B,$);i=K.add3H(y,D,N,M),s=y|0}({h:i,l:s}=K.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=K.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=K.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=K.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:d}=K.add(this.Eh|0,this.El|0,h|0,d|0),{h:p,l:f}=K.add(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:w}=K.add(this.Gh|0,this.Gl|0,g|0,w|0),{h:E,l:b}=K.add(this.Hh|0,this.Hl|0,E|0,b|0),this.set(i,s,n,o,a,c,u,l,h,d,p,f,g,w,E,b)}roundClean(){Ut.fill(0),Ft.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 rg=Af(()=>new tg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oo=BigInt(0),Sl=BigInt(1),ig=BigInt(2);function Po(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $o(r){if(!Po(r))throw new Error("Uint8Array expected")}function Qs(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}const sg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ao(r){$o(r);let e="";for(let t=0;t<r.length;t++)e+=sg[r[t]];return e}function Dl(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Oo:BigInt("0x"+r)}const Dt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oa(r){if(r>=Dt._0&&r<=Dt._9)return r-Dt._0;if(r>=Dt.A&&r<=Dt.F)return r-(Dt.A-10);if(r>=Dt.a&&r<=Dt.f)return r-(Dt.a-10)}function Ol(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);const e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=Oa(r.charCodeAt(n)),a=Oa(r.charCodeAt(n+1));if(o===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function ng(r){return Dl(Ao(r))}function ns(r){return $o(r),Dl(Ao(Uint8Array.from(r).reverse()))}function Pl(r,e){return Ol(r.toString(16).padStart(e*2,"0"))}function qn(r,e){return Pl(r,e).reverse()}function Ot(r,e,t){let i;if(typeof e=="string")try{i=Ol(e)}catch(n){throw new Error(r+" must be hex string or Uint8Array, cause: "+n)}else if(Po(e))i=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");const s=i.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return i}function Pa(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];$o(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}const Xs=r=>typeof r=="bigint"&&Oo<=r;function og(r,e,t){return Xs(r)&&Xs(e)&&Xs(t)&&e<=r&&r<t}function ai(r,e,t,i){if(!og(e,t,i))throw new Error("expected valid "+r+": "+t+" <= n < "+i+", got "+e)}function ag(r){let e;for(e=0;r>Oo;r>>=Sl,e+=1);return e}const cg=r=>(ig<<BigInt(r-1))-Sl,ug={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Po(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function xo(r,e,t={}){const i=(s,n,o)=>{const a=ug[n];if(typeof a!="function")throw new Error("invalid validator function");const c=r[s];if(!(o&&c===void 0)&&!a(c,r))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(t))i(s,n,!0);return r}function $a(r){const e=new WeakMap;return(t,...i)=>{const s=e.get(t);if(s!==void 0)return s;const n=r(t,...i);return e.set(t,n),n}}const be=BigInt(0),ce=BigInt(1),er=BigInt(2),lg=BigInt(3),Ln=BigInt(4),Aa=BigInt(5),xa=BigInt(8);function pe(r,e){const t=r%e;return t>=be?t:e+t}function hg(r,e,t){if(e<be)throw new Error("invalid exponent, negatives unsupported");if(t<=be)throw new Error("invalid modulus");if(t===ce)return be;let i=ce;for(;e>be;)e&ce&&(i=i*r%t),r=r*r%t,e>>=ce;return i}function pt(r,e,t){let i=r;for(;e-- >be;)i*=i,i%=t;return i}function Ca(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=pe(r,e),i=e,s=be,n=ce;for(;t!==be;){const o=i/t,a=i%t,c=s-n*o;i=t,t=a,s=n,n=c}if(i!==ce)throw new Error("invert: does not exist");return pe(s,e)}function dg(r){const e=(r-ce)/er;let t,i,s;for(t=r-ce,i=0;t%er===be;t/=er,i++);for(s=er;s<r&&hg(s,e,r)!==r-ce;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(r+ce)/Ln;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(t+ce)/er;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),t),l=o.pow(a,n),h=o.pow(a,t);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,ce<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function pg(r){if(r%Ln===lg){const e=(r+ce)/Ln;return function(t,i){const s=t.pow(i,e);if(!t.eql(t.sqr(s),i))throw new Error("Cannot find square root");return s}}if(r%xa===Aa){const e=(r-Aa)/xa;return function(t,i){const s=t.mul(i,er),n=t.pow(s,e),o=t.mul(i,n),a=t.mul(t.mul(o,er),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),i))throw new Error("Cannot find square root");return c}}return dg(r)}const fg=(r,e)=>(pe(r,e)&ce)===ce,gg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function yg(r){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=gg.reduce((i,s)=>(i[s]="function",i),e);return xo(r,t)}function mg(r,e,t){if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return r.ONE;if(t===ce)return e;let i=r.ONE,s=e;for(;t>be;)t&ce&&(i=r.mul(i,s)),s=r.sqr(s),t>>=ce;return i}function wg(r,e){const t=new Array(e.length),i=e.reduce((n,o,a)=>r.is0(o)?n:(t[a]=n,r.mul(n,o)),r.ONE),s=r.inv(i);return e.reduceRight((n,o,a)=>r.is0(o)?n:(t[a]=r.mul(n,t[a]),r.mul(n,o)),s),t}function $l(r,e){const t=e!==void 0?e:r.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function Al(r,e,t=!1,i={}){if(r<=be)throw new Error("invalid field: expected ORDER > 0, got "+r);const{nBitLength:s,nByteLength:n}=$l(r,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:r,isLE:t,BITS:s,BYTES:n,MASK:cg(s),ZERO:be,ONE:ce,create:c=>pe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return be<=c&&c<r},is0:c=>c===be,isOdd:c=>(c&ce)===ce,neg:c=>pe(-c,r),eql:(c,u)=>c===u,sqr:c=>pe(c*c,r),add:(c,u)=>pe(c+u,r),sub:(c,u)=>pe(c-u,r),mul:(c,u)=>pe(c*u,r),pow:(c,u)=>mg(a,c,u),div:(c,u)=>pe(c*Ca(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ca(c,r),sqrt:i.sqrt||(c=>(o||(o=pg(r)),o(a,c))),invertBatch:c=>wg(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>t?qn(c,n):Pl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?ns(c):ng(c)}});return Object.freeze(a)}const Ta=BigInt(0),Hi=BigInt(1);function en(r,e){const t=e.negate();return r?t:e}function xl(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tn(r,e){xl(r,e);const t=Math.ceil(e/r)+1,i=2**(r-1);return{windows:t,windowSize:i}}function bg(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function vg(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const rn=new WeakMap,Cl=new WeakMap;function sn(r){return Cl.get(r)||1}function Eg(r,e){return{constTimeNegate:en,hasPrecomputes(t){return sn(t)!==1},unsafeLadder(t,i,s=r.ZERO){let n=t;for(;i>Ta;)i&Hi&&(s=s.add(n)),n=n.double(),i>>=Hi;return s},precomputeWindow(t,i){const{windows:s,windowSize:n}=tn(i,e),o=[];let a=t,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,i,s){const{windows:n,windowSize:o}=tn(t,e);let a=r.ZERO,c=r.BASE;const u=BigInt(2**t-1),l=2**t,h=BigInt(t);for(let d=0;d<n;d++){const p=d*o;let f=Number(s&u);s>>=h,f>o&&(f-=l,s+=Hi);const g=p,w=p+Math.abs(f)-1,E=d%2!==0,b=f<0;f===0?c=c.add(en(E,i[g])):a=a.add(en(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(t,i,s,n=r.ZERO){const{windows:o,windowSize:a}=tn(t,e),c=BigInt(2**t-1),u=2**t,l=BigInt(t);for(let h=0;h<o;h++){const d=h*a;if(s===Ta)break;let p=Number(s&c);if(s>>=l,p>a&&(p-=u,s+=Hi),p===0)continue;let f=i[d+Math.abs(p)-1];p<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(t,i,s){let n=rn.get(i);return n||(n=this.precomputeWindow(i,t),t!==1&&rn.set(i,s(n))),n},wNAFCached(t,i,s){const n=sn(t);return this.wNAF(n,this.getPrecomputes(n,t,s),i)},wNAFCachedUnsafe(t,i,s,n){const o=sn(t);return o===1?this.unsafeLadder(t,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),i,n)},setWindowSize(t,i){xl(i,e),Cl.set(t,i),rn.delete(t)}}}function _g(r,e,t,i){if(bg(t,r),vg(i,e),t.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=r.ZERO,n=ag(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let p=0;p<i.length;p++){const f=i[p],g=Number(f>>BigInt(h)&BigInt(a));c[g]=c[g].add(t[p])}let d=s;for(let p=c.length-1,f=s;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Ig(r){return yg(r.Fp),xo(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$l(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}const nt=BigInt(0),je=BigInt(1),Vi=BigInt(2),Sg=BigInt(8),Dg={zip215:!0};function Og(r){const e=Ig(r);return xo(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Pg(r){const e=Og(r),{Fp:t,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=Vi<<BigInt(a*8)-je,l=t.create,h=Al(e.n,e.nBitLength),d=e.uvRatio||((y,m)=>{try{return{isValid:!0,value:t.sqrt(y*t.inv(m))}}catch{return{isValid:!1,value:nt}}}),p=e.adjustScalarBytes||(y=>y),f=e.domain||((y,m,S)=>{if(Qs("phflag",S),m.length||S)throw new Error("Contexts/pre-hash are not supported");return y});function g(y,m){ai("coordinate "+y,m,nt,u)}function w(y){if(!(y instanceof _))throw new Error("ExtendedPoint expected")}const E=$a((y,m)=>{const{ex:S,ey:x,ez:O}=y,C=y.is0();m==null&&(m=C?Sg:t.inv(O));const q=l(S*m),k=l(x*m),z=l(O*m);if(C)return{x:nt,y:je};if(z!==je)throw new Error("invZ was invalid");return{x:q,y:k}}),b=$a(y=>{const{a:m,d:S}=e;if(y.is0())throw new Error("bad point: ZERO");const{ex:x,ey:O,ez:C,et:q}=y,k=l(x*x),z=l(O*O),L=l(C*C),H=l(L*L),V=l(k*m),ne=l(L*l(V+z)),ee=l(H+l(S*l(k*z)));if(ne!==ee)throw new Error("bad point: equation left != right (1)");const Y=l(x*O),Ae=l(C*q);if(Y!==Ae)throw new Error("bad point: equation left != right (2)");return!0});class _{constructor(m,S,x,O){this.ex=m,this.ey=S,this.ez=x,this.et=O,g("x",m),g("y",S),g("z",x),g("t",O),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof _)throw new Error("extended point not allowed");const{x:S,y:x}=m||{};return g("x",S),g("y",x),new _(S,x,je,l(S*x))}static normalizeZ(m){const S=t.invertBatch(m.map(x=>x.ez));return m.map((x,O)=>x.toAffine(S[O])).map(_.fromAffine)}static msm(m,S){return _g(_,h,m,S)}_setWindowSize(m){v.setWindowSize(this,m)}assertValidity(){b(this)}equals(m){w(m);const{ex:S,ey:x,ez:O}=this,{ex:C,ey:q,ez:k}=m,z=l(S*k),L=l(C*O),H=l(x*k),V=l(q*O);return z===L&&H===V}is0(){return this.equals(_.ZERO)}negate(){return new _(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:S,ey:x,ez:O}=this,C=l(S*S),q=l(x*x),k=l(Vi*l(O*O)),z=l(m*C),L=S+x,H=l(l(L*L)-C-q),V=z+q,ne=V-k,ee=z-q,Y=l(H*ne),Ae=l(V*ee),Ee=l(H*ee),Ce=l(ne*V);return new _(Y,Ae,Ce,Ee)}add(m){w(m);const{a:S,d:x}=e,{ex:O,ey:C,ez:q,et:k}=this,{ex:z,ey:L,ez:H,et:V}=m;if(S===BigInt(-1)){const Wo=l((C-O)*(L+z)),Go=l((C+O)*(L-z)),zs=l(Go-Wo);if(zs===nt)return this.double();const Yo=l(q*Vi*V),Jo=l(k*Vi*H),Zo=Jo+Yo,Qo=Go+Wo,Xo=Jo-Yo,Cd=l(Zo*zs),Td=l(Qo*Xo),Rd=l(Zo*Xo),Nd=l(zs*Qo);return new _(Cd,Td,Nd,Rd)}const ne=l(O*z),ee=l(C*L),Y=l(k*x*V),Ae=l(q*H),Ee=l((O+C)*(z+L)-ne-ee),Ce=Ae-Y,Je=Ae+Y,Ze=l(ee-S*ne),mr=l(Ee*Ce),$d=l(Je*Ze),Ad=l(Ee*Ze),xd=l(Ce*Je);return new _(mr,$d,xd,Ad)}subtract(m){return this.add(m.negate())}wNAF(m){return v.wNAFCached(this,m,_.normalizeZ)}multiply(m){const S=m;ai("scalar",S,je,i);const{p:x,f:O}=this.wNAF(S);return _.normalizeZ([x,O])[0]}multiplyUnsafe(m,S=_.ZERO){const x=m;return ai("scalar",x,nt,i),x===nt?T:this.is0()||x===je?this:v.wNAFCachedUnsafe(this,x,_.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return v.unsafeLadder(this,i).is0()}toAffine(m){return E(this,m)}clearCofactor(){const{h:m}=e;return m===je?this:this.multiplyUnsafe(m)}static fromHex(m,S=!1){const{d:x,a:O}=e,C=t.BYTES;m=Ot("pointHex",m,C),Qs("zip215",S);const q=m.slice(),k=m[C-1];q[C-1]=k&-129;const z=ns(q),L=S?u:t.ORDER;ai("pointHex.y",z,nt,L);const H=l(z*z),V=l(H-je),ne=l(x*H-O);let{isValid:ee,value:Y}=d(V,ne);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const Ae=(Y&je)===je,Ee=(k&128)!==0;if(!S&&Y===nt&&Ee)throw new Error("Point.fromHex: x=0 and x_0=1");return Ee!==Ae&&(Y=l(-Y)),_.fromAffine({x:Y,y:z})}static fromPrivateKey(m){return D(m).point}toRawBytes(){const{x:m,y:S}=this.toAffine(),x=qn(S,t.BYTES);return x[x.length-1]|=m&je?128:0,x}toHex(){return Ao(this.toRawBytes())}}_.BASE=new _(e.Gx,e.Gy,je,l(e.Gx*e.Gy)),_.ZERO=new _(nt,je,je,nt);const{BASE:A,ZERO:T}=_,v=Eg(_,a*8);function I(y){return pe(y,i)}function P(y){return I(ns(y))}function D(y){const m=t.BYTES;y=Ot("private key",y,m);const S=Ot("hashed private key",n(y),2*m),x=p(S.slice(0,m)),O=S.slice(m,2*m),C=P(x),q=A.multiply(C),k=q.toRawBytes();return{head:x,prefix:O,scalar:C,point:q,pointBytes:k}}function j(y){return D(y).pointBytes}function N(y=new Uint8Array,...m){const S=Pa(...m);return P(n(f(S,Ot("context",y),!!s)))}function B(y,m,S={}){y=Ot("message",y),s&&(y=s(y));const{prefix:x,scalar:O,pointBytes:C}=D(m),q=N(S.context,x,y),k=A.multiply(q).toRawBytes(),z=N(S.context,k,C,y),L=I(q+z*O);ai("signature.s",L,nt,i);const H=Pa(k,qn(L,t.BYTES));return Ot("result",H,t.BYTES*2)}const M=Dg;function $(y,m,S,x=M){const{context:O,zip215:C}=x,q=t.BYTES;y=Ot("signature",y,2*q),m=Ot("message",m),S=Ot("publicKey",S,q),C!==void 0&&Qs("zip215",C),s&&(m=s(m));const k=ns(y.slice(q,2*q));let z,L,H;try{z=_.fromHex(S,C),L=_.fromHex(y.slice(0,q),C),H=A.multiplyUnsafe(k)}catch{return!1}if(!C&&z.isSmallOrder())return!1;const V=N(O,L.toRawBytes(),z.toRawBytes(),m);return L.add(z.multiplyUnsafe(V)).subtract(H).clearCofactor().equals(_.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:B,verify:$,ExtendedPoint:_,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(t.BYTES),precompute(y=8,m=_.BASE){return m._setWindowSize(y),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const Co=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ra=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const $g=BigInt(1),Na=BigInt(2);BigInt(3);const Ag=BigInt(5),xg=BigInt(8);function Cg(r){const e=BigInt(10),t=BigInt(20),i=BigInt(40),s=BigInt(80),n=Co,o=r*r%n*r%n,a=pt(o,Na,n)*o%n,c=pt(a,$g,n)*r%n,u=pt(c,Ag,n)*c%n,l=pt(u,e,n)*u%n,h=pt(l,t,n)*l%n,d=pt(h,i,n)*h%n,p=pt(d,s,n)*d%n,f=pt(p,s,n)*d%n,g=pt(f,e,n)*u%n;return{pow_p_5_8:pt(g,Na,n)*r%n,b2:o}}function Tg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Rg(r,e){const t=Co,i=pe(e*e*e,t),s=pe(i*i*e,t),n=Cg(r*s).pow_p_5_8;let o=pe(r*i*n,t);const a=pe(e*o*o,t),c=o,u=pe(o*Ra,t),l=a===r,h=a===pe(-r,t),d=a===pe(-r*Ra,t);return l&&(o=c),(h||d)&&(o=u),fg(o,t)&&(o=pe(-o,t)),{isValid:l||h,value:o}}const Ng=Al(Co,void 0,!0),jg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ng,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:xg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:rg,randomBytes:_l,adjustScalarBytes:Tg,uvRatio:Rg},Tl=Pg(jg),Bg="EdDSA",Ug="JWT",ps=".",Os="base64url",Rl="utf8",Nl="utf8",Fg=":",qg="did",Lg="key",ja="base58btc",kg="z",Mg="K36",zg=32;function To(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function jl(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?To(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Bl(r,e){e||(e=r.reduce((s,n)=>s+n.length,0));const t=jl(e);let i=0;for(const s of r)t.set(s,i),i+=s.length;return To(t)}function Hg(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,w=0,E=0,b=f.length;E!==b&&f[E]===0;)E++,g++;for(var _=(b-E)*l+1>>>0,A=new Uint8Array(_);E!==b;){for(var T=f[E],v=0,I=_-1;(T!==0||v<w)&&I!==-1;I--,v++)T+=256*A[I]>>>0,A[I]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=v,E++}for(var P=_-w;P!==_&&A[P]===0;)P++;for(var D=c.repeat(g);P<_;++P)D+=r.charAt(A[P]);return D}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var w=0,E=0;f[g]===c;)w++,g++;for(var b=(f.length-g)*u+1>>>0,_=new Uint8Array(b);f[g];){var A=t[f.charCodeAt(g)];if(A===255)return;for(var T=0,v=b-1;(A!==0||T<E)&&v!==-1;v--,T++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}if(f[g]!==" "){for(var I=b-E;I!==b&&_[I]===0;)I++;for(var P=new Uint8Array(w+(b-I)),D=w;I!==b;)P[D++]=_[I++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var Vg=Hg,Kg=Vg;const Ul=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},Wg=r=>new TextEncoder().encode(r),Gg=r=>new TextDecoder().decode(r);let Yg=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Jg=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Fl(this,e)}},Zg=class{constructor(e){this.decoders=e}or(e){return Fl(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 Fl=(r,e)=>new Zg({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});let Qg=class{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Yg(e,t,i),this.decoder=new Jg(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ps=({name:r,prefix:e,encode:t,decode:i})=>new Qg(r,e,t,i),Ci=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=Kg(t,e);return Ps({prefix:r,name:e,encode:i,decode:n=>Ul(s(n))})},Xg=(r,e,t,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[r[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ey=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Oe=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Ps({prefix:e,name:r,encode(s){return ey(s,i,t)},decode(s){return Xg(s,i,t,r)}}),ty=Ps({prefix:"\0",name:"identity",encode:r=>Gg(r),decode:r=>Wg(r)});var ry=Object.freeze({__proto__:null,identity:ty});const iy=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sy=Object.freeze({__proto__:null,base2:iy});const ny=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var oy=Object.freeze({__proto__:null,base8:ny});const ay=Ci({prefix:"9",name:"base10",alphabet:"0123456789"});var cy=Object.freeze({__proto__:null,base10:ay});const uy=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ly=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hy=Object.freeze({__proto__:null,base16:uy,base16upper:ly});const dy=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),py=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fy=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),gy=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yy=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),my=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wy=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),by=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vy=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ey=Object.freeze({__proto__:null,base32:dy,base32upper:py,base32pad:fy,base32padupper:gy,base32hex:yy,base32hexupper:my,base32hexpad:wy,base32hexpadupper:by,base32z:vy});const _y=Ci({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iy=Ci({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sy=Object.freeze({__proto__:null,base36:_y,base36upper:Iy});const Dy=Ci({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Oy=Ci({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Py=Object.freeze({__proto__:null,base58btc:Dy,base58flickr:Oy});const $y=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ay=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xy=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cy=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ty=Object.freeze({__proto__:null,base64:$y,base64pad:Ay,base64url:xy,base64urlpad:Cy});const ql=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Ry=ql.reduce((r,e,t)=>(r[t]=e,r),[]),Ny=ql.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function jy(r){return r.reduce((e,t)=>(e+=Ry[t],e),"")}function By(r){const e=[];for(const t of r){const i=Ny[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const Uy=Ps({prefix:"🚀",name:"base256emoji",encode:jy,decode:By});var Fy=Object.freeze({__proto__:null,base256emoji:Uy}),qy=Ll,Ba=128,Ly=-128,ky=Math.pow(2,31);function Ll(r,e,t){e=e||[],t=t||0;for(var i=t;r>=ky;)e[t++]=r&255|Ba,r/=128;for(;r&Ly;)e[t++]=r&255|Ba,r>>>=7;return e[t]=r|0,Ll.bytes=t-i+1,e}var My=kn,zy=128,Ua=127;function kn(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw kn.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&Ua)<<s:(o&Ua)*Math.pow(2,s),s+=7}while(o>=zy);return kn.bytes=n-i,t}var Hy=Math.pow(2,7),Vy=Math.pow(2,14),Ky=Math.pow(2,21),Wy=Math.pow(2,28),Gy=Math.pow(2,35),Yy=Math.pow(2,42),Jy=Math.pow(2,49),Zy=Math.pow(2,56),Qy=Math.pow(2,63),Xy=function(r){return r<Hy?1:r<Vy?2:r<Ky?3:r<Wy?4:r<Gy?5:r<Yy?6:r<Jy?7:r<Zy?8:r<Qy?9:10},em={encode:qy,decode:My,encodingLength:Xy},kl=em;const Fa=(r,e,t=0)=>(kl.encode(r,e,t),e),qa=r=>kl.encodingLength(r),Mn=(r,e)=>{const t=e.byteLength,i=qa(r),s=i+qa(t),n=new Uint8Array(s+t);return Fa(r,n,0),Fa(t,n,i),n.set(e,s),new tm(r,t,e,n)};let tm=class{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}};const Ml=({name:r,code:e,encode:t})=>new rm(r,e,t);let rm=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Mn(this.code,t):t.then(i=>Mn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const zl=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),im=Ml({name:"sha2-256",code:18,encode:zl("SHA-256")}),sm=Ml({name:"sha2-512",code:19,encode:zl("SHA-512")});var nm=Object.freeze({__proto__:null,sha256:im,sha512:sm});const Hl=0,om="identity",Vl=Ul,am=r=>Mn(Hl,Vl(r)),cm={code:Hl,name:om,encode:Vl,digest:am};var um=Object.freeze({__proto__:null,identity:cm});new TextEncoder,new TextDecoder;const La={...ry,...sy,...oy,...cy,...hy,...Ey,...Sy,...Py,...Ty,...Fy};({...nm,...um});function Kl(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const ka=Kl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),nn=Kl("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=jl(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Wl={utf8:ka,"utf-8":ka,hex:La.base16,latin1:nn,ascii:nn,binary:nn,...La};function $s(r,e="utf8"){const t=Wl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}function Zr(r,e="utf8"){const t=Wl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?To(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function Ma(r){return cr($s(Zr(r,Os),Rl))}function fs(r){return $s(Zr(Bt(r),Rl),Os)}function Gl(r){const e=Zr(Mg,ja),t=kg+$s(Bl([e,r]),ja);return[qg,Lg,t].join(Fg)}function lm(r){return $s(r,Os)}function hm(r){return Zr(r,Os)}function dm(r){return Zr([fs(r.header),fs(r.payload)].join(ps),Nl)}function pm(r){return[fs(r.header),fs(r.payload),lm(r.signature)].join(ps)}function zn(r){const e=r.split(ps),t=Ma(e[0]),i=Ma(e[1]),s=hm(e[2]),n=Zr(e.slice(0,2).join(ps),Nl);return{header:t,payload:i,signature:s,data:n}}function za(r=_l(zg)){const e=Tl.getPublicKey(r);return{secretKey:Bl([r,e]),publicKey:e}}async function fm(r,e,t,i,s=U.fromMiliseconds(Date.now())){const n={alg:Bg,typ:Ug},o=Gl(i.publicKey),a=s+t,c={iss:o,sub:r,aud:e,iat:s,exp:a},u=dm({header:n,payload:c}),l=Tl.sign(u,i.secretKey.slice(0,32));return pm({header:n,payload:c,signature:l})}function Yl(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function mi(r,e){e||(e=r.reduce((s,n)=>s+n.length,0));const t=Yl(e);let i=0;for(const s of r)t.set(s,i),i+=s.length;return t}function gm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,w=0,E=0,b=f.length;E!==b&&f[E]===0;)E++,g++;for(var _=(b-E)*l+1>>>0,A=new Uint8Array(_);E!==b;){for(var T=f[E],v=0,I=_-1;(T!==0||v<w)&&I!==-1;I--,v++)T+=256*A[I]>>>0,A[I]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=v,E++}for(var P=_-w;P!==_&&A[P]===0;)P++;for(var D=c.repeat(g);P<_;++P)D+=r.charAt(A[P]);return D}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var w=0,E=0;f[g]===c;)w++,g++;for(var b=(f.length-g)*u+1>>>0,_=new Uint8Array(b);f[g];){var A=t[f.charCodeAt(g)];if(A===255)return;for(var T=0,v=b-1;(A!==0||T<E)&&v!==-1;v--,T++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}if(f[g]!==" "){for(var I=b-E;I!==b&&_[I]===0;)I++;for(var P=new Uint8Array(w+(b-I)),D=w;I!==b;)P[D++]=_[I++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var ym=gm,mm=ym;const wm=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},bm=r=>new TextEncoder().encode(r),vm=r=>new TextDecoder().decode(r);class Em{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class _m{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Jl(this,e)}}class Im{constructor(e){this.decoders=e}or(e){return Jl(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 Jl=(r,e)=>new Im({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class Sm{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Em(e,t,i),this.decoder=new _m(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const As=({name:r,prefix:e,encode:t,decode:i})=>new Sm(r,e,t,i),Ti=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=mm(t,e);return As({prefix:r,name:e,encode:i,decode:n=>wm(s(n))})},Dm=(r,e,t,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[r[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Om=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Pe=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>As({prefix:e,name:r,encode(s){return Om(s,i,t)},decode(s){return Dm(s,i,t,r)}}),Pm=As({prefix:"\0",name:"identity",encode:r=>vm(r),decode:r=>bm(r)}),$m=Object.freeze(Object.defineProperty({__proto__:null,identity:Pm},Symbol.toStringTag,{value:"Module"})),Am=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),xm=Object.freeze(Object.defineProperty({__proto__:null,base2:Am},Symbol.toStringTag,{value:"Module"})),Cm=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Tm=Object.freeze(Object.defineProperty({__proto__:null,base8:Cm},Symbol.toStringTag,{value:"Module"})),Rm=Ti({prefix:"9",name:"base10",alphabet:"0123456789"}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base10:Rm},Symbol.toStringTag,{value:"Module"})),jm=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bm=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Um=Object.freeze(Object.defineProperty({__proto__:null,base16:jm,base16upper:Bm},Symbol.toStringTag,{value:"Module"})),Fm=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qm=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Lm=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),km=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mm=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zm=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hm=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vm=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Km=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Wm=Object.freeze(Object.defineProperty({__proto__:null,base32:Fm,base32hex:Mm,base32hexpad:Hm,base32hexpadupper:Vm,base32hexupper:zm,base32pad:Lm,base32padupper:km,base32upper:qm,base32z:Km},Symbol.toStringTag,{value:"Module"})),Gm=Ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ym=Ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Jm=Object.freeze(Object.defineProperty({__proto__:null,base36:Gm,base36upper:Ym},Symbol.toStringTag,{value:"Module"})),Zm=Ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qm=Ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Xm=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Zm,base58flickr:Qm},Symbol.toStringTag,{value:"Module"})),ew=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tw=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rw=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iw=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),sw=Object.freeze(Object.defineProperty({__proto__:null,base64:ew,base64pad:tw,base64url:rw,base64urlpad:iw},Symbol.toStringTag,{value:"Module"})),Zl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),nw=Zl.reduce((r,e,t)=>(r[t]=e,r),[]),ow=Zl.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function aw(r){return r.reduce((e,t)=>(e+=nw[t],e),"")}function cw(r){const e=[];for(const t of r){const i=ow[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const uw=As({prefix:"🚀",name:"base256emoji",encode:aw,decode:cw}),lw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:uw},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Ha={...$m,...xm,...Tm,...Nm,...Um,...Wm,...Jm,...Xm,...sw,...lw};function Ql(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Va=Ql("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),on=Ql("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=Yl(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Xl={utf8:Va,"utf-8":Va,hex:Ha.base16,latin1:on,ascii:on,binary:on,...Ha};function rt(r,e="utf8"){const t=Xl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}function Le(r,e="utf8"){const t=Xl[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}const hw={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var dw={};const pw=":";function kr(r){const[e,t]=r.split(pw);return{namespace:e,reference:t}}function Ka(r,e=[]){const t=[];return Object.keys(r).forEach(i=>{if(e.length&&!e.includes(i))return;const s=r[i];t.push(...s.accounts)}),t}function eh(r,e){return r.includes(":")?[r]:e.chains||[]}var fw=Object.defineProperty,gw=Object.defineProperties,yw=Object.getOwnPropertyDescriptors,Wa=Object.getOwnPropertySymbols,mw=Object.prototype.hasOwnProperty,ww=Object.prototype.propertyIsEnumerable,Ga=(r,e,t)=>e in r?fw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ya=(r,e)=>{for(var t in e||(e={}))mw.call(e,t)&&Ga(r,t,e[t]);if(Wa)for(var t of Wa(e))ww.call(e,t)&&Ga(r,t,e[t]);return r},bw=(r,e)=>gw(r,yw(e));const vw="ReactNative",We={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Ew="js";function gs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Wt(){return!jt.getDocument()&&!!jt.getNavigator()&&navigator.product===vw}function _w(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Iw(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Qr(){return!gs()&&!!jt.getNavigator()&&!!jt.getDocument()}function Ri(){return Wt()?We.reactNative:gs()?We.node:Qr()?We.browser:We.unknown}function Ja(){var r;try{return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(r=global.Application)==null?void 0:r.applicationId:void 0}catch{return}}function Sw(r,e){const t=new URLSearchParams(r);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&t.set(i,s)}return t.toString()}function Dw(r){var e,t;const i=th();try{return r!=null&&r.url&&i.url&&new URL(r.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${r.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),r.url=i.url),(e=r==null?void 0:r.icons)!=null&&e.length&&r.icons.length>0&&(r.icons=r.icons.filter(s=>s!=="")),bw(Ya(Ya({},i),r),{url:(r==null?void 0:r.url)||i.url,name:(r==null?void 0:r.name)||i.name,description:(r==null?void 0:r.description)||i.description,icons:(t=r==null?void 0:r.icons)!=null&&t.length&&r.icons.length>0?r.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),r||i}}function th(){return Cp.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Ow(){if(Ri()===We.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:i}=global.Platform;return[t,i].join("-")}const r=Yd();if(r===null)return"unknown";const e=r.os?r.os.replace(" ","").toLowerCase():"unknown";return r.type==="browser"?[e,r.name,r.version].join("-"):[e,r.version].join("-")}function Pw(){var r;const e=Ri();return e===We.browser?[e,((r=jt.getLocation())==null?void 0:r.host)||"unknown"].join(":"):e}function rh(r,e,t){const i=Ow(),s=Pw();return[[r,e].join("-"),[Ew,t].join("-"),i,s].join("/")}function $w({protocol:r,version:e,relayUrl:t,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=t.split("?"),l=rh(r,e,i),h={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Sw(u[1]||"",h);return u[0]+"?"+d}function sr(r,e){return r.filter(t=>e.includes(t)).length===r.length}function Hn(r){return Object.fromEntries(r.entries())}function Vn(r){return new Map(Object.entries(r))}function Qt(r=U.FIVE_MINUTES,e){const t=U.toMiliseconds(r||U.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},t),i=a,s=c})}}function zt(r,e,t){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(t)),e);try{const o=await r;i(o)}catch(o){s(o)}clearTimeout(n)})}function ih(r,e){if(typeof e=="string"&&e.startsWith(`${r}:`))return e;if(r.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(r.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: ${r}`)}function Aw(r){return ih("topic",r)}function xw(r){return ih("id",r)}function sh(r){const[e,t]=r.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function de(r,e){return U.fromMiliseconds(Date.now()+U.toMiliseconds(r))}function kt(r){return Date.now()>=U.toMiliseconds(r)}function X(r,e){return`${r}${e?`:${e}`:""}`}function _t(r=[],e=[]){return[...new Set([...r,...e])]}async function Cw({id:r,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const s=typeof t=="string"?JSON.parse(t):t,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=Tw(n,r,e),a=Ri();if(a===We.browser){if(!((i=jt.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Rw(o)}else a===We.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function Tw(r,e,t){const i=`requestId=${e}&sessionTopic=${t}`;r.endsWith("/")&&(r=r.slice(0,-1));let s=`${r}`;if(r.startsWith("https://t.me")){const n=r.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Uw(i,!0)}`}else s=`${s}/wc?${i}`;return s}function Rw(r){let e="_self";Bw()?e="_top":(jw()||r.startsWith("https://")||r.startsWith("http://"))&&(e="_blank"),window.open(r,e,"noreferrer noopener")}async function Nw(r,e){let t="";try{if(Qr()&&(t=localStorage.getItem(e),t))return t;t=await r.getItem(e)}catch(i){console.error(i)}return t}function Za(r,e){if(!r.includes(e))return null;const t=r.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Qa(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Ro(){return typeof process<"u"&&dw.IS_VITEST==="true"}function jw(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Bw(){try{return window.self!==window.top}catch{return!1}}function Uw(r,e=!1){const t=Buffer.from(r).toString("base64");return e?t.replace(/[=]/g,""):t}function nh(r){return Buffer.from(r,"base64").toString("utf-8")}function Fw(r){return new Promise(e=>setTimeout(e,r))}function Si(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function qw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ni(r,...e){if(!qw(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function No(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Si(r.outputLen),Si(r.blockLen)}function Mr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function oh(r,e){Ni(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ki=BigInt(2**32-1),Xa=BigInt(32);function Lw(r,e=!1){return e?{h:Number(r&Ki),l:Number(r>>Xa&Ki)}:{h:Number(r>>Xa&Ki)|0,l:Number(r&Ki)|0}}function kw(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Lw(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Mw=(r,e,t)=>r<<t|e>>>32-t,zw=(r,e,t)=>e<<t|r>>>32-t,Hw=(r,e,t)=>e<<t-32|r>>>64-t,Vw=(r,e,t)=>r<<t-32|e>>>64-t,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Kw(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function an(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ft(r,e){return r<<32-e|r>>>e}const ec=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ww(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function tc(r){for(let e=0;e<r.length;e++)r[e]=Ww(r[e])}function Gw(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function zr(r){return typeof r=="string"&&(r=Gw(r)),Ni(r),r}function Yw(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Ni(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}let jo=class{clone(){return this._cloneInto()}};function ah(r){const e=i=>r().update(zr(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xr(r=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(r));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}const ch=[],uh=[],lh=[],Jw=BigInt(0),ci=BigInt(1),Zw=BigInt(2),Qw=BigInt(7),Xw=BigInt(256),eb=BigInt(113);for(let r=0,e=ci,t=1,i=0;r<24;r++){[t,i]=[i,(2*t+3*i)%5],ch.push(2*(5*i+t)),uh.push((r+1)*(r+2)/2%64);let s=Jw;for(let n=0;n<7;n++)e=(e<<ci^(e>>Qw)*eb)%Xw,e&Zw&&(s^=ci<<(ci<<BigInt(n))-ci);lh.push(s)}const[tb,rb]=kw(lh,!0),rc=(r,e,t)=>t>32?Hw(r,e,t):Mw(r,e,t),ic=(r,e,t)=>t>32?Vw(r,e,t):zw(r,e,t);function ib(r,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],l=t[c+1],h=rc(u,l,1)^t[a],d=ic(u,l,1)^t[a+1];for(let p=0;p<50;p+=10)r[o+p]^=h,r[o+p+1]^=d}let s=r[2],n=r[3];for(let o=0;o<24;o++){const a=uh[o],c=rc(s,n,a),u=ic(s,n,a),l=ch[o];s=r[l],n=r[l+1],r[l]=c,r[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}r[0]^=tb[i],r[1]^=rb[i]}t.fill(0)}let sb=class hh extends jo{constructor(e,t,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Si(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Kw(this.state)}keccak(){ec||tc(this.state32),ib(this.state32,this.rounds),ec||tc(this.state32),this.posOut=0,this.pos=0}update(e){Mr(this);const{blockLen:t,state:i}=this;e=zr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(t-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,(t&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Mr(this,!1),Ni(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(t.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Si(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(oh(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new hh(t,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const nb=(r,e,t)=>ah(()=>new sb(e,r,t)),ob=nb(1,136,256/8),ab="https://rpc.walletconnect.org/v1";function dh(r){const e=`Ethereum Signed Message:
|
|
17
17
|
${r.length}`,t=new TextEncoder().encode(e+r);return"0x"+Buffer.from(ob(t)).toString("hex")}async function cb(r,e,t,i,s,n){switch(t.t){case"eip191":return await ub(r,e,t.s);case"eip1271":return await lb(r,e,t.s,i,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function ub(r,e,t){return(await bf({hash:dh(e),signature:t})).toLowerCase()===r.toLowerCase()}async function lb(r,e,t,i,s,n){const o=kr(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u="0000000000000000000000000000000000000000000000000000000000000041",l=t.substring(2),h=dh(e).substring(2),d=a+h+c+u+l,p=await fetch(`${n||ab}/?chainId=${i}&projectId=${s}`,{method:"POST",body:JSON.stringify({id:hb(),jsonrpc:"2.0",method:"eth_call",params:[{to:r,data:d},"latest"]})}),{result:f}=await p.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function hb(){return Date.now()+Math.floor(Math.random()*1e3)}function db(r){const e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const i=t[0];if(i===0)throw new Error("No signatures found");const s=1+i*64;if(t.length<s)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=Buffer.from(r,"base64").slice(1,65);return _f.encode(n)}var pb=Object.defineProperty,fb=Object.defineProperties,gb=Object.getOwnPropertyDescriptors,sc=Object.getOwnPropertySymbols,yb=Object.prototype.hasOwnProperty,mb=Object.prototype.propertyIsEnumerable,nc=(r,e,t)=>e in r?pb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wb=(r,e)=>{for(var t in e||(e={}))yb.call(e,t)&&nc(r,t,e[t]);if(sc)for(var t of sc(e))mb.call(e,t)&&nc(r,t,e[t]);return r},bb=(r,e)=>fb(r,gb(e));const vb="did:pkh:",Bo=r=>r==null?void 0:r.split(":"),Eb=r=>{const e=r&&Bo(r);if(e)return r.includes(vb)?e[3]:e[1]},Kn=r=>{const e=r&&Bo(r);if(e)return e[2]+":"+e[3]},ys=r=>{const e=r&&Bo(r);if(e)return e.pop()};async function oc(r){const{cacao:e,projectId:t}=r,{s:i,p:s}=e,n=ph(s,s.iss),o=ys(s.iss);return await cb(o,n,i,Kn(s.iss),t)}const ph=(r,e)=>{const t=`${r.domain} wants you to sign in with your Ethereum account:`,i=ys(e);if(!r.aud&&!r.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=r.statement||void 0;const n=`URI: ${r.aud||r.uri}`,o=`Version: ${r.version}`,a=`Chain ID: ${Eb(e)}`,c=`Nonce: ${r.nonce}`,u=`Issued At: ${r.iat}`,l=r.exp?`Expiration Time: ${r.exp}`:void 0,h=r.nbf?`Not Before: ${r.nbf}`:void 0,d=r.requestId?`Request ID: ${r.requestId}`:void 0,p=r.resources?`Resources:${r.resources.map(g=>`
|
|
18
18
|
- ${g}`).join("")}`:void 0,f=os(r.resources);if(f){const g=Di(f);s=xb(s,g)}return[t,i,"",s,"",n,o,a,c,u,l,h,d,p].filter(g=>g!=null).join(`
|
|
19
19
|
`)};function _b(r){return Buffer.from(JSON.stringify(r)).toString("base64")}function Ib(r){return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}function ur(r){if(!r)throw new Error("No recap provided, value is undefined");if(!r.att)throw new Error("No `att` property found");const e=Object.keys(r.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=r.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(s=>{const n=i[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function Sb(r,e,t,i={}){return t==null||t.sort((s,n)=>s.localeCompare(n)),{att:{[r]:Db(e,t,i)}}}function Db(r,e,t={}){e=e==null?void 0:e.sort((s,n)=>s.localeCompare(n));const i=e.map(s=>({[`${r}/${s}`]:[t]}));return Object.assign({},...i)}function fh(r){return ur(r),`urn:recap:${_b(r).replace(/=/g,"")}`}function Di(r){const e=Ib(r.replace("urn:recap:",""));return ur(e),e}function Ob(r,e,t){const i=Sb(r,e,t);return fh(i)}function Pb(r){return r&&r.includes("urn:recap:")}function $b(r,e){const t=Di(r),i=Di(e),s=Ab(t,i);return fh(s)}function Ab(r,e){ur(r),ur(e);const t=Object.keys(r.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),i={att:{}};return t.forEach(s=>{var n,o;Object.keys(((n=r.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;i.att[s]=bb(wb({},i.att[s]),{[a]:((c=r.att[s])==null?void 0:c[a])||((u=e.att[s])==null?void 0:u[a])})})}),i}function xb(r="",e){ur(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(r.includes(t))return r;const i=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,d)=>h.action.localeCompare(d.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(s++,`(${s}) '${h}': '${u[h].join("', '")}' for '${a}'.`));i.push(l.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${r?r+" ":""}${o}`}function ac(r){var e;const t=Di(r);ur(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(s=>s.split("/")[1]):[]}function cc(r){const e=Di(r);ur(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(s=>{var n;(n=s==null?void 0:s[0])!=null&&n.chains&&t.push(s[0].chains)})}),[...new Set(t.flat())]}function os(r){if(!r)return;const e=r==null?void 0:r[r.length-1];return Pb(e)?e:void 0}function cn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function gh(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ke(r,...e){if(!gh(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function uc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Cb(r,e){Ke(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function lc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}const Vt=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Tb=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Rb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Rb)throw new Error("Non little-endian hardware is not supported");function Nb(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Wn(r){if(typeof r=="string")r=Nb(r);else if(gh(r))r=Gn(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function jb(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function Bb(r,e){if(r.length!==e.length)return!1;let t=0;for(let i=0;i<r.length;i++)t|=r[i]^e[i];return t===0}const Ub=(r,e)=>{function t(i,...s){if(Ke(i),r.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Ke(u):Ke(u,r.nonceLength)}const n=r.tagLength;n&&s[1]!==void 0&&Ke(s[1]);const o=e(i,...s),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");Ke(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ke(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(Ke(u),n&&u.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(t,r),t};function hc(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!Fb(e))throw new Error("invalid output, must be aligned");return e}function dc(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n);r.setUint32(e+4,o,i),r.setUint32(e+0,a,i)}function Fb(r){return r.byteOffset%4===0}function Gn(r){return Uint8Array.from(r)}function Hr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}const yh=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),qb=yh("expand 16-byte k"),Lb=yh("expand 32-byte k"),kb=Vt(qb),Mb=Vt(Lb);function J(r,e){return r<<e|r>>>32-e}function Yn(r){return r.byteOffset%4===0}const Wi=64,zb=16,mh=2**32-1,pc=new Uint32Array;function Hb(r,e,t,i,s,n,o,a){const c=s.length,u=new Uint8Array(Wi),l=Vt(u),h=Yn(s)&&Yn(n),d=h?Vt(s):pc,p=h?Vt(n):pc;for(let f=0;f<c;o++){if(r(e,t,i,l,o,a),o>=mh)throw new Error("arx: counter overflow");const g=Math.min(Wi,c-f);if(h&&g===Wi){const w=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let E=0,b;E<zb;E++)b=w+E,p[b]=d[b]^l[E];f+=Wi;continue}for(let w=0,E;w<g;w++)E=f+w,n[E]=s[E]^u[w];f+=g}}function Vb(r,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:s,counterRight:n,rounds:o}=jb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return cn(s),cn(o),lc(n),lc(t),(a,c,u,l,h=0)=>{Ke(a),Ke(c),Ke(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),Ke(l),cn(h),h<0||h>=mh)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const p=[];let f=a.length,g,w;if(f===32)p.push(g=Gn(a)),w=Mb;else if(f===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),w=kb,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);Yn(c)||p.push(c=Gn(c));const E=Vt(g);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(w,E,Vt(c.subarray(0,16)),E),c=c.subarray(16)}const b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const A=new Uint8Array(12);A.set(c,n?0:12-c.length),c=A,p.push(c)}const _=Vt(c);return Hb(r,w,E,_,u,l,h,o),Hr(...p),l}}const _e=(r,e)=>r[e++]&255|(r[e++]&255)<<8;class Kb{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=Wn(e),Ke(e,32);const t=_e(e,0),i=_e(e,2),s=_e(e,4),n=_e(e,6),o=_e(e,8),a=_e(e,10),c=_e(e,12),u=_e(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=_e(e,16+2*l)}process(e,t,i=!1){const s=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],d=o[5],p=o[6],f=o[7],g=o[8],w=o[9],E=_e(e,t+0),b=_e(e,t+2),_=_e(e,t+4),A=_e(e,t+6),T=_e(e,t+8),v=_e(e,t+10),I=_e(e,t+12),P=_e(e,t+14);let D=n[0]+(E&8191),j=n[1]+((E>>>13|b<<3)&8191),N=n[2]+((b>>>10|_<<6)&8191),B=n[3]+((_>>>7|A<<9)&8191),M=n[4]+((A>>>4|T<<12)&8191),$=n[5]+(T>>>1&8191),y=n[6]+((T>>>14|v<<2)&8191),m=n[7]+((v>>>11|I<<5)&8191),S=n[8]+((I>>>8|P<<8)&8191),x=n[9]+(P>>>5|s),O=0,C=O+D*a+j*(5*w)+N*(5*g)+B*(5*f)+M*(5*p);O=C>>>13,C&=8191,C+=$*(5*d)+y*(5*h)+m*(5*l)+S*(5*u)+x*(5*c),O+=C>>>13,C&=8191;let q=O+D*c+j*a+N*(5*w)+B*(5*g)+M*(5*f);O=q>>>13,q&=8191,q+=$*(5*p)+y*(5*d)+m*(5*h)+S*(5*l)+x*(5*u),O+=q>>>13,q&=8191;let k=O+D*u+j*c+N*a+B*(5*w)+M*(5*g);O=k>>>13,k&=8191,k+=$*(5*f)+y*(5*p)+m*(5*d)+S*(5*h)+x*(5*l),O+=k>>>13,k&=8191;let z=O+D*l+j*u+N*c+B*a+M*(5*w);O=z>>>13,z&=8191,z+=$*(5*g)+y*(5*f)+m*(5*p)+S*(5*d)+x*(5*h),O+=z>>>13,z&=8191;let L=O+D*h+j*l+N*u+B*c+M*a;O=L>>>13,L&=8191,L+=$*(5*w)+y*(5*g)+m*(5*f)+S*(5*p)+x*(5*d),O+=L>>>13,L&=8191;let H=O+D*d+j*h+N*l+B*u+M*c;O=H>>>13,H&=8191,H+=$*a+y*(5*w)+m*(5*g)+S*(5*f)+x*(5*p),O+=H>>>13,H&=8191;let V=O+D*p+j*d+N*h+B*l+M*u;O=V>>>13,V&=8191,V+=$*c+y*a+m*(5*w)+S*(5*g)+x*(5*f),O+=V>>>13,V&=8191;let ne=O+D*f+j*p+N*d+B*h+M*l;O=ne>>>13,ne&=8191,ne+=$*u+y*c+m*a+S*(5*w)+x*(5*g),O+=ne>>>13,ne&=8191;let ee=O+D*g+j*f+N*p+B*d+M*h;O=ee>>>13,ee&=8191,ee+=$*l+y*u+m*c+S*a+x*(5*w),O+=ee>>>13,ee&=8191;let Y=O+D*w+j*g+N*f+B*p+M*d;O=Y>>>13,Y&=8191,Y+=$*h+y*l+m*u+S*c+x*a,O+=Y>>>13,Y&=8191,O=(O<<2)+O|0,O=O+C|0,C=O&8191,O=O>>>13,q+=O,n[0]=C,n[1]=q,n[2]=k,n[3]=z,n[4]=L,n[5]=H,n[6]=V,n[7]=ne,n[8]=ee,n[9]=Y}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,i[0]=e[0]+5,s=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+s,s=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Hr(i)}update(e){uc(this);const{buffer:t,blockLen:i}=this;e=Wn(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);if(o===i){for(;i<=s-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Hr(this.h,this.r,this.buffer,this.pad)}digestInto(e){uc(this),Cb(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}}function Wb(r){const e=(i,s)=>r(s).update(Wn(i)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>r(i),e}const Gb=Wb(r=>new Kb(r));function Yb(r,e,t,i,s,n=20){let o=r[0],a=r[1],c=r[2],u=r[3],l=e[0],h=e[1],d=e[2],p=e[3],f=e[4],g=e[5],w=e[6],E=e[7],b=s,_=t[0],A=t[1],T=t[2],v=o,I=a,P=c,D=u,j=l,N=h,B=d,M=p,$=f,y=g,m=w,S=E,x=b,O=_,C=A,q=T;for(let z=0;z<n;z+=2)v=v+j|0,x=J(x^v,16),$=$+x|0,j=J(j^$,12),v=v+j|0,x=J(x^v,8),$=$+x|0,j=J(j^$,7),I=I+N|0,O=J(O^I,16),y=y+O|0,N=J(N^y,12),I=I+N|0,O=J(O^I,8),y=y+O|0,N=J(N^y,7),P=P+B|0,C=J(C^P,16),m=m+C|0,B=J(B^m,12),P=P+B|0,C=J(C^P,8),m=m+C|0,B=J(B^m,7),D=D+M|0,q=J(q^D,16),S=S+q|0,M=J(M^S,12),D=D+M|0,q=J(q^D,8),S=S+q|0,M=J(M^S,7),v=v+N|0,q=J(q^v,16),m=m+q|0,N=J(N^m,12),v=v+N|0,q=J(q^v,8),m=m+q|0,N=J(N^m,7),I=I+B|0,x=J(x^I,16),S=S+x|0,B=J(B^S,12),I=I+B|0,x=J(x^I,8),S=S+x|0,B=J(B^S,7),P=P+M|0,O=J(O^P,16),$=$+O|0,M=J(M^$,12),P=P+M|0,O=J(O^P,8),$=$+O|0,M=J(M^$,7),D=D+j|0,C=J(C^D,16),y=y+C|0,j=J(j^y,12),D=D+j|0,C=J(C^D,8),y=y+C|0,j=J(j^y,7);let k=0;i[k++]=o+v|0,i[k++]=a+I|0,i[k++]=c+P|0,i[k++]=u+D|0,i[k++]=l+j|0,i[k++]=h+N|0,i[k++]=d+B|0,i[k++]=p+M|0,i[k++]=f+$|0,i[k++]=g+y|0,i[k++]=w+m|0,i[k++]=E+S|0,i[k++]=b+x|0,i[k++]=_+O|0,i[k++]=A+C|0,i[k++]=T+q|0}const Jb=Vb(Yb,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Zb=new Uint8Array(16),fc=(r,e)=>{r.update(e);const t=e.length%16;t&&r.update(Zb.subarray(t))},Qb=new Uint8Array(32);function gc(r,e,t,i,s){const n=r(e,t,Qb),o=Gb.create(n);s&&fc(o,s),fc(o,i);const a=new Uint8Array(16),c=Tb(a);dc(c,0,BigInt(s?s.length:0),!0),dc(c,8,BigInt(i.length),!0),o.update(a);const u=o.digest();return Hr(n,a),u}const Xb=r=>(e,t,i)=>({encrypt(s,n){const o=s.length;n=hc(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);r(e,t,a,a,1);const c=gc(r,e,t,a,i);return n.set(c,o),Hr(c),n},decrypt(s,n){n=hc(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=gc(r,e,t,o,i);if(!Bb(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),r(e,t,n,n,1),Hr(c),n}}),wh=Ub({blockSize:64,nonceLength:12,tagLength:16},Xb(Jb));let bh=class extends jo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,No(e);const i=zr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Mr(this),this.iHash.update(e),this}digestInto(e){Mr(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:t,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const xs=(r,e,t)=>new bh(r,e).update(t).digest();xs.create=(r,e)=>new bh(r,e);function ev(r,e,t){return No(r),t===void 0&&(t=new Uint8Array(r.outputLen)),xs(r,zr(t),zr(e))}const un=new Uint8Array([0]),yc=new Uint8Array;function tv(r,e,t,i=32){if(No(r),Si(i),i>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(i/r.outputLen);t===void 0&&(t=yc);const n=new Uint8Array(s*r.outputLen),o=xs.create(r,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<s;u++)un[0]=u+1,a.update(u===0?yc:c).update(t).update(un).digestInto(c),n.set(c,r.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),un.fill(0),n.slice(0,i)}const rv=(r,e,t,i,s)=>tv(r,ev(r,e,t),i,s);function iv(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=i?4:0,u=i?0:4;r.setUint32(e+c,o,i),r.setUint32(e+u,a,i)}function sv(r,e,t){return r&e^~r&t}function nv(r,e,t){return r&e^r&t^e&t}let ov=class extends jo{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=an(this.buffer)}update(e){Mr(this);const{view:t,buffer:i,blockLen:s}=this;e=zr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=an(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Mr(this),oh(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)t[h]=0;iv(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=an(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(i),e}};const av=new Uint32Array([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]),qt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Lt=new Uint32Array(64);class cv extends ov{constructor(){super(64,32,8,!1),this.A=qt[0]|0,this.B=qt[1]|0,this.C=qt[2]|0,this.D=qt[3]|0,this.E=qt[4]|0,this.F=qt[5]|0,this.G=qt[6]|0,this.H=qt[7]|0}get(){const{A:e,B:t,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,t,i,s,n,o,a,c]}set(e,t,i,s,n,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Lt[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){const d=Lt[h-15],p=Lt[h-2],f=ft(d,7)^ft(d,18)^d>>>3,g=ft(p,17)^ft(p,19)^p>>>10;Lt[h]=g+Lt[h-7]+f+Lt[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const d=ft(a,6)^ft(a,11)^ft(a,25),p=l+d+sv(a,c,u)+av[h]+Lt[h]|0,f=(ft(i,2)^ft(i,13)^ft(i,22))+nv(i,s,n)|0;l=u,u=c,c=a,a=o+p|0,o=n,n=s,s=i,i=p+f|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(i,s,n,o,a,c,u,l)}roundClean(){Lt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const ji=ah(()=>new cv);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Cs=BigInt(0),Ts=BigInt(1),uv=BigInt(2);function lr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Bi(r){if(!lr(r))throw new Error("Uint8Array expected")}function Vr(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}const lv=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Kr(r){Bi(r);let e="";for(let t=0;t<r.length;t++)e+=lv[r[t]];return e}function Fr(r){const e=r.toString(16);return e.length&1?"0"+e:e}function Uo(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Cs:BigInt("0x"+r)}const Pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function mc(r){if(r>=Pt._0&&r<=Pt._9)return r-Pt._0;if(r>=Pt.A&&r<=Pt.F)return r-(Pt.A-10);if(r>=Pt.a&&r<=Pt.f)return r-(Pt.a-10)}function Wr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);const e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=mc(r.charCodeAt(n)),a=mc(r.charCodeAt(n+1));if(o===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function or(r){return Uo(Kr(r))}function Oi(r){return Bi(r),Uo(Kr(Uint8Array.from(r).reverse()))}function Gr(r,e){return Wr(r.toString(16).padStart(e*2,"0"))}function Rs(r,e){return Gr(r,e).reverse()}function hv(r){return Wr(Fr(r))}function Ve(r,e,t){let i;if(typeof e=="string")try{i=Wr(e)}catch(n){throw new Error(r+" must be hex string or Uint8Array, cause: "+n)}else if(lr(e))i=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");const s=i.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return i}function Pi(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Bi(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}function dv(r,e){if(r.length!==e.length)return!1;let t=0;for(let i=0;i<r.length;i++)t|=r[i]^e[i];return t===0}function pv(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}const ln=r=>typeof r=="bigint"&&Cs<=r;function Ns(r,e,t){return ln(r)&&ln(e)&&ln(t)&&e<=r&&r<t}function Rt(r,e,t,i){if(!Ns(e,t,i))throw new Error("expected valid "+r+": "+t+" <= n < "+i+", got "+e)}function vh(r){let e;for(e=0;r>Cs;r>>=Ts,e+=1);return e}function fv(r,e){return r>>BigInt(e)&Ts}function gv(r,e,t){return r|(t?Ts:Cs)<<BigInt(e)}const Fo=r=>(uv<<BigInt(r-1))-Ts,hn=r=>new Uint8Array(r),wc=r=>Uint8Array.from(r);function Eh(r,e,t){if(typeof r!="number"||r<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 t!="function")throw new Error("hmacFn must be a function");let i=hn(r),s=hn(r),n=0;const o=()=>{i.fill(1),s.fill(0),n=0},a=(...l)=>t(s,i,...l),c=(l=hn())=>{s=a(wc([0]),l),i=a(),l.length!==0&&(s=a(wc([1]),l),i=a())},u=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<e;){i=a();const d=i.slice();h.push(d),l+=i.length}return Pi(...h)};return(l,h)=>{o(),c(l);let d;for(;!(d=h(u()));)c();return o(),d}}const yv={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||lr(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ei(r,e,t={}){const i=(s,n,o)=>{const a=yv[n];if(typeof a!="function")throw new Error("invalid validator function");const c=r[s];if(!(o&&c===void 0)&&!a(c,r))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(t))i(s,n,!0);return r}const mv=()=>{throw new Error("not implemented")};function Jn(r){const e=new WeakMap;return(t,...i)=>{const s=e.get(t);if(s!==void 0)return s;const n=r(t,...i);return e.set(t,n),n}}var wv=Object.freeze({__proto__:null,isBytes:lr,abytes:Bi,abool:Vr,bytesToHex:Kr,numberToHexUnpadded:Fr,hexToNumber:Uo,hexToBytes:Wr,bytesToNumberBE:or,bytesToNumberLE:Oi,numberToBytesBE:Gr,numberToBytesLE:Rs,numberToVarBytesBE:hv,ensureBytes:Ve,concatBytes:Pi,equalBytes:dv,utf8ToBytes:pv,inRange:Ns,aInRange:Rt,bitLen:vh,bitGet:fv,bitSet:gv,bitMask:Fo,createHmacDrbg:Eh,validateObject:ei,notImplemented:mv,memoized:Jn});const ve=BigInt(0),ue=BigInt(1),tr=BigInt(2),bv=BigInt(3),Zn=BigInt(4),bc=BigInt(5),vc=BigInt(8);function qe(r,e){const t=r%e;return t>=ve?t:e+t}function _h(r,e,t){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(t<=ve)throw new Error("invalid modulus");if(t===ue)return ve;let i=ue;for(;e>ve;)e&ue&&(i=i*r%t),r=r*r%t,e>>=ue;return i}function ut(r,e,t){let i=r;for(;e-- >ve;)i*=i,i%=t;return i}function Qn(r,e){if(r===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let t=qe(r,e),i=e,s=ve,n=ue;for(;t!==ve;){const o=i/t,a=i%t,c=s-n*o;i=t,t=a,s=n,n=c}if(i!==ue)throw new Error("invert: does not exist");return qe(s,e)}function vv(r){const e=(r-ue)/tr;let t,i,s;for(t=r-ue,i=0;t%tr===ve;t/=tr,i++);for(s=tr;s<r&&_h(s,e,r)!==r-ue;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(r+ue)/Zn;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(t+ue)/tr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),t),l=o.pow(a,n),h=o.pow(a,t);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,ue<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function Ev(r){if(r%Zn===bv){const e=(r+ue)/Zn;return function(t,i){const s=t.pow(i,e);if(!t.eql(t.sqr(s),i))throw new Error("Cannot find square root");return s}}if(r%vc===bc){const e=(r-bc)/vc;return function(t,i){const s=t.mul(i,tr),n=t.pow(s,e),o=t.mul(i,n),a=t.mul(t.mul(o,tr),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),i))throw new Error("Cannot find square root");return c}}return vv(r)}const _v=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Iv(r){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=_v.reduce((i,s)=>(i[s]="function",i),e);return ei(r,t)}function Sv(r,e,t){if(t<ve)throw new Error("invalid exponent, negatives unsupported");if(t===ve)return r.ONE;if(t===ue)return e;let i=r.ONE,s=e;for(;t>ve;)t&ue&&(i=r.mul(i,s)),s=r.sqr(s),t>>=ue;return i}function Dv(r,e){const t=new Array(e.length),i=e.reduce((n,o,a)=>r.is0(o)?n:(t[a]=n,r.mul(n,o)),r.ONE),s=r.inv(i);return e.reduceRight((n,o,a)=>r.is0(o)?n:(t[a]=r.mul(n,t[a]),r.mul(n,o)),s),t}function Ih(r,e){const t=e!==void 0?e:r.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function Sh(r,e,t=!1,i={}){if(r<=ve)throw new Error("invalid field: expected ORDER > 0, got "+r);const{nBitLength:s,nByteLength:n}=Ih(r,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:r,isLE:t,BITS:s,BYTES:n,MASK:Fo(s),ZERO:ve,ONE:ue,create:c=>qe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<r},is0:c=>c===ve,isOdd:c=>(c&ue)===ue,neg:c=>qe(-c,r),eql:(c,u)=>c===u,sqr:c=>qe(c*c,r),add:(c,u)=>qe(c+u,r),sub:(c,u)=>qe(c-u,r),mul:(c,u)=>qe(c*u,r),pow:(c,u)=>Sv(a,c,u),div:(c,u)=>qe(c*Qn(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Qn(c,r),sqrt:i.sqrt||(c=>(o||(o=Ev(r)),o(a,c))),invertBatch:c=>Dv(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>t?Rs(c,n):Gr(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Oi(c):or(c)}});return Object.freeze(a)}function Dh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function Oh(r){const e=Dh(r);return e+Math.ceil(e/2)}function Ov(r,e,t=!1){const i=r.length,s=Dh(e),n=Oh(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=t?Oi(r):or(r),a=qe(o,e-ue)+ue;return t?Rs(a,s):Gr(a,s)}const Ec=BigInt(0),Gi=BigInt(1);function dn(r,e){const t=e.negate();return r?t:e}function Ph(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function pn(r,e){Ph(r,e);const t=Math.ceil(e/r)+1,i=2**(r-1);return{windows:t,windowSize:i}}function Pv(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function $v(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const fn=new WeakMap,$h=new WeakMap;function gn(r){return $h.get(r)||1}function Av(r,e){return{constTimeNegate:dn,hasPrecomputes(t){return gn(t)!==1},unsafeLadder(t,i,s=r.ZERO){let n=t;for(;i>Ec;)i&Gi&&(s=s.add(n)),n=n.double(),i>>=Gi;return s},precomputeWindow(t,i){const{windows:s,windowSize:n}=pn(i,e),o=[];let a=t,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,i,s){const{windows:n,windowSize:o}=pn(t,e);let a=r.ZERO,c=r.BASE;const u=BigInt(2**t-1),l=2**t,h=BigInt(t);for(let d=0;d<n;d++){const p=d*o;let f=Number(s&u);s>>=h,f>o&&(f-=l,s+=Gi);const g=p,w=p+Math.abs(f)-1,E=d%2!==0,b=f<0;f===0?c=c.add(dn(E,i[g])):a=a.add(dn(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(t,i,s,n=r.ZERO){const{windows:o,windowSize:a}=pn(t,e),c=BigInt(2**t-1),u=2**t,l=BigInt(t);for(let h=0;h<o;h++){const d=h*a;if(s===Ec)break;let p=Number(s&c);if(s>>=l,p>a&&(p-=u,s+=Gi),p===0)continue;let f=i[d+Math.abs(p)-1];p<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(t,i,s){let n=fn.get(i);return n||(n=this.precomputeWindow(i,t),t!==1&&fn.set(i,s(n))),n},wNAFCached(t,i,s){const n=gn(t);return this.wNAF(n,this.getPrecomputes(n,t,s),i)},wNAFCachedUnsafe(t,i,s,n){const o=gn(t);return o===1?this.unsafeLadder(t,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),i,n)},setWindowSize(t,i){Ph(i,e),$h.set(t,i),fn.delete(t)}}}function xv(r,e,t,i){if(Pv(t,r),$v(i,e),t.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=r.ZERO,n=vh(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let p=0;p<i.length;p++){const f=i[p],g=Number(f>>BigInt(h)&BigInt(a));c[g]=c[g].add(t[p])}let d=s;for(let p=c.length-1,f=s;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Ah(r){return Iv(r.Fp),ei(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ih(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const _r=BigInt(0),yn=BigInt(1);function Cv(r){return ei(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Tv(r){const e=Cv(r),{P:t}=e,i=b=>qe(b,t),s=e.montgomeryBits,n=Math.ceil(s/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>_h(b,t-BigInt(2),t));function u(b,_,A){const T=i(b*(_-A));return _=i(_-T),A=i(A+T),[_,A]}const l=(e.a-BigInt(2))/BigInt(4);function h(b,_){Rt("u",b,_r,t),Rt("scalar",_,_r,t);const A=_,T=b;let v=yn,I=_r,P=b,D=yn,j=_r,N;for(let M=BigInt(s-1);M>=_r;M--){const $=A>>M&yn;j^=$,N=u(j,v,P),v=N[0],P=N[1],N=u(j,I,D),I=N[0],D=N[1],j=$;const y=v+I,m=i(y*y),S=v-I,x=i(S*S),O=m-x,C=P+D,q=P-D,k=i(q*y),z=i(C*S),L=k+z,H=k-z;P=i(L*L),D=i(T*i(H*H)),v=i(m*x),I=i(O*(m+i(l*O)))}N=u(j,v,P),v=N[0],P=N[1],N=u(j,I,D),I=N[0],D=N[1];const B=c(I);return i(v*B)}function d(b){return Rs(i(b),n)}function p(b){const _=Ve("u coordinate",b,n);return o===32&&(_[31]&=127),Oi(_)}function f(b){const _=Ve("scalar",b),A=_.length;if(A!==n&&A!==o){let T=""+n+" or "+o;throw new Error("invalid scalar, expected "+T+" bytes, got "+A)}return Oi(a(_))}function g(b,_){const A=p(_),T=f(b),v=h(A,T);if(v===_r)throw new Error("invalid private or public key received");return d(v)}const w=d(e.Gu);function E(b){return g(b,w)}return{scalarMult:g,scalarMultBase:E,getSharedSecret:(b,_)=>g(b,_),getPublicKey:b=>E(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:w}}const Xn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Rv=BigInt(1),_c=BigInt(2),Nv=BigInt(3),jv=BigInt(5);BigInt(8);function Bv(r){const e=BigInt(10),t=BigInt(20),i=BigInt(40),s=BigInt(80),n=Xn,o=r*r%n*r%n,a=ut(o,_c,n)*o%n,c=ut(a,Rv,n)*r%n,u=ut(c,jv,n)*c%n,l=ut(u,e,n)*u%n,h=ut(l,t,n)*l%n,d=ut(h,i,n)*h%n,p=ut(d,s,n)*d%n,f=ut(p,s,n)*d%n,g=ut(f,e,n)*u%n;return{pow_p_5_8:ut(g,_c,n)*r%n,b2:o}}function Uv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}const eo=Tv({P:Xn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{const e=Xn,{pow_p_5_8:t,b2:i}=Bv(r);return qe(ut(t,Nv,e)*i,e)},adjustScalarBytes:Uv,randomBytes:Xr});function Ic(r){r.lowS!==void 0&&Vr("lowS",r.lowS),r.prehash!==void 0&&Vr("prehash",r.prehash)}function Fv(r){const e=Ah(r);ei(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:i,a:s}=e;if(t){if(!i.eql(s,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:qv,hexToBytes:Lv}=wv;class kv extends Error{constructor(e=""){super(e)}}const Ct={Err:kv,_tlv:{encode:(r,e)=>{const{Err:t}=Ct;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const i=e.length/2,s=Fr(i);if(s.length/2&128)throw new t("tlv.encode: long form length too big");const n=i>127?Fr(s.length/2|128):"";return Fr(r)+n+s+e},decode(r,e){const{Err:t}=Ct;let i=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[i++]!==r)throw new t("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const u=e.subarray(i,i+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(i+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(r){const{Err:e}=Ct;if(r<Tt)throw new e("integer: negative integers are not allowed");let t=Fr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){const{Err:e}=Ct;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return qv(r)}},toSig(r){const{Err:e,_int:t,_tlv:i}=Ct,s=typeof r=="string"?Lv(r):r;Bi(s);const{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:u,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){const{_tlv:e,_int:t}=Ct,i=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),n=i+s;return e.encode(48,n)}},Tt=BigInt(0),me=BigInt(1);BigInt(2);const Sc=BigInt(3);BigInt(4);function Mv(r){const e=Fv(r),{Fp:t}=e,i=Sh(e.n,e.nBitLength),s=e.toBytes||((g,w,E)=>{const b=w.toAffine();return Pi(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),n=e.fromBytes||(g=>{const w=g.subarray(1),E=t.fromBytes(w.subarray(0,t.BYTES)),b=t.fromBytes(w.subarray(t.BYTES,2*t.BYTES));return{x:E,y:b}});function o(g){const{a:w,b:E}=e,b=t.sqr(g),_=t.mul(b,g);return t.add(t.add(_,t.mul(g,w)),E)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return Ns(g,me,e.n)}function c(g){const{allowedPrivateKeyLengths:w,nByteLength:E,wrapPrivateKey:b,n:_}=e;if(w&&typeof g!="bigint"){if(lr(g)&&(g=Kr(g)),typeof g!="string"||!w.includes(g.length))throw new Error("invalid private key");g=g.padStart(E*2,"0")}let A;try{A=typeof g=="bigint"?g:or(Ve("private key",g,E))}catch{throw new Error("invalid private key, expected hex or "+E+" bytes, got "+typeof g)}return b&&(A=qe(A,_)),Rt("private key",A,me,_),A}function u(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}const l=Jn((g,w)=>{const{px:E,py:b,pz:_}=g;if(t.eql(_,t.ONE))return{x:E,y:b};const A=g.is0();w==null&&(w=A?t.ONE:t.inv(_));const T=t.mul(E,w),v=t.mul(b,w),I=t.mul(_,w);if(A)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:T,y:v}}),h=Jn(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}const{x:w,y:E}=g.toAffine();if(!t.isValid(w)||!t.isValid(E))throw new Error("bad point: x or y not FE");const b=t.sqr(E),_=o(w);if(!t.eql(b,_))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(w,E,b){if(this.px=w,this.py=E,this.pz=b,w==null||!t.isValid(w))throw new Error("x required");if(E==null||!t.isValid(E))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(w){const{x:E,y:b}=w||{};if(!w||!t.isValid(E)||!t.isValid(b))throw new Error("invalid affine point");if(w instanceof d)throw new Error("projective point not allowed");const _=A=>t.eql(A,t.ZERO);return _(E)&&_(b)?d.ZERO:new d(E,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const E=t.invertBatch(w.map(b=>b.pz));return w.map((b,_)=>b.toAffine(E[_])).map(d.fromAffine)}static fromHex(w){const E=d.fromAffine(n(Ve("pointHex",w)));return E.assertValidity(),E}static fromPrivateKey(w){return d.BASE.multiply(c(w))}static msm(w,E){return xv(d,i,w,E)}_setWindowSize(w){f.setWindowSize(this,w)}assertValidity(){h(this)}hasEvenY(){const{y:w}=this.toAffine();if(t.isOdd)return!t.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){u(w);const{px:E,py:b,pz:_}=this,{px:A,py:T,pz:v}=w,I=t.eql(t.mul(E,v),t.mul(A,_)),P=t.eql(t.mul(b,v),t.mul(T,_));return I&&P}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){const{a:w,b:E}=e,b=t.mul(E,Sc),{px:_,py:A,pz:T}=this;let v=t.ZERO,I=t.ZERO,P=t.ZERO,D=t.mul(_,_),j=t.mul(A,A),N=t.mul(T,T),B=t.mul(_,A);return B=t.add(B,B),P=t.mul(_,T),P=t.add(P,P),v=t.mul(w,P),I=t.mul(b,N),I=t.add(v,I),v=t.sub(j,I),I=t.add(j,I),I=t.mul(v,I),v=t.mul(B,v),P=t.mul(b,P),N=t.mul(w,N),B=t.sub(D,N),B=t.mul(w,B),B=t.add(B,P),P=t.add(D,D),D=t.add(P,D),D=t.add(D,N),D=t.mul(D,B),I=t.add(I,D),N=t.mul(A,T),N=t.add(N,N),D=t.mul(N,B),v=t.sub(v,D),P=t.mul(N,j),P=t.add(P,P),P=t.add(P,P),new d(v,I,P)}add(w){u(w);const{px:E,py:b,pz:_}=this,{px:A,py:T,pz:v}=w;let I=t.ZERO,P=t.ZERO,D=t.ZERO;const j=e.a,N=t.mul(e.b,Sc);let B=t.mul(E,A),M=t.mul(b,T),$=t.mul(_,v),y=t.add(E,b),m=t.add(A,T);y=t.mul(y,m),m=t.add(B,M),y=t.sub(y,m),m=t.add(E,_);let S=t.add(A,v);return m=t.mul(m,S),S=t.add(B,$),m=t.sub(m,S),S=t.add(b,_),I=t.add(T,v),S=t.mul(S,I),I=t.add(M,$),S=t.sub(S,I),D=t.mul(j,m),I=t.mul(N,$),D=t.add(I,D),I=t.sub(M,D),D=t.add(M,D),P=t.mul(I,D),M=t.add(B,B),M=t.add(M,B),$=t.mul(j,$),m=t.mul(N,m),M=t.add(M,$),$=t.sub(B,$),$=t.mul(j,$),m=t.add(m,$),B=t.mul(M,m),P=t.add(P,B),B=t.mul(S,m),I=t.mul(y,I),I=t.sub(I,B),B=t.mul(y,M),D=t.mul(S,D),D=t.add(D,B),new d(I,P,D)}subtract(w){return this.add(w.negate())}is0(){return this.equals(d.ZERO)}wNAF(w){return f.wNAFCached(this,w,d.normalizeZ)}multiplyUnsafe(w){const{endo:E,n:b}=e;Rt("scalar",w,Tt,b);const _=d.ZERO;if(w===Tt)return _;if(this.is0()||w===me)return this;if(!E||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,w,d.normalizeZ);let{k1neg:A,k1:T,k2neg:v,k2:I}=E.splitScalar(w),P=_,D=_,j=this;for(;T>Tt||I>Tt;)T&me&&(P=P.add(j)),I&me&&(D=D.add(j)),j=j.double(),T>>=me,I>>=me;return A&&(P=P.negate()),v&&(D=D.negate()),D=new d(t.mul(D.px,E.beta),D.py,D.pz),P.add(D)}multiply(w){const{endo:E,n:b}=e;Rt("scalar",w,me,b);let _,A;if(E){const{k1neg:T,k1:v,k2neg:I,k2:P}=E.splitScalar(w);let{p:D,f:j}=this.wNAF(v),{p:N,f:B}=this.wNAF(P);D=f.constTimeNegate(T,D),N=f.constTimeNegate(I,N),N=new d(t.mul(N.px,E.beta),N.py,N.pz),_=D.add(N),A=j.add(B)}else{const{p:T,f:v}=this.wNAF(w);_=T,A=v}return d.normalizeZ([_,A])[0]}multiplyAndAddUnsafe(w,E,b){const _=d.BASE,A=(v,I)=>I===Tt||I===me||!v.equals(_)?v.multiplyUnsafe(I):v.multiply(I),T=A(this,E).add(A(w,b));return T.is0()?void 0:T}toAffine(w){return l(this,w)}isTorsionFree(){const{h:w,isTorsionFree:E}=e;if(w===me)return!0;if(E)return E(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:E}=e;return w===me?this:E?E(d,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return Vr("isCompressed",w),this.assertValidity(),s(d,this,w)}toHex(w=!0){return Vr("isCompressed",w),Kr(this.toRawBytes(w))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);const p=e.nBitLength,f=Av(d,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function zv(r){const e=Ah(r);return ei(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Hv(r){const e=zv(r),{Fp:t,n:i}=e,s=t.BYTES+1,n=2*t.BYTES+1;function o($){return qe($,i)}function a($){return Qn($,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=Mv({...e,toBytes($,y,m){const S=y.toAffine(),x=t.toBytes(S.x),O=Pi;return Vr("isCompressed",m),m?O(Uint8Array.from([y.hasEvenY()?2:3]),x):O(Uint8Array.from([4]),x,t.toBytes(S.y))},fromBytes($){const y=$.length,m=$[0],S=$.subarray(1);if(y===s&&(m===2||m===3)){const x=or(S);if(!Ns(x,me,t.ORDER))throw new Error("Point is not on curve");const O=l(x);let C;try{C=t.sqrt(O)}catch(k){const z=k instanceof Error?": "+k.message:"";throw new Error("Point is not on curve"+z)}const q=(C&me)===me;return(m&1)===1!==q&&(C=t.neg(C)),{x,y:C}}else if(y===n&&m===4){const x=t.fromBytes(S.subarray(0,t.BYTES)),O=t.fromBytes(S.subarray(t.BYTES,2*t.BYTES));return{x,y:O}}else{const x=s,O=n;throw new Error("invalid Point, expected length of "+x+", or uncompressed "+O+", got "+y)}}}),d=$=>Kr(Gr($,e.nByteLength));function p($){const y=i>>me;return $>y}function f($){return p($)?o(-$):$}const g=($,y,m)=>or($.slice(y,m));class w{constructor(y,m,S){this.r=y,this.s=m,this.recovery=S,this.assertValidity()}static fromCompact(y){const m=e.nByteLength;return y=Ve("compactSignature",y,m*2),new w(g(y,0,m),g(y,m,2*m))}static fromDER(y){const{r:m,s:S}=Ct.toSig(Ve("DER",y));return new w(m,S)}assertValidity(){Rt("r",this.r,me,i),Rt("s",this.s,me,i)}addRecoveryBit(y){return new w(this.r,this.s,y)}recoverPublicKey(y){const{r:m,s:S,recovery:x}=this,O=v(Ve("msgHash",y));if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");const C=x===2||x===3?m+e.n:m;if(C>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const q=(x&1)===0?"02":"03",k=c.fromHex(q+d(C)),z=a(C),L=o(-O*z),H=o(S*z),V=c.BASE.multiplyAndAddUnsafe(k,L,H);if(!V)throw new Error("point at infinify");return V.assertValidity(),V}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Wr(this.toDERHex())}toDERHex(){return Ct.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Wr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const E={isValidPrivateKey($){try{return u($),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const $=Oh(e.n);return Ov(e.randomBytes($),e.n)},precompute($=8,y=c.BASE){return y._setWindowSize($),y.multiply(BigInt(3)),y}};function b($,y=!0){return c.fromPrivateKey($).toRawBytes(y)}function _($){const y=lr($),m=typeof $=="string",S=(y||m)&&$.length;return y?S===s||S===n:m?S===2*s||S===2*n:$ instanceof c}function A($,y,m=!0){if(_($))throw new Error("first arg must be private key");if(!_(y))throw new Error("second arg must be public key");return c.fromHex(y).multiply(u($)).toRawBytes(m)}const T=e.bits2int||function($){if($.length>8192)throw new Error("input is too large");const y=or($),m=$.length*8-e.nBitLength;return m>0?y>>BigInt(m):y},v=e.bits2int_modN||function($){return o(T($))},I=Fo(e.nBitLength);function P($){return Rt("num < 2^"+e.nBitLength,$,Tt,I),Gr($,e.nByteLength)}function D($,y,m=j){if(["recovered","canonical"].some(ee=>ee in m))throw new Error("sign() legacy options not supported");const{hash:S,randomBytes:x}=e;let{lowS:O,prehash:C,extraEntropy:q}=m;O==null&&(O=!0),$=Ve("msgHash",$),Ic(m),C&&($=Ve("prehashed msgHash",S($)));const k=v($),z=u(y),L=[P(z),P(k)];if(q!=null&&q!==!1){const ee=q===!0?x(t.BYTES):q;L.push(Ve("extraEntropy",ee))}const H=Pi(...L),V=k;function ne(ee){const Y=T(ee);if(!h(Y))return;const Ae=a(Y),Ee=c.BASE.multiply(Y).toAffine(),Ce=o(Ee.x);if(Ce===Tt)return;const Je=o(Ae*o(V+Ce*z));if(Je===Tt)return;let Ze=(Ee.x===Ce?0:2)|Number(Ee.y&me),mr=Je;return O&&p(Je)&&(mr=f(Je),Ze^=1),new w(Ce,mr,Ze)}return{seed:H,k2sig:ne}}const j={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function B($,y,m=j){const{seed:S,k2sig:x}=D($,y,m),O=e;return Eh(O.hash.outputLen,O.nByteLength,O.hmac)(S,x)}c.BASE._setWindowSize(8);function M($,y,m,S=N){var Je;const x=$;y=Ve("msgHash",y),m=Ve("publicKey",m);const{lowS:O,prehash:C,format:q}=S;if(Ic(S),"strict"in S)throw new Error("options.strict was renamed to lowS");if(q!==void 0&&q!=="compact"&&q!=="der")throw new Error("format must be compact or der");const k=typeof x=="string"||lr(x),z=!k&&!q&&typeof x=="object"&&x!==null&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!k&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let L,H;try{if(z&&(L=new w(x.r,x.s)),k){try{q!=="compact"&&(L=w.fromDER(x))}catch(Ze){if(!(Ze instanceof Ct.Err))throw Ze}!L&&q!=="der"&&(L=w.fromCompact(x))}H=c.fromHex(m)}catch{return!1}if(!L||O&&L.hasHighS())return!1;C&&(y=e.hash(y));const{r:V,s:ne}=L,ee=v(y),Y=a(ne),Ae=o(ee*Y),Ee=o(V*Y),Ce=(Je=c.BASE.multiplyAndAddUnsafe(H,Ae,Ee))==null?void 0:Je.toAffine();return Ce?o(Ce.x)===V:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:A,sign:B,verify:M,ProjectivePoint:c,Signature:w,utils:E}}function Vv(r){return{hash:r,hmac:(e,...t)=>xs(r,e,Yw(...t)),randomBytes:Xr}}function Kv(r,e){const t=i=>Hv({...r,...Vv(i)});return{...t(e),create:t}}const xh=Sh(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Wv=xh.create(BigInt("-3")),Gv=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Yv=Kv({a:Wv,b:Gv,Fp:xh,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ji),Ch="base10",Re="base16",lt="base64pad",Mt="base64url",Ui="utf8",Th=0,Nt=1,Fi=2,Jv=0,Dc=1,wi=12,qo=32;function Zv(){const r=eo.utils.randomPrivateKey(),e=eo.getPublicKey(r);return{privateKey:Le(r,Re),publicKey:Le(e,Re)}}function to(){const r=Xr(qo);return Le(r,Re)}function Qv(r,e){const t=eo.getSharedSecret(rt(r,Re),rt(e,Re)),i=rv(ji,t,void 0,void 0,qo);return Le(i,Re)}function as(r){const e=ji(rt(r,Re));return Le(e,Re)}function Et(r){const e=ji(rt(r,Ui));return Le(e,Re)}function Rh(r){return rt(`${r}`,Ch)}function hr(r){return Number(Le(r,Ch))}function Nh(r){return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function jh(r){const e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Xv(r){const e=Rh(typeof r.type<"u"?r.type:Th);if(hr(e)===Nt&&typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof r.senderPublicKey<"u"?rt(r.senderPublicKey,Re):void 0,i=typeof r.iv<"u"?rt(r.iv,Re):Xr(wi),s=rt(r.symKey,Re),n=wh(s,i).encrypt(rt(r.message,Ui)),o=Bh({type:e,sealed:n,iv:i,senderPublicKey:t});return r.encoding===Mt?Nh(o):o}function e0(r){const e=rt(r.symKey,Re),{sealed:t,iv:i}=$i({encoded:r.encoded,encoding:r.encoding}),s=wh(e,i).decrypt(t);if(s===null)throw new Error("Failed to decrypt");return Le(s,Ui)}function t0(r,e){const t=Rh(Fi),i=Xr(wi),s=rt(r,Ui),n=Bh({type:t,sealed:s,iv:i});return e===Mt?Nh(n):n}function r0(r,e){const{sealed:t}=$i({encoded:r,encoding:e});return Le(t,Ui)}function Bh(r){if(hr(r.type)===Fi)return Le(mi([r.type,r.sealed]),lt);if(hr(r.type)===Nt){if(typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Le(mi([r.type,r.senderPublicKey,r.iv,r.sealed]),lt)}return Le(mi([r.type,r.iv,r.sealed]),lt)}function $i(r){const e=(r.encoding||lt)===Mt?jh(r.encoded):r.encoded,t=rt(e,lt),i=t.slice(Jv,Dc),s=Dc;if(hr(i)===Nt){const c=s+qo,u=c+wi,l=t.slice(s,c),h=t.slice(c,u),d=t.slice(u);return{type:i,sealed:d,iv:h,senderPublicKey:l}}if(hr(i)===Fi){const c=t.slice(s),u=Xr(wi);return{type:i,sealed:c,iv:u}}const n=s+wi,o=t.slice(s,n),a=t.slice(n);return{type:i,sealed:a,iv:o}}function i0(r,e){const t=$i({encoded:r,encoding:e==null?void 0:e.encoding});return Uh({type:hr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Le(t.senderPublicKey,Re):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Uh(r){const e=(r==null?void 0:r.type)||Th;if(e===Nt){if(typeof(r==null?void 0:r.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(r==null?void 0:r.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:r==null?void 0:r.senderPublicKey,receiverPublicKey:r==null?void 0:r.receiverPublicKey}}function Oc(r){return r.type===Nt&&typeof r.senderPublicKey=="string"&&typeof r.receiverPublicKey=="string"}function Pc(r){return r.type===Fi}function s0(r){const e=Buffer.from(r.x,"base64"),t=Buffer.from(r.y,"base64");return mi([new Uint8Array([4]),e,t])}function n0(r,e){const[t,i,s]=r.split("."),n=Buffer.from(jh(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${i}`,u=ji(c),l=s0(e);if(!Yv.verify(mi([o,a]),u,l))throw new Error("Invalid signature");return zn(r).payload}const o0="irn";function ms(r){return(r==null?void 0:r.relay)||{protocol:o0}}function gi(r){const e=hw[r];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${r}`);return e}function a0(r,e="-"){const t={},i="relay"+e;return Object.keys(r).forEach(s=>{if(s.startsWith(i)){const n=s.replace(i,""),o=r[s];t[n]=o}}),t}function $c(r){if(!r.includes("wc:")){const u=nh(r);u!=null&&u.includes("wc:")&&(r=u)}r=r.includes("wc://")?r.replace("wc://",""):r,r=r.includes("wc:")?r.replace("wc:",""):r;const e=r.indexOf(":"),t=r.indexOf("?")!==-1?r.indexOf("?"):void 0,i=r.substring(0,e),s=r.substring(e+1,t).split("@"),n=typeof t<"u"?r.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((u,l)=>{a[l]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:c0(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:a0(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function c0(r){return r.startsWith("//")?r.substring(2):r}function u0(r,e="-"){const t="relay",i={};return Object.keys(r).forEach(s=>{const n=s,o=t+e+n;r[n]&&(i[o]=r[n])}),i}function Ac(r){const e=new URLSearchParams,t=u0(r.relay);Object.keys(t).sort().forEach(s=>{e.set(s,t[s])}),e.set("symKey",r.symKey),r.expiryTimestamp&&e.set("expiryTimestamp",r.expiryTimestamp.toString()),r.methods&&e.set("methods",r.methods.join(","));const i=e.toString();return`${r.protocol}:${r.topic}@${r.version}?${i}`}function Yi(r,e,t){return`${r}?wc_ev=${t}&topic=${e}`}var l0=Object.defineProperty,h0=Object.defineProperties,d0=Object.getOwnPropertyDescriptors,xc=Object.getOwnPropertySymbols,p0=Object.prototype.hasOwnProperty,f0=Object.prototype.propertyIsEnumerable,Cc=(r,e,t)=>e in r?l0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g0=(r,e)=>{for(var t in e||(e={}))p0.call(e,t)&&Cc(r,t,e[t]);if(xc)for(var t of xc(e))f0.call(e,t)&&Cc(r,t,e[t]);return r},y0=(r,e)=>h0(r,d0(e));function ti(r){const e=[];return r.forEach(t=>{const[i,s]=t.split(":");e.push(`${i}:${s}`)}),e}function m0(r){const e=[];return Object.values(r).forEach(t=>{e.push(...ti(t.accounts))}),e}function w0(r,e){const t=[];return Object.values(r).forEach(i=>{ti(i.accounts).includes(e)&&t.push(...i.methods)}),t}function b0(r,e){const t=[];return Object.values(r).forEach(i=>{ti(i.accounts).includes(e)&&t.push(...i.events)}),t}function js(r){return r.includes(":")}function qr(r){return js(r)?r.split(":")[0]:r}function Tc(r){var e,t,i;const s={};if(!Kt(r))return s;for(const[n,o]of Object.entries(r)){const a=js(n)?[n]:o.chains,c=o.methods||[],u=o.events||[],l=qr(n);s[l]=y0(g0({},s[l]),{chains:_t(a,(e=s[l])==null?void 0:e.chains),methods:_t(c,(t=s[l])==null?void 0:t.methods),events:_t(u,(i=s[l])==null?void 0:i.events)})}return s}function v0(r){const e={};return r==null||r.forEach(t=>{var i;const[s,n]=t.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(t),(i=e[s].chains)==null||i.push(`${s}:${n}`)}),e}function Rc(r,e){e=e.map(i=>i.replace("did:pkh:",""));const t=v0(e);for(const[i,s]of Object.entries(t))s.methods?s.methods=_t(s.methods,r):s.methods=r,s.events=["chainChanged","accountsChanged"];return t}function E0(r,e){var t,i,s,n,o,a;const c=Tc(r),u=Tc(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const d of h)l[d]={chains:_t((t=c[d])==null?void 0:t.chains,(i=u[d])==null?void 0:i.chains),methods:_t((s=c[d])==null?void 0:s.methods,(n=u[d])==null?void 0:n.methods),events:_t((o=c[d])==null?void 0:o.events,(a=u[d])==null?void 0:a.events)};return l}const _0={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}},I0={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 F(r,e){const{message:t,code:i}=I0[r];return{message:e?`${t} ${e}`:t,code:i}}function te(r,e){const{message:t,code:i}=_0[r];return{message:e?`${t} ${e}`:t,code:i}}function ht(r,e){return!!Array.isArray(r)}function Kt(r){return Object.getPrototypeOf(r)===Object.prototype&&Object.keys(r).length}function De(r){return typeof r>"u"}function he(r,e){return e&&De(r)?!0:typeof r=="string"&&!!r.trim().length}function Lo(r,e){return e&&De(r)?!0:typeof r=="number"&&!isNaN(r)}function S0(r,e){const{requiredNamespaces:t}=e,i=Object.keys(r.namespaces),s=Object.keys(t);let n=!0;return sr(s,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:u}=r.namespaces[o],l=ti(a),h=t[o];(!sr(eh(o,h),l)||!sr(h.methods,c)||!sr(h.events,u))&&(n=!1)}),n):!1}function ws(r){return he(r,!1)&&r.includes(":")?r.split(":").length===2:!1}function D0(r){if(he(r,!1)&&r.includes(":")){const e=r.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&ws(t)}}return!1}function O0(r){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(he(r,!1)){if(e(r))return!0;const t=nh(r);return e(t)}}catch{}return!1}function P0(r){var e;return(e=r==null?void 0:r.proposer)==null?void 0:e.publicKey}function $0(r){return r==null?void 0:r.topic}function A0(r,e){let t=null;return he(r==null?void 0:r.publicKey,!1)||(t=F("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function Nc(r){let e=!0;return ht(r)?r.length&&(e=r.every(t=>he(t,!1))):e=!1,e}function x0(r,e,t){let i=null;return ht(e)&&e.length?e.forEach(s=>{i||ws(s)||(i=te("UNSUPPORTED_CHAINS",`${t}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):ws(r)||(i=te("UNSUPPORTED_CHAINS",`${t}, 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 C0(r,e,t){let i=null;return Object.entries(r).forEach(([s,n])=>{if(i)return;const o=x0(s,eh(s,n),`${e} ${t}`);o&&(i=o)}),i}function T0(r,e){let t=null;return ht(r)?r.forEach(i=>{t||D0(i)||(t=te("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function R0(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const s=T0(i==null?void 0:i.accounts,`${e} namespace`);s&&(t=s)}),t}function N0(r,e){let t=null;return Nc(r==null?void 0:r.methods)?Nc(r==null?void 0:r.events)||(t=te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Fh(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const s=N0(i,`${e}, namespace`);s&&(t=s)}),t}function j0(r,e,t){let i=null;if(r&&Kt(r)){const s=Fh(r,e);s&&(i=s);const n=C0(r,e,t);n&&(i=n)}else i=F("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function mn(r,e){let t=null;if(r&&Kt(r)){const i=Fh(r,e);i&&(t=i);const s=R0(r,e);s&&(t=s)}else t=F("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function qh(r){return he(r.protocol,!0)}function B0(r,e){let t=!1;return r?r&&ht(r)&&r.length&&r.forEach(i=>{t=qh(i)}):t=!0,t}function U0(r){return typeof r=="number"}function Fe(r){return typeof r<"u"&&typeof r!==null}function F0(r){return!(!r||typeof r!="object"||!r.code||!Lo(r.code,!1)||!r.message||!he(r.message,!1))}function q0(r){return!(De(r)||!he(r.method,!1))}function L0(r){return!(De(r)||De(r.result)&&De(r.error)||!Lo(r.id,!1)||!he(r.jsonrpc,!1))}function k0(r){return!(De(r)||!he(r.name,!1))}function jc(r,e){return!(!ws(e)||!m0(r).includes(e))}function M0(r,e,t){return he(t,!1)?w0(r,e).includes(t):!1}function z0(r,e,t){return he(t,!1)?b0(r,e).includes(t):!1}function Bc(r,e,t){let i=null;const s=H0(r),n=V0(e),o=Object.keys(s),a=Object.keys(n),c=Uc(Object.keys(r)),u=Uc(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(i=F("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
@@ -36,4 +36,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
|
36
36
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
37
37
|
PERFORMANCE OF THIS SOFTWARE.
|
|
38
38
|
***************************************************************************** */var io=function(r,e){return io=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])},io(r,e)};function E1(r,e){io(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var so=function(){return so=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++){t=arguments[i];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},so.apply(this,arguments)};function _1(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(r);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(r,i[s])&&(t[i[s]]=r[i[s]]);return t}function I1(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(n=(s<3?o(n):s>3?o(e,t,n):o(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}function S1(r,e){return function(t,i){e(t,i,r)}}function D1(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function O1(r,e,t,i){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):s(l.value).then(a,c)}u((i=i.apply(r,e||[])).next())})}function P1(r,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,s=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){t.label=u[1];break}if(u[0]===6&&t.label<n[1]){t.label=n[1],n=u;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(u);break}n[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(l){u=[6,l],s=0}finally{i=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function $1(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function A1(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function no(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vh(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return n}function x1(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Vh(arguments[e]));return r}function C1(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),s=0,e=0;e<t;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Ai(r){return this instanceof Ai?(this.v=r,this):new Ai(r)}function T1(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(p){return new Promise(function(f,g){n.push([d,p,f,g])>1||a(d,p)})})}function a(d,p){try{c(i[d](p))}catch(f){h(n[0][3],f)}}function c(d){d.value instanceof Ai?Promise.resolve(d.value.v).then(u,l):h(n[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function R1(r){var e,t;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=r[s]?function(o){return(t=!t)?{value:Ai(r[s](o)),done:s==="return"}:n?n(o):o}:n}}function N1(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof no=="function"?no(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=r[n]&&function(o){return new Promise(function(a,c){o=r[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function j1(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function B1(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function U1(r){return r&&r.__esModule?r:{default:r}}function F1(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function q1(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const L1=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return so},__asyncDelegator:R1,__asyncGenerator:T1,__asyncValues:N1,__await:Ai,__awaiter:O1,__classPrivateFieldGet:F1,__classPrivateFieldSet:q1,__createBinding:$1,__decorate:I1,__exportStar:A1,__extends:E1,__generator:P1,__importDefault:U1,__importStar:B1,__makeTemplateObject:j1,__metadata:D1,__param:S1,__read:Vh,__rest:_1,__spread:x1,__spreadArrays:C1,__values:no},Symbol.toStringTag,{value:"Module"})),k1=rl(L1);var $t={},Zc;function M1(){if(Zc)return $t;Zc=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.isBrowserCryptoAvailable=$t.getSubtleCrypto=$t.getBrowerCrypto=void 0;function r(){return(vt===null||vt===void 0?void 0:vt.crypto)||(vt===null||vt===void 0?void 0:vt.msCrypto)||{}}$t.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}$t.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return $t.isBrowserCryptoAvailable=t,$t}var At={},Qc;function z1(){if(Qc)return At;Qc=1,Object.defineProperty(At,"__esModule",{value:!0}),At.isBrowser=At.isNode=At.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}At.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}At.isNode=e;function t(){return!r()&&!e()}return At.isBrowser=t,At}var Xc;function H1(){return Xc||(Xc=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=k1;e.__exportStar(M1(),r),e.__exportStar(z1(),r)})(_n)),_n}var V1=H1();function wt(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function nr(r=6){return BigInt(wt(r))}function Ht(r,e,t){return{id:t||wt(),jsonrpc:"2.0",method:r,params:e}}function Us(r,e){return{id:r,jsonrpc:"2.0",result:e}}function Fs(r,e,t){return{id:r,jsonrpc:"2.0",error:K1(e)}}function K1(r,e){return typeof r>"u"?Jc(Mh):(typeof r=="string"&&(r=Object.assign(Object.assign({},Jc(Mo)),{message:r})),b1(r.code)&&(r=v1(r.code)),r)}class W1{}class G1 extends W1{constructor(){super()}}class Y1 extends G1{constructor(e){super()}}const J1="^https?:",Z1="^wss?:";function Q1(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Kh(r,e){const t=Q1(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function eu(r){return Kh(r,J1)}function tu(r){return Kh(r,Z1)}function X1(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function Wh(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function zo(r){return Wh(r)&&"method"in r}function qs(r){return Wh(r)&&(bt(r)||tt(r))}function bt(r){return"result"in r}function tt(r){return"error"in r}let it=class extends Y1{constructor(e){super(e),this.events=new Ye.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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Ht(e.method,e.params||[],e.id||nr().toString()),t)}async requestStrict(e,t){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{tt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,t)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),qs(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const e_=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),t_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",ru=r=>r.split("?")[0],iu=10,r_=e_();let i_=class{constructor(e){if(this.url=e,this.events=new Ye.EventEmitter,this.registering=!1,!tu(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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(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(Bt(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!tu(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const s=V1.isReactNative()?void 0:{rejectUnauthorized:!X1(e)},n=new r_(e,[],s);t_()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),t(n)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),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 t=typeof e.data=="string"?cr(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Fs(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return Hh(e,ru(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>iu&&this.events.setMaxListeners(iu)}emitError(e){const t=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${ru(this.url)}`));return this.events.emit("register_error",t),t}};var s_={};const Gh="wc",Yh=2,oo="core",It=`${Gh}@2:${oo}:`,n_={logger:"error"},o_={database:":memory:"},a_="crypto",su="client_ed25519_seed",c_=U.ONE_DAY,u_="keychain",l_="0.3",h_="messages",d_="0.3",nu=U.SIX_HOURS,p_="publisher",Jh="irn",f_="error",Zh="wss://relay.walletconnect.org",g_="relayer",we={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"},y_="_subscription",Qe={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},m_=.1,ao="2.21.1",ae={link_mode:"link_mode",relay:"relay"},ls={inbound:"inbound",outbound:"outbound"},w_="0.3",b_="WALLETCONNECT_CLIENT_ID",ou="WALLETCONNECT_LINK_MODE_APPS",He={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},v_="subscription",E_="0.3",__="pairing",I_="0.3",li={wc_pairingDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:U.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:U.ONE_DAY,prompt:!1,tag:0},res:{ttl:U.ONE_DAY,prompt:!1,tag:0}}},rr={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"},S_="history",D_="0.3",O_="expirer",et={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},P_="0.3",$_="verify-api",A_="https://verify.walletconnect.com",Qh="https://verify.walletconnect.org",vi=Qh,x_=`${vi}/v3`,C_=[A_,Qh],T_="echo",R_="https://echo.walletconnect.com",mt={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"},xt={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"},at={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"},Jt={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"},Zt={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},hi={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},N_=.1,j_="event-client",B_=86400,U_="https://pulse.walletconnect.org/batch";function F_(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,w=0,E=0,b=f.length;E!==b&&f[E]===0;)E++,g++;for(var _=(b-E)*l+1>>>0,A=new Uint8Array(_);E!==b;){for(var T=f[E],v=0,I=_-1;(T!==0||v<w)&&I!==-1;I--,v++)T+=256*A[I]>>>0,A[I]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=v,E++}for(var P=_-w;P!==_&&A[P]===0;)P++;for(var D=c.repeat(g);P<_;++P)D+=r.charAt(A[P]);return D}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var w=0,E=0;f[g]===c;)w++,g++;for(var b=(f.length-g)*u+1>>>0,_=new Uint8Array(b);f[g];){var A=t[f.charCodeAt(g)];if(A===255)return;for(var T=0,v=b-1;(A!==0||T<E)&&v!==-1;v--,T++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}if(f[g]!==" "){for(var I=b-E;I!==b&&_[I]===0;)I++;for(var P=new Uint8Array(w+(b-I)),D=w;I!==b;)P[D++]=_[I++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var q_=F_,L_=q_;const Xh=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},k_=r=>new TextEncoder().encode(r),M_=r=>new TextDecoder().decode(r);class z_{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class H_{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 ed(this,e)}}class V_{constructor(e){this.decoders=e}or(e){return ed(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 ed=(r,e)=>new V_({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class K_{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new z_(e,t,i),this.decoder=new H_(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ls=({name:r,prefix:e,encode:t,decode:i})=>new K_(r,e,t,i),ki=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=L_(t,e);return Ls({prefix:r,name:e,encode:i,decode:n=>Xh(s(n))})},W_=(r,e,t,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[r[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},G_=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},$e=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Ls({prefix:e,name:r,encode(s){return G_(s,i,t)},decode(s){return W_(s,i,t,r)}}),Y_=Ls({prefix:"\0",name:"identity",encode:r=>M_(r),decode:r=>k_(r)});var J_=Object.freeze({__proto__:null,identity:Y_});const Z_=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Q_=Object.freeze({__proto__:null,base2:Z_});const X_=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var eI=Object.freeze({__proto__:null,base8:X_});const tI=ki({prefix:"9",name:"base10",alphabet:"0123456789"});var rI=Object.freeze({__proto__:null,base10:tI});const iI=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sI=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var nI=Object.freeze({__proto__:null,base16:iI,base16upper:sI});const oI=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aI=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cI=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),uI=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lI=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hI=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dI=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pI=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fI=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var gI=Object.freeze({__proto__:null,base32:oI,base32upper:aI,base32pad:cI,base32padupper:uI,base32hex:lI,base32hexupper:hI,base32hexpad:dI,base32hexpadupper:pI,base32z:fI});const yI=ki({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mI=ki({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wI=Object.freeze({__proto__:null,base36:yI,base36upper:mI});const bI=ki({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vI=ki({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var EI=Object.freeze({__proto__:null,base58btc:bI,base58flickr:vI});const _I=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),II=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),SI=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),DI=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var OI=Object.freeze({__proto__:null,base64:_I,base64pad:II,base64url:SI,base64urlpad:DI});const td=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),PI=td.reduce((r,e,t)=>(r[t]=e,r),[]),$I=td.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function AI(r){return r.reduce((e,t)=>(e+=PI[t],e),"")}function xI(r){const e=[];for(const t of r){const i=$I[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const CI=Ls({prefix:"🚀",name:"base256emoji",encode:AI,decode:xI});var TI=Object.freeze({__proto__:null,base256emoji:CI}),RI=rd,au=128,NI=-128,jI=Math.pow(2,31);function rd(r,e,t){e=e||[],t=t||0;for(var i=t;r>=jI;)e[t++]=r&255|au,r/=128;for(;r&NI;)e[t++]=r&255|au,r>>>=7;return e[t]=r|0,rd.bytes=t-i+1,e}var BI=co,UI=128,cu=127;function co(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw co.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&cu)<<s:(o&cu)*Math.pow(2,s),s+=7}while(o>=UI);return co.bytes=n-i,t}var FI=Math.pow(2,7),qI=Math.pow(2,14),LI=Math.pow(2,21),kI=Math.pow(2,28),MI=Math.pow(2,35),zI=Math.pow(2,42),HI=Math.pow(2,49),VI=Math.pow(2,56),KI=Math.pow(2,63),WI=function(r){return r<FI?1:r<qI?2:r<LI?3:r<kI?4:r<MI?5:r<zI?6:r<HI?7:r<VI?8:r<KI?9:10},GI={encode:RI,decode:BI,encodingLength:WI},id=GI;const uu=(r,e,t=0)=>(id.encode(r,e,t),e),lu=r=>id.encodingLength(r),uo=(r,e)=>{const t=e.byteLength,i=lu(r),s=i+lu(t),n=new Uint8Array(s+t);return uu(r,n,0),uu(t,n,i),n.set(e,s),new YI(r,t,e,n)};class YI{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const sd=({name:r,code:e,encode:t})=>new JI(r,e,t);class JI{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?uo(this.code,t):t.then(i=>uo(this.code,i))}else throw Error("Unknown type, must be binary type")}}const nd=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),ZI=sd({name:"sha2-256",code:18,encode:nd("SHA-256")}),QI=sd({name:"sha2-512",code:19,encode:nd("SHA-512")});var XI=Object.freeze({__proto__:null,sha256:ZI,sha512:QI});const od=0,e2="identity",ad=Xh,t2=r=>uo(od,ad(r)),r2={code:od,name:e2,encode:ad,digest:t2};var i2=Object.freeze({__proto__:null,identity:r2});new TextEncoder,new TextDecoder;const hu={...J_,...Q_,...eI,...rI,...nI,...gI,...wI,...EI,...OI,...TI};({...XI,...i2});function s2(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function cd(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const du=cd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),In=cd("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=s2(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),n2={utf8:du,"utf-8":du,hex:hu.base16,latin1:In,ascii:In,binary:In,...hu};function o2(r,e="utf8"){const t=n2[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}var a2=Object.defineProperty,c2=(r,e,t)=>e in r?a2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gt=(r,e,t)=>c2(r,typeof e!="symbol"?e+"":e,t);class u2{constructor(e,t){this.core=e,this.logger=t,gt(this,"keychain",new Map),gt(this,"name",u_),gt(this,"version",l_),gt(this,"initialized",!1),gt(this,"storagePrefix",It),gt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),gt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),gt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),gt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=F("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),gt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Hn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Vn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var l2=Object.defineProperty,h2=(r,e,t)=>e in r?l2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ie=(r,e,t)=>h2(r,typeof e!="symbol"?e+"":e,t);class d2{constructor(e,t,i){this.core=e,this.logger=t,Ie(this,"name",a_),Ie(this,"keychain"),Ie(this,"randomSessionIdentifier",to()),Ie(this,"initialized",!1),Ie(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ie(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ie(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=za(s);return Gl(n.publicKey)}),Ie(this,"generateKeyPair",()=>{this.isInitialized();const s=Zv();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ie(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=za(n),a=this.randomSessionIdentifier;return await fm(a,s,c_,o)}),Ie(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=Qv(a,n);return this.setSymKey(c,o)}),Ie(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||as(s);return await this.keychain.set(o,s),o}),Ie(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"encode",async(s,n,o)=>{this.isInitialized();const a=Uh(o),c=Bt(n);if(Pc(a))return t0(c,o==null?void 0:o.encoding);if(Oc(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(d,p)}const u=this.getSymKey(s),{type:l,senderPublicKey:h}=a;return Xv({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Ie(this,"decode",async(s,n,o)=>{this.isInitialized();const a=i0(n,o);if(Pc(a)){const c=r0(n,o==null?void 0:o.encoding);return cr(c)}if(Oc(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;s=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(s),u=e0({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return cr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ie(this,"getPayloadType",(s,n=lt)=>{const o=$i({encoded:s,encoding:n});return hr(o.type)}),Ie(this,"getPayloadSenderPublicKey",(s,n=lt)=>{const o=$i({encoded:s,encoding:n});return o.senderPublicKey?Le(o.senderPublicKey,Re):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new u2(this.core,this.logger)}get context(){return ke(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(su)}catch{e=to(),await this.keychain.set(su,e)}return o2(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var p2=Object.defineProperty,f2=Object.defineProperties,g2=Object.getOwnPropertyDescriptors,pu=Object.getOwnPropertySymbols,y2=Object.prototype.hasOwnProperty,m2=Object.prototype.propertyIsEnumerable,lo=(r,e,t)=>e in r?p2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,w2=(r,e)=>{for(var t in e||(e={}))y2.call(e,t)&&lo(r,t,e[t]);if(pu)for(var t of pu(e))m2.call(e,t)&&lo(r,t,e[t]);return r},b2=(r,e)=>f2(r,g2(e)),Me=(r,e,t)=>lo(r,typeof e!="symbol"?e+"":e,t);class v2 extends t1{constructor(e,t){super(e,t),this.logger=e,this.core=t,Me(this,"messages",new Map),Me(this,"messagesWithoutClientAck",new Map),Me(this,"name",h_),Me(this,"version",d_),Me(this,"initialized",!1),Me(this,"storagePrefix",It),Me(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Me(this,"set",async(i,s,n)=>{this.isInitialized();const o=Et(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===ls.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,b2(w2({},c),{[o]:s}))}return await this.persist(),o}),Me(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),Me(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),Me(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=Et(s);return typeof n[o]<"u"}),Me(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Et(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),Me(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return ke(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,Hn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Hn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Vn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Vn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var E2=Object.defineProperty,_2=Object.defineProperties,I2=Object.getOwnPropertyDescriptors,fu=Object.getOwnPropertySymbols,S2=Object.prototype.hasOwnProperty,D2=Object.prototype.propertyIsEnumerable,ho=(r,e,t)=>e in r?E2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Qi=(r,e)=>{for(var t in e||(e={}))S2.call(e,t)&&ho(r,t,e[t]);if(fu)for(var t of fu(e))D2.call(e,t)&&ho(r,t,e[t]);return r},Sn=(r,e)=>_2(r,I2(e)),ct=(r,e,t)=>ho(r,typeof e!="symbol"?e+"":e,t);class O2 extends r1{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ct(this,"events",new Ye.EventEmitter),ct(this,"name",p_),ct(this,"queue",new Map),ct(this,"publishTimeout",U.toMiliseconds(U.ONE_MINUTE)),ct(this,"initialPublishTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ct(this,"needsTransportRestart",!1),ct(this,"publish",async(i,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const a=(n==null?void 0:n.ttl)||nu,c=ms(n),u=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,h=(n==null?void 0:n.id)||nr().toString(),d={topic:i,message:s,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const f=new Promise(async g=>{const w=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(we.publish,w),g(d))};this.relayer.events.on(we.publish,w);const E=zt(new Promise((b,_)=>{this.rpcPublish({topic:i,message:s,ttl:a,prompt:u,tag:l,id:h,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),_(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await E,this.events.removeListener(we.publish,w)}catch(b){this.queue.set(h,Sn(Qi({},d),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:i,message:s,opts:n}}),await zt(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),ct(this,"on",(i,s)=>{this.events.on(i,s)}),ct(this,"once",(i,s)=>{this.events.once(i,s)}),ct(this,"off",(i,s)=>{this.events.off(i,s)}),ct(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return ke(this.logger)}async rpcPublish(e){var t,i,s,n;const{topic:o,message:a,ttl:c=nu,prompt:u,tag:l,id:h,attestation:d,tvf:p}=e,f={method:gi(ms().protocol).publish,params:Qi({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},p),id:h};De((t=f.params)==null?void 0:t.prompt)&&((i=f.params)==null||delete i.prompt),De((s=f.params)==null?void 0:s.tag)&&((n=f.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const g=await this.relayer.request(f);return this.relayer.events.emit(we.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Sn(Qi({},e),{attempt:i}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Sn(Qi({},e),{topic:s,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(fr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(we.connection_stalled);return}this.checkQueue()}),this.relayer.on(we.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var P2=Object.defineProperty,$2=(r,e,t)=>e in r?P2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ir=(r,e,t)=>$2(r,typeof e!="symbol"?e+"":e,t);class A2{constructor(){Ir(this,"map",new Map),Ir(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Ir(this,"get",e=>this.map.get(e)||[]),Ir(this,"exists",(e,t)=>this.get(e).includes(t)),Ir(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter(n=>n!==t);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),Ir(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var x2=Object.defineProperty,C2=Object.defineProperties,T2=Object.getOwnPropertyDescriptors,gu=Object.getOwnPropertySymbols,R2=Object.prototype.hasOwnProperty,N2=Object.prototype.propertyIsEnumerable,po=(r,e,t)=>e in r?x2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,di=(r,e)=>{for(var t in e||(e={}))R2.call(e,t)&&po(r,t,e[t]);if(gu)for(var t of gu(e))N2.call(e,t)&&po(r,t,e[t]);return r},Dn=(r,e)=>C2(r,T2(e)),ie=(r,e,t)=>po(r,typeof e!="symbol"?e+"":e,t);class j2 extends n1{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ie(this,"subscriptions",new Map),ie(this,"topicMap",new A2),ie(this,"events",new Ye.EventEmitter),ie(this,"name",v_),ie(this,"version",E_),ie(this,"pending",new Map),ie(this,"cached",[]),ie(this,"initialized",!1),ie(this,"storagePrefix",It),ie(this,"subscribeTimeout",U.toMiliseconds(U.ONE_MINUTE)),ie(this,"initialSubscribeTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ie(this,"clientId"),ie(this,"batchSubscribeTopicsLimit",500),ie(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ie(this,"subscribe",async(i,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const n=ms(s),o={topic:i,relay:n,transportType:s==null?void 0:s.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),ie(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),ie(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),ie(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ie(this,"on",(i,s)=>{this.events.on(i,s)}),ie(this,"once",(i,s)=>{this.events.once(i,s)}),ie(this,"off",(i,s)=>{this.events.off(i,s)}),ie(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),ie(this,"start",async()=>{await this.onConnect()}),ie(this,"stop",async()=>{await this.onDisconnect()}),ie(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ie(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),ie(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(fr.pulse,async()=>{await this.checkPending()}),this.events.on(He.created,async i=>{const s=He.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(He.deleted,async i=>{const s=He.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return ke(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,t){let i=!1;try{i=this.getSubscription(e).topic===t}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,t){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=ms(i);await this.restartToComplete({topic:e,id:t,relay:s}),await this.rpcUnsubscribe(e,t,s);const n=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t,i){var s;(!i||(i==null?void 0:i.transportType)===ae.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:gi(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===ae.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},U.toMiliseconds(U.ONE_SECOND)),a;const c=new Promise(async l=>{const h=d=>{d.topic===e&&(this.events.removeListener(He.created,h),l(d.id))};this.events.on(He.created,h);try{const d=await zt(new Promise((p,f)=>{this.relayer.request(n).catch(g=>{this.logger.warn(g,g==null?void 0:g.message),f(g)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(He.created,h),l(d)}catch{}}),u=await zt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(we.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:gi(t.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await zt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(we.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:gi(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await zt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(we.connection_stalled)}return s}rpcUnsubscribe(e,t,i){const s={method:gi(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,Dn(di({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,di({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,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,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,di({},t)),this.topicMap.set(t.topic,e),this.events.emit(He.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(He.deleted,Dn(di({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(He.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(He.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>Dn(di({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await Fw(U.toMiliseconds(U.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=F("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 Et(e+await this.getClientId())}}var B2=Object.defineProperty,yu=Object.getOwnPropertySymbols,U2=Object.prototype.hasOwnProperty,F2=Object.prototype.propertyIsEnumerable,fo=(r,e,t)=>e in r?B2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,mu=(r,e)=>{for(var t in e||(e={}))U2.call(e,t)&&fo(r,t,e[t]);if(yu)for(var t of yu(e))F2.call(e,t)&&fo(r,t,e[t]);return r},Z=(r,e,t)=>fo(r,typeof e!="symbol"?e+"":e,t);class q2 extends i1{constructor(e){super(e),Z(this,"protocol","wc"),Z(this,"version",2),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Ye.EventEmitter),Z(this,"provider"),Z(this,"messages"),Z(this,"subscriber"),Z(this,"publisher"),Z(this,"name",g_),Z(this,"transportExplicitlyClosed",!1),Z(this,"initialized",!1),Z(this,"connectionAttemptInProgress",!1),Z(this,"relayUrl"),Z(this,"projectId"),Z(this,"packageName"),Z(this,"bundleId"),Z(this,"hasExperiencedNetworkDisruption",!1),Z(this,"pingTimeout"),Z(this,"heartBeatTimeout",U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS)),Z(this,"reconnectTimeout"),Z(this,"connectPromise"),Z(this,"reconnectInProgress",!1),Z(this,"requestsInFlight",[]),Z(this,"connectTimeout",U.toMiliseconds(U.ONE_SECOND*15)),Z(this,"request",async t=>{var i,s;this.logger.debug("Publishing Request Payload");const n=t.id||nr().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((s=t.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Z(this,"resetPingTimeout",()=>{gs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),Z(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Z(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(we.connect)}),Z(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Z(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(we.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Z(this,"registerProviderListeners",()=>{this.provider.on(Qe.payload,this.onPayloadHandler),this.provider.on(Qe.connect,this.onConnectHandler),this.provider.on(Qe.disconnect,this.onDisconnectHandler),this.provider.on(Qe.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):qi(Bs({level:e.logger||f_})),this.messages=new v2(this.logger,e.core),this.subscriber=new j2(this,this.logger),this.publisher=new O2(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Zh,this.projectId=e.projectId,_w()?this.packageName=Ja():Iw()&&(this.bundleId=Ja()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return ke(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:ae.relay},ls.outbound)}async subscribe(e,t){var i,s,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(He.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(He.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,mu({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&h(d)})||a,l()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("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(t,i)=>{await this.connect(e).then(t).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 Fc())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 t=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const s=de(U.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(we.message,e),await this.recordMessageEvent(e,ls.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,n),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(Qe.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Qe.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,U.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,s,n;if(gs())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new it(new i_($w({sdkVersion:ao,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,t){const{topic:i,message:s}=e;await this.messages.set(i,s,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const s=this.messages.has(t,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),zo(e)){if(!e.method.endsWith(y_))return;const t=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=t.data,a={topic:i,message:s,publishedAt:n,transportType:ae.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(mu({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else qs(e)&&this.events.emit(we.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ls.inbound),this.events.emit(we.message,e))}async acknowledgePayload(e){const t=Us(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Qe.payload,this.onPayloadHandler),this.provider.off(Qe.connect,this.onConnectHandler),this.provider.off(Qe.disconnect,this.onDisconnectHandler),this.provider.off(Qe.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Fc();J0(async t=>{e!==t&&(e=t,t?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(fr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&X0())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(we.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},U.toMiliseconds(m_)))))}isInitialized(){if(!this.initialized){const{message:e}=F("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 L2(){}function wu(r){if(!r||typeof r!="object")return!1;const e=Object.getPrototypeOf(r);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(r)==="[object Object]":!1}function bu(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function vu(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const k2="[object RegExp]",M2="[object String]",z2="[object Number]",H2="[object Boolean]",Eu="[object Arguments]",V2="[object Symbol]",K2="[object Date]",W2="[object Map]",G2="[object Set]",Y2="[object Array]",J2="[object Function]",Z2="[object ArrayBuffer]",On="[object Object]",Q2="[object Error]",X2="[object DataView]",eS="[object Uint8Array]",tS="[object Uint8ClampedArray]",rS="[object Uint16Array]",iS="[object Uint32Array]",sS="[object BigUint64Array]",nS="[object Int8Array]",oS="[object Int16Array]",aS="[object Int32Array]",cS="[object BigInt64Array]",uS="[object Float32Array]",lS="[object Float64Array]";function hS(r,e){return r===e||Number.isNaN(r)&&Number.isNaN(e)}function dS(r,e,t){return yi(r,e,void 0,void 0,void 0,void 0,t)}function yi(r,e,t,i,s,n,o){const a=o(r,e,t,i,s,n);if(a!==void 0)return a;if(typeof r==typeof e)switch(typeof r){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return r===e;case"number":return r===e||Object.is(r,e);case"function":return r===e;case"object":return Ei(r,e,n,o)}return Ei(r,e,n,o)}function Ei(r,e,t,i){if(Object.is(r,e))return!0;let s=vu(r),n=vu(e);if(s===Eu&&(s=On),n===Eu&&(n=On),s!==n)return!1;switch(s){case M2:return r.toString()===e.toString();case z2:{const c=r.valueOf(),u=e.valueOf();return hS(c,u)}case H2:case K2:case V2:return Object.is(r.valueOf(),e.valueOf());case k2:return r.source===e.source&&r.flags===e.flags;case J2:return r===e}t=t??new Map;const o=t.get(r),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(r,e),t.set(e,r);try{switch(s){case W2:{if(r.size!==e.size)return!1;for(const[c,u]of r.entries())if(!e.has(c)||!yi(u,e.get(c),c,r,e,t,i))return!1;return!0}case G2:{if(r.size!==e.size)return!1;const c=Array.from(r.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],d=u.findIndex(p=>yi(h,p,void 0,r,e,t,i));if(d===-1)return!1;u.splice(d,1)}return!0}case Y2:case eS:case tS:case rS:case iS:case sS:case nS:case oS:case aS:case cS:case uS:case lS:{if(typeof Buffer<"u"&&Buffer.isBuffer(r)!==Buffer.isBuffer(e)||r.length!==e.length)return!1;for(let c=0;c<r.length;c++)if(!yi(r[c],e[c],c,r,e,t,i))return!1;return!0}case Z2:return r.byteLength!==e.byteLength?!1:Ei(new Uint8Array(r),new Uint8Array(e),t,i);case X2:return r.byteLength!==e.byteLength||r.byteOffset!==e.byteOffset?!1:Ei(new Uint8Array(r),new Uint8Array(e),t,i);case Q2:return r.name===e.name&&r.message===e.message;case On:{if(!(Ei(r.constructor,e.constructor,t,i)||wu(r)&&wu(e)))return!1;const c=[...Object.keys(r),...bu(r)],u=[...Object.keys(e),...bu(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=r[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!yi(d,p,h,r,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(r),t.delete(e)}}function pS(r,e){return dS(r,e,L2)}var fS=Object.defineProperty,_u=Object.getOwnPropertySymbols,gS=Object.prototype.hasOwnProperty,yS=Object.prototype.propertyIsEnumerable,go=(r,e,t)=>e in r?fS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Iu=(r,e)=>{for(var t in e||(e={}))gS.call(e,t)&&go(r,t,e[t]);if(_u)for(var t of _u(e))yS.call(e,t)&&go(r,t,e[t]);return r},Be=(r,e,t)=>go(r,typeof e!="symbol"?e+"":e,t);class gr extends s1{constructor(e,t,i,s=It,n=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,Be(this,"map",new Map),Be(this,"version",w_),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"getKey"),Be(this,"storagePrefix",It),Be(this,"recentlyDeleted",[]),Be(this,"recentlyDeletedLimit",200),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!De(o)?this.map.set(this.getKey(o),o):P0(o)?this.map.set(o.id,o):$0(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Be(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())}),Be(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Be(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>pS(a[c],o[c]))):this.values)),Be(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=Iu(Iu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Be(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=Ne(t,this.name),this.storagePrefix=s,this.getKey=n}get context(){return ke(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 t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:s}=F("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}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:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mS=Object.defineProperty,wS=(r,e,t)=>e in r?mS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,W=(r,e,t)=>wS(r,typeof e!="symbol"?e+"":e,t);class bS{constructor(e,t){this.core=e,this.logger=t,W(this,"name",__),W(this,"version",I_),W(this,"events",new So),W(this,"pairings"),W(this,"initialized",!1),W(this,"storagePrefix",It),W(this,"ignoredPayloadTypes",[Nt]),W(this,"registeredMethods",[]),W(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),W(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),W(this,"create",async i=>{this.isInitialized();const s=to(),n=await this.core.crypto.setSymKey(s),o=de(U.FIVE_MINUTES),a={protocol:Jh},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},u=Ac({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(rr.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:u}}),W(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[mt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:u}=$c(i.uri);s.props.properties.topic=n,s.addTrace(mt.pairing_uri_validation_success),s.addTrace(mt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),s.addTrace(mt.existing_pairing),l.active)throw s.setError(xt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(mt.pairing_not_expired)}const h=c||de(U.FIVE_MINUTES),d={topic:n,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(n,h),await this.pairings.set(n,d),s.addTrace(mt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(rr.create,d),s.addTrace(mt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(mt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(xt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw s.setError(xt.subscribe_pairing_topic_failure),p}return s.addTrace(mt.subscribe_pairing_topic_success),d}),W(this,"activate",async({topic:i})=>{this.isInitialized();const s=de(U.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),W(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Qt();this.events.once(X("pairing_ping",n),({error:u})=>{u?c(u):a()}),await o()}}),W(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),W(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),W(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),W(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(s))}),W(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return Ac({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),W(this,"sendRequest",async(i,s,n)=>{const o=Ht(s,n),a=await this.core.crypto.encode(i,o),c=li[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),W(this,"sendResult",async(i,s,n)=>{const o=Us(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=li[c].res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),W(this,"sendError",async(i,s,n)=>{const o=Fs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=li[c]?li[c].res:li.unregistered_method.res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),W(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),W(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>kt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),W(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),W(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),W(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(rr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),W(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{bt(s)?this.events.emit(X("pairing_ping",n),{}):tt(s)&&this.events.emit(X("pairing_ping",n),{error:s.error})},500)}),W(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(rr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),W(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),W(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(te("WC_METHOD_UNSUPPORTED",i))}),W(this,"isValidPair",(i,s)=>{var n;if(!Fe(i)){const{message:a}=F("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(xt.malformed_pairing_uri),new Error(a)}if(!O0(i.uri)){const{message:a}=F("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(xt.malformed_pairing_uri),new Error(a)}const o=$c(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(xt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(xt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&U.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(xt.pairing_expired);const{message:a}=F("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),W(this,"isValidPing",async i=>{if(!Fe(i)){const{message:n}=F("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),W(this,"isValidDisconnect",async i=>{if(!Fe(i)){const{message:n}=F("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),W(this,"isValidPairingTopic",async i=>{if(!he(i,!1)){const{message:s}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(kt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=F("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new gr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ke(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(we.message,async e=>{const{topic:t,message:i,transportType:s}=e;if(this.pairings.keys.includes(t)&&s!==ae.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(t,i);zo(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):qs(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(et.expired,async e=>{const{topic:t}=sh(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(rr.expire,{topic:t}))})}}var vS=Object.defineProperty,ES=(r,e,t)=>e in r?vS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Se=(r,e,t)=>ES(r,typeof e!="symbol"?e+"":e,t);class _S extends e1{constructor(e,t){super(e,t),this.core=e,this.logger=t,Se(this,"records",new Map),Se(this,"events",new Ye.EventEmitter),Se(this,"name",S_),Se(this,"version",D_),Se(this,"cached",[]),Se(this,"initialized",!1),Se(this,"storagePrefix",It),Se(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)}),Se(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:de(U.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ot.created,o)}),Se(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=tt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(ot.updated,s))}),Se(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),Se(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(ot.deleted,n)}}),this.persist()}),Se(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),Se(this,"on",(i,s)=>{this.events.on(i,s)}),Se(this,"once",(i,s)=>{this.events.once(i,s)}),Se(this,"off",(i,s)=>{this.events.off(i,s)}),Se(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(t,this.name)}get context(){return ke(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(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Ht(t.request.method,t.request.params,t.id),chainId:t.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 t=this.records.get(e);if(!t){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}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:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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 t=ot.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ot.updated,e=>{const t=ot.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ot.deleted,e=>{const t=ot.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(fr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{U.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(ot.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var IS=Object.defineProperty,SS=(r,e,t)=>e in r?IS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xe=(r,e,t)=>SS(r,typeof e!="symbol"?e+"":e,t);class DS extends o1{constructor(e,t){super(e,t),this.core=e,this.logger=t,xe(this,"expirations",new Map),xe(this,"events",new Ye.EventEmitter),xe(this,"name",O_),xe(this,"version",P_),xe(this,"cached",[]),xe(this,"initialized",!1),xe(this,"storagePrefix",It),xe(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)}),xe(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),xe(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(et.created,{target:n,expiration:o})}),xe(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),xe(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(et.deleted,{target:s,expiration:n})}}),xe(this,"on",(i,s)=>{this.events.on(i,s)}),xe(this,"once",(i,s)=>{this.events.once(i,s)}),xe(this,"off",(i,s)=>{this.events.off(i,s)}),xe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(t,this.name)}get context(){return ke(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 Aw(e);if(typeof e=="number")return xw(e);const{message:t}=F("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}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(et.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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 t=this.expirations.get(e);if(!t){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;U.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(et.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(fr.pulse,()=>this.checkExpirations()),this.events.on(et.created,e=>{const t=et.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(et.expired,e=>{const t=et.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(et.deleted,e=>{const t=et.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var OS=Object.defineProperty,PS=(r,e,t)=>e in r?OS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,le=(r,e,t)=>PS(r,typeof e!="symbol"?e+"":e,t);class $S extends a1{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,le(this,"name",$_),le(this,"abortController"),le(this,"isDevEnv"),le(this,"verifyUrlV3",x_),le(this,"storagePrefix",It),le(this,"version",Yh),le(this,"publicKey"),le(this,"fetchPromise"),le(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),le(this,"register",async s=>{if(!Qr()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const u=jt.getDocument(),l=this.startAbortTimer(U.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",w),u.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",f,{signal:this.abortController.signal});const w=E=>{if(E.data&&typeof E.data=="string")try{const b=JSON.parse(E.data);if(b.type==="verify_attestation"){if(zn(b.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",w),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};u.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),le(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(zn(n).payload.id!==a)return;const u=await this.isValidJwtAttestation(n);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),le(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(U.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),le(this,"getVerifyUrl",s=>{let n=s||vi;return C_.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${vi}`),n=vi),n}),le(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(U.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),le(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),le(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),le(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),le(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),le(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),le(this,"validateAttestation",(s,n)=>{const o=n0(s,n.publicKey),a={hasExpired:U.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=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=Ro(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ke(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}}var AS=Object.defineProperty,xS=(r,e,t)=>e in r?AS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Su=(r,e,t)=>xS(r,typeof e!="symbol"?e+"":e,t);class CS extends c1{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Su(this,"context",T_),Su(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${R_}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=Ne(t,this.context)}}var TS=Object.defineProperty,Du=Object.getOwnPropertySymbols,RS=Object.prototype.hasOwnProperty,NS=Object.prototype.propertyIsEnumerable,yo=(r,e,t)=>e in r?TS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pi=(r,e)=>{for(var t in e||(e={}))RS.call(e,t)&&yo(r,t,e[t]);if(Du)for(var t of Du(e))NS.call(e,t)&&yo(r,t,e[t]);return r},fe=(r,e,t)=>yo(r,typeof e!="symbol"?e+"":e,t);class jS extends u1{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,fe(this,"context",j_),fe(this,"storagePrefix",It),fe(this,"storageVersion",N_),fe(this,"events",new Map),fe(this,"shouldPersist",!1),fe(this,"init",async()=>{if(!Ro())try{const s={eventId:Qa(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rh(this.core.relayer.protocol,this.core.relayer.version,ao)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),fe(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,u=Qa(),l=this.core.projectId||"",h=Date.now(),d=pi({eventId:u,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,d),this.shouldPersist=!0),d}),fe(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return pi(pi({},a),this.setMethods(a.eventId))}),fe(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),fe(this,"setEventListeners",()=>{this.core.heartbeat.on(fr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(s.timestamp)>B_&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),fe(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),fe(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),fe(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),fe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),fe(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,pi(pi({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),fe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),fe(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${U_}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ao}${n}`,{method:"POST",body:JSON.stringify(s)})}),fe(this,"getAppDomain",()=>th().url),this.logger=Ne(t,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 BS=Object.defineProperty,Ou=Object.getOwnPropertySymbols,US=Object.prototype.hasOwnProperty,FS=Object.prototype.propertyIsEnumerable,mo=(r,e,t)=>e in r?BS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pu=(r,e)=>{for(var t in e||(e={}))US.call(e,t)&&mo(r,t,e[t]);if(Ou)for(var t of Ou(e))FS.call(e,t)&&mo(r,t,e[t]);return r},oe=(r,e,t)=>mo(r,typeof e!="symbol"?e+"":e,t);let qS=class ud extends JE{constructor(e){var t;super(e),oe(this,"protocol",Gh),oe(this,"version",Yh),oe(this,"name",oo),oe(this,"relayUrl"),oe(this,"projectId"),oe(this,"customStoragePrefix"),oe(this,"events",new Ye.EventEmitter),oe(this,"logger"),oe(this,"heartbeat"),oe(this,"relayer"),oe(this,"crypto"),oe(this,"storage"),oe(this,"history"),oe(this,"expirer"),oe(this,"pairing"),oe(this,"verify"),oe(this,"echoClient"),oe(this,"linkModeSupportedApps"),oe(this,"eventClient"),oe(this,"initialized",!1),oe(this,"logChunkController"),oe(this,"on",(a,c)=>this.events.on(a,c)),oe(this,"once",(a,c)=>this.events.once(a,c)),oe(this,"off",(a,c)=>this.events.off(a,c)),oe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),oe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ae.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});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)||Zh,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Bs({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:n_.logger,name:oo}),{logger:n,chunkLoggerController:o}=WE({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.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=Ne(n,this.name),this.heartbeat=new tE,this.crypto=new d2(this,this.logger,e==null?void 0:e.keychain),this.history=new _S(this,this.logger),this.expirer=new DS(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new xE(Pu(Pu({},o_),e==null?void 0:e.storageOptions)),this.relayer=new q2({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new bS(this,this.logger),this.verify=new $S(this,this.logger,this.storage),this.echoClient=new CS(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new jS(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new ud(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(b_,i),t}get context(){return ke(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(ou,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(ou)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,i=`${t}_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[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&s_.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const LS=qS,ld="wc",hd=2,dd="client",Ho=`${ld}@${hd}:${dd}:`,Pn={name:dd,logger:"error"},$u="WALLETCONNECT_DEEPLINK_CHOICE",kS="proposal",Au="Proposal expired",MS="session",Sr=U.SEVEN_DAYS,zS="engine",ge={wc_sessionPropose:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1104},res:{ttl:U.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1106},res:{ttl:U.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1112},res:{ttl:U.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1114},res:{ttl:U.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:U.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:U.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1119}}},$n={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},yt={idle:"IDLE",active:"ACTIVE"},xu={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},HS="request",VS=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],KS="wc",WS="auth",GS="authKeys",YS="pairingTopics",JS="requests",ks=`${KS}@${1.5}:${WS}:`,hs=`${ks}:PUB_KEY`;var ZS=Object.defineProperty,QS=Object.defineProperties,XS=Object.getOwnPropertyDescriptors,Cu=Object.getOwnPropertySymbols,eD=Object.prototype.hasOwnProperty,tD=Object.prototype.propertyIsEnumerable,wo=(r,e,t)=>e in r?ZS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,se=(r,e)=>{for(var t in e||(e={}))eD.call(e,t)&&wo(r,t,e[t]);if(Cu)for(var t of Cu(e))tD.call(e,t)&&wo(r,t,e[t]);return r},Te=(r,e)=>QS(r,XS(e)),R=(r,e,t)=>wo(r,typeof e!="symbol"?e+"":e,t);class rD extends p1{constructor(e){super(e),R(this,"name",zS),R(this,"events",new So),R(this,"initialized",!1),R(this,"requestQueue",{state:yt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:yt.idle,queue:[]}),R(this,"requestQueueDelay",U.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(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(ge)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Te(se({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=E0(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=i;let l=s,h,d=!1;try{if(l){const v=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=v.active}}catch(v){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),v}if(!l||!d){const{topic:v,uri:I}=await this.client.core.pairing.create();l=v,h=I}if(!l){const{message:v}=F("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(v)}const p=await this.client.core.crypto.generateKeyPair(),f=ge.wc_sessionPropose.req.ttl||U.FIVE_MINUTES,g=de(f),w=Te(se(se({requiredNamespaces:n,optionalNamespaces:o,relays:u??[{protocol:Jh}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),E=X("session_connect",w.id),{reject:b,resolve:_,done:A}=Qt(f,Au),T=({id:v})=>{v===w.id&&(this.client.events.off("proposal_expire",T),this.pendingSessions.delete(w.id),this.events.emit(E,{error:{message:Au,code:0}}))};return this.client.events.on("proposal_expire",T),this.events.once(E,({error:v,session:I})=>{this.client.events.off("proposal_expire",T),v?b(v):I&&_(I)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:h,approval:A}}),R(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),R(this,"approve",async t=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[at.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(D){throw o.setError(Jt.no_internet_connection),D}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(D){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Jt.proposal_not_found),D}try{await this.isValidApprove(t)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Jt.session_approve_namespace_validation_failure),D}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=t,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:w,optionalNamespaces:E}=p;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:f});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:at.session_approve_started,properties:{topic:f,trace:[at.session_approve_started,at.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),A=g.publicKey,T=await this.client.core.crypto.generateSharedKey(_,A),v=se(se(se({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:_,metadata:this.client.metadata},expiry:de(Sr)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),I=ae.relay;b.addTrace(at.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:I})}catch(D){throw b.setError(Jt.subscribe_session_topic_failure),D}b.addTrace(at.subscribe_session_topic_success);const P=Te(se({},v),{topic:T,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:f,acknowledged:!1,self:v.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:_,transportType:ae.relay});await this.client.session.set(T,P),b.addTrace(at.store_session);try{b.addTrace(at.publishing_session_settle),await this.sendRequest({topic:T,method:"wc_sessionSettle",params:v,throwOnFailedPublish:!0}).catch(D=>{throw b==null||b.setError(Jt.session_settle_publish_failure),D}),b.addTrace(at.session_settle_publish_success),b.addTrace(at.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:_},throwOnFailedPublish:!0}).catch(D=>{throw b==null||b.setError(Jt.session_approve_publish_failure),D}),b.addTrace(at.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(T,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),D}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.client.proposal.delete(a,te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(T,de(Sr)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),R(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:s,rpcOpts:ge.wc_sessionPropose.reject}),await this.client.proposal.delete(i,te("USER_DISCONNECTED")))}),R(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:s}=t,{done:n,resolve:o,reject:a}=Qt(),c=wt(),u=nr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(X("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:n}}),R(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=t,s=wt(),{done:n,resolve:o,reject:a}=Qt();return this.events.once(X("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,de(Sr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),R(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(E){throw this.client.logger.error("request() -> isValidRequest() failed"),E}const{chainId:i,request:s,topic:n,expiry:o=ge.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ae.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),u=nr().toString(),{done:l,resolve:h,reject:d}=Qt(o,"Request expired. Please try again.");this.events.once(X("session_request",c),({error:E,result:b})=>{E?d(E):h(b)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:p,params:{request:Te(se({},s),{expiryTimestamp:de(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(E=>d(E)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await l();const g={request:Te(se({},s),{expiryTimestamp:de(o)}),chainId:i},w=this.shouldSetTVF(p,g);return await Promise.all([new Promise(async E=>{await this.sendRequest(se({clientRpcId:c,relayRpcId:u,topic:n,method:p,params:g,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,g)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),E()}),new Promise(async E=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const _=await Nw(this.client.core.storage,$u);await Cw({id:c,topic:n,wcDeepLink:_})}E()}),l()]).then(E=>E[2])}),R(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:s}=t,{id:n}=s,o=this.client.session.get(i);o.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);bt(s)?await this.sendResult({id:n,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:a}):tt(s)&&await this.sendError({id:n,topic:i,error:s.error,appLink:a}),this.cleanupAfterResponse(t)}),R(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=t;if(this.client.session.keys.includes(i)){const s=wt(),n=nr().toString(),{done:o,resolve:a,reject:c}=Qt();this.events.once(X("session_ping",s),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),R(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:s,chainId:n}=t,o=nr().toString(),a=wt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=F("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),R(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>S0(i,t)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(t,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ae.link_mode:ae.relay;o===ae.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:p,nbf:f,methods:g=[],expiry:w}=t,E=[...t.resources||[]],{topic:b,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:_}});const A=await this.client.core.crypto.generateKeyPair(),T=as(A);if(await Promise.all([this.client.auth.authKeys.set(hs,{responseTopic:T,publicKey:A}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:b})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),g.length>0){const{namespace:O}=kr(a[0]);let C=Ob(O,"request",g);os(E)&&(C=$b(C,E.pop())),E.push(C)}const v=w&&w>ge.wc_sessionAuthenticate.req.ttl?w:ge.wc_sessionAuthenticate.req.ttl,I={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:E},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:de(v)},P={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},D={requiredNamespaces:{},optionalNamespaces:P,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:de(ge.wc_sessionPropose.req.ttl),id:wt()},{done:j,resolve:N,reject:B}=Qt(v,"Request expired"),M=wt(),$=X("session_connect",D.id),y=X("session_request",M),m=async({error:O,session:C})=>{this.events.off(y,S),O?B(O):C&&N({session:C})},S=async O=>{var C,q,k;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),O.error){const Y=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===Y.code?void 0:(this.events.off($,m),B(O.error.message))}await this.deleteProposal(D.id),this.events.off($,m);const{cacaos:z,responder:L}=O.result,H=[],V=[];for(const Y of z){await oc({cacao:Y,projectId:this.client.core.projectId})||(this.client.logger.error(Y,"Signature verification failed"),B(te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ae}=Y,Ee=os(Ae.resources),Ce=[Kn(Ae.iss)],Je=ys(Ae.iss);if(Ee){const Ze=ac(Ee),mr=cc(Ee);H.push(...Ze),Ce.push(...mr)}for(const Ze of Ce)V.push(`${Ze}:${Je}`)}const ne=await this.client.core.crypto.generateSharedKey(A,L.publicKey);let ee;H.length>0&&(ee={topic:ne,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:de(Sr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:Rc([...new Set(H)],[...new Set(V)]),transportType:o},await this.client.core.relayer.subscribe(ne,{transportType:o}),await this.client.session.set(ne,ee),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:L.metadata}),ee=this.client.session.get(ne)),(C=this.client.metadata.redirect)!=null&&C.linkMode&&(q=L.metadata.redirect)!=null&&q.linkMode&&(k=L.metadata.redirect)!=null&&k.universal&&i&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(ne,{transportType:ae.link_mode})),N({auths:z,session:ee})};this.events.once($,m),this.events.once(y,S);let x;try{if(n){const O=Ht("wc_sessionAuthenticate",I,M);this.client.core.history.set(b,O);const C=await this.client.core.crypto.encode("",O,{type:Fi,encoding:Mt});x=Yi(i,b,C)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:I,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:D,expiry:ge.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:D.id})])}catch(O){throw this.events.off($,m),this.events.off(y,S),O}return await this.setProposal(D.id,D),await this.setAuthRequest(M,{request:Te(se({},I),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:x??_,response:j}}),R(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:s}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Zt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw n.setError(hi.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(hi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||ae.relay;a===ae.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=as(c),h={type:Nt,receiverPublicKey:c,senderPublicKey:u},d=[],p=[];for(const w of s){if(!await oc({cacao:w,projectId:this.client.core.projectId})){n.setError(hi.invalid_cacao);const T=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:T,encodeOpts:h}),new Error(T.message)}n.addTrace(Zt.cacaos_verified);const{p:E}=w,b=os(E.resources),_=[Kn(E.iss)],A=ys(E.iss);if(b){const T=ac(b),v=cc(b);d.push(...T),_.push(...v)}for(const T of _)p.push(`${T}:${A}`)}const f=await this.client.core.crypto.generateSharedKey(u,c);n.addTrace(Zt.create_authenticated_session_topic);let g;if((d==null?void 0:d.length)>0){g={topic:f,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:de(Sr),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Rc([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(Zt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(w){throw n.setError(hi.subscribe_authenticated_session_topic_failure),w}n.addTrace(Zt.subscribe_authenticated_session_topic_success),await this.client.session.set(f,g),n.addTrace(Zt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Zt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:s,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw n.setError(hi.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:n.eventId}),{session:g}}),R(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:s}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=as(o),u={type:Nt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:u,rpcOpts:ge.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,te("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:s}=t;return ph(i,s)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),R(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),R(this,"deleteSession",async t=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem($u).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===s&&this.deletePendingSessionRequest(u.id,te("USER_DISCONNECTED"))}),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),R(this,"deleteProposal",async(t,i)=>{if(i)try{const s=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Jt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),R(this,"deletePendingSessionRequest",async(t,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),s&&(this.sessionRequestQueue.state=yt.idle,this.client.events.emit("session_request_expire",{id:t}))}),R(this,"deletePendingAuthRequest",async(t,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),s?Promise.resolve():this.client.core.expirer.del(t)])}),R(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),R(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,de(ge.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),R(this,"setAuthRequest",async(t,i)=>{const{request:s,pairingTopic:n,transportType:o=ae.relay}=i;this.client.core.expirer.set(t,s.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:t,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async t=>{const{id:i,topic:s,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||de(ge.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),R(this,"sendRequest",async t=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=t,d=Ht(s,n,c);let p;const f=!!l;try{const E=f?Mt:lt;p=await this.client.core.crypto.encode(i,d,{encoding:E})}catch(E){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),E}let g;if(VS.includes(s)){const E=Et(JSON.stringify(d)),b=Et(p);g=await this.client.core.verify.register({id:b,decryptedId:E})}const w=ge[s].req;if(w.attestation=g,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(i,d),f){const E=Yi(l,i,p);await global.Linking.openURL(E,this.client.name)}else{const E=ge[s].req;o&&(E.ttl=o),a&&(E.id=a),E.tvf=Te(se({},h),{correlationId:d.id}),u?(E.internal=Te(se({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,E)):this.client.core.relayer.publish(i,p,E).catch(b=>this.client.logger.error(b))}return d.id}),R(this,"sendResult",async t=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,u=Us(i,n);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?Mt:lt;l=await this.client.core.crypto.encode(s,u,Te(se({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),f}let d,p;try{d=await this.client.core.history.get(s,i);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(i,f.params,n))}catch(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),f}if(h){const f=Yi(c,s,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,g=ge[f].res;g.tvf=Te(se({},p),{correlationId:i}),o?(g.internal=Te(se({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,l,g)):this.client.core.relayer.publish(s,l,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),R(this,"sendError",async t=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,u=Fs(i,n);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?Mt:lt;l=await this.client.core.crypto.encode(s,u,Te(se({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let d;try{d=await this.client.core.history.get(s,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),p}if(h){const p=Yi(c,s,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||ge[p].res;this.client.core.relayer.publish(s,l,f)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;kt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&t.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{kt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...t.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),R(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),R(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===yt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=yt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=yt.idle}),R(this,"processRequest",async t=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=t,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async t=>{const{topic:i,payload:s,transportType:n}=t,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:s}=F("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),R(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:s}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=t,{params:a,id:c}=s;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u==null||u.setError(xt.proposal_listener_not_found)),this.isValidConnect(se({},s.params));const l=a.expiryTimestamp||de(ge.wc_sessionPropose.req.ttl),h=se({id:c,pairingTopic:i,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:n,hash:Et(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});u==null||u.addTrace(mt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:ge.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(t,i,s)=>{const{id:n}=i;if(bt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:t})}else if(tt(i)){await this.client.proposal.delete(n,te("USER_DISCONNECTED"));const o=X("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),R(this,"onSessionSettleRequest",async(t,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=i.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===t);if(!p)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(p.proposalId),g=Te(se(se(se({topic:t,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:ae.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(X("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(t,i)=>{const{id:s}=i;bt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(X("session_approve",s),{})):tt(i)&&(await this.client.session.delete(t,te("USER_DISCONNECTED")),this.events.emit(X("session_approve",s),{error:i.error}))}),R(this,"onSessionUpdateRequest",async(t,i)=>{const{params:s,id:n}=i;try{const o=`${t}_session_update`,a=ui.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:t},s));try{ui.set(o,n),await this.client.session.update(t,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw ui.delete(o),c}this.client.events.emit("session_update",{id:n,topic:t,params:s})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(t,i)=>{const{id:s}=i,n=X("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_update",s),{}):tt(i)&&this.events.emit(X("session_update",s),{error:i.error})}),R(this,"onSessionExtendRequest",async(t,i)=>{const{id:s}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,de(Sr)),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:t})}catch(n){await this.sendError({id:s,topic:t,error:n}),this.client.logger.error(n)}}),R(this,"onSessionExtendResponse",(t,i)=>{const{id:s}=i,n=X("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_extend",s),{}):tt(i)&&this.events.emit(X("session_extend",s),{error:i.error})}),R(this,"onSessionPingRequest",async(t,i)=>{const{id:s}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:t})}catch(n){await this.sendError({id:s,topic:t,error:n}),this.client.logger.error(n)}}),R(this,"onSessionPingResponse",(t,i)=>{const{id:s}=i,n=X("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);bt(i)?this.events.emit(X("session_ping",s),{}):tt(i)&&this.events.emit(X("session_ping",s),{error:i.error})},500)}),R(this,"onSessionDeleteRequest",async(t,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(we.publish,async()=>{n(await this.deleteSession({topic:t,id:s}))})}),this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),R(this,"onSessionRequest",async t=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=t,{id:h,params:d}=a;try{await this.isValidRequest(se({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:Et(JSON.stringify(Ht("wc_sessionRequest",d,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),g={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(g),l===ae.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=p.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(t,i)=>{const{id:s}=i,n=X("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_request",s),{result:i.result}):tt(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionEventRequest",async(t,i)=>{const{id:s,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=ui.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(se({topic:t},n)),this.client.events.emit("session_event",{id:s,topic:t,params:n}),ui.set(o,s)}catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),bt(i)?this.events.emit(X("session_request",s),{result:i.result}):tt(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:u,authPayload:l,expiryTimestamp:h}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Et(JSON.stringify(n)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:s,id:n.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:p,pairingTopic:s,transportType:c}),c===ae.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(u){this.client.logger.error(u);const l=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:Nt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:n.id,topic:s,error:u,encodeOpts:p,rpcOpts:ge.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),R(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=yt.idle,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=X("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(X("session_request",n.request.id),{error:i})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===yt.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=yt.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),R(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),R(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Ht("wc_sessionPropose",Te(se({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),R(this,"isValidConnect",async t=>{if(!Fe(t)){const{message:u}=F("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(De(i)||await this.isValidPairingTopic(i),!B0(c)){const{message:u}=F("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!De(s)&&Kt(s)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(s,"requiredNamespaces")}if(!De(n)&&Kt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),De(o)||this.validateSessionProps(o,"sessionProperties"),!De(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(t,i)=>{const s=j0(t,"connect()",i);if(s)throw new Error(s.message)}),R(this,"isValidApprove",async t=>{if(!Fe(t))throw new Error(F("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=mn(s,"approve()");if(u)throw new Error(u.message);const l=Bc(c.requiredNamespaces,s,"approve()");if(l)throw new Error(l.message);if(!he(n,!0)){const{message:h}=F("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(De(o)||this.validateSessionProps(o,"sessionProperties"),!De(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async t=>{if(!Fe(t)){const{message:n}=F("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:s}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!F0(s)){const{message:n}=F("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),R(this,"isValidSessionSettleRequest",t=>{if(!Fe(t)){const{message:u}=F("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(u)}const{relay:i,controller:s,namespaces:n,expiry:o}=t;if(!qh(i)){const{message:u}=F("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=A0(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=mn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(kt(o)){const{message:u}=F("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async t=>{if(!Fe(t)){const{message:c}=F("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:i,namespaces:s}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=mn(s,"update()");if(o)throw new Error(o.message);const a=Bc(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async t=>{if(!Fe(t)){const{message:s}=F("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(s)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),R(this,"isValidRequest",async t=>{if(!Fe(t)){const{message:c}=F("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!jc(a,n)){const{message:c}=F("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!q0(s)){const{message:c}=F("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!M0(a,n,s.method)){const{message:c}=F("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!K0(o,$n)){const{message:c}=F("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${$n.min} and ${$n.max}`);throw new Error(c)}}),R(this,"isValidRespond",async t=>{var i;if(!Fe(t)){const{message:o}=F("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:s,response:n}=t;try{await this.isValidSessionTopic(s)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!L0(n)){const{message:o}=F("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),R(this,"isValidPing",async t=>{if(!Fe(t)){const{message:s}=F("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(s)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidEmit",async t=>{if(!Fe(t)){const{message:a}=F("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!jc(o,n)){const{message:a}=F("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!k0(s)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!z0(o,n,s.name)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async t=>{if(!Fe(t)){const{message:s}=F("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(s)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidAuthenticate",t=>{const{chains:i,uri:s,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!he(s,!1))throw new Error("uri is required parameter");if(!he(n,!1))throw new Error("domain is required parameter");if(!he(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>kr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=kr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async t=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||vi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ae.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach((s,n)=>{if(s==null){const{message:o}=F("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),R(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:s}=F("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(s)}}),R(this,"isLinkModeEnabled",(t,i)=>{var s,n,o,a,c,u,l,h,d;return!t||i!==ae.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=t==null?void 0:t.redirect)==null?void 0:l.universal)!==void 0&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(t,i)=>{var s;return this.isLinkModeEnabled(t,i)?(s=t==null?void 0:t.redirect)==null?void 0:s.universal:void 0}),R(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Za(t,"topic")||"",s=decodeURIComponent(Za(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:ae.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),R(this,"registerLinkModeListeners",async()=>{var t;if(Ro()||Wt()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),R(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:s}=i;return Object.keys(xu).includes(s.method)}),R(this,"getTVFParams",(t,i,s)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,s);return Te(se({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const s=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(t,i)=>{try{const s=xu[t];if(typeof i=="string")return[i];const n=i[s.key];if(ht(n))return t==="solana_signAllTransactions"?n.map(o=>db(o)):n;if(typeof n=="string")return[n]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(t))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(we.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(hs)?this.client.auth.authKeys.get(hs):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===ae.link_mode?Mt:lt});zo(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:s,transportType:n,encryptedId:Et(i)})):qs(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(et.expired,async e=>{const{topic:t,id:i}=sh(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,F("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,F("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(rr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(rr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!he(e,!1)){const{message:t}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(kt(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=F("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!he(e,!1)){const{message:t}=F("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=F("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(kt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=F("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=F("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}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(he(e,!1)){const{message:t}=F("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=F("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!U0(e)){const{message:t}=F("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=F("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(kt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=F("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class iD extends gr{constructor(e,t){super(e,t,kS,Ho),this.core=e,this.logger=t}}let sD=class extends gr{constructor(e,t){super(e,t,MS,Ho),this.core=e,this.logger=t}};class nD extends gr{constructor(e,t){super(e,t,HS,Ho,i=>i.id),this.core=e,this.logger=t}}class oD extends gr{constructor(e,t){super(e,t,GS,ks,()=>hs),this.core=e,this.logger=t}}class aD extends gr{constructor(e,t){super(e,t,YS,ks),this.core=e,this.logger=t}}class cD extends gr{constructor(e,t){super(e,t,JS,ks,i=>i.id),this.core=e,this.logger=t}}var uD=Object.defineProperty,lD=(r,e,t)=>e in r?uD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,An=(r,e,t)=>lD(r,typeof e!="symbol"?e+"":e,t);class hD{constructor(e,t){this.core=e,this.logger=t,An(this,"authKeys"),An(this,"pairingTopics"),An(this,"requests"),this.authKeys=new oD(this.core,this.logger),this.pairingTopics=new aD(this.core,this.logger),this.requests=new cD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var dD=Object.defineProperty,pD=(r,e,t)=>e in r?dD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,G=(r,e,t)=>pD(r,typeof e!="symbol"?e+"":e,t);let fD=class pd extends d1{constructor(e){super(e),G(this,"protocol",ld),G(this,"version",hd),G(this,"name",Pn.name),G(this,"metadata"),G(this,"core"),G(this,"logger"),G(this,"events",new Ye.EventEmitter),G(this,"engine"),G(this,"session"),G(this,"proposal"),G(this,"pendingRequest"),G(this,"auth"),G(this,"signConfig"),G(this,"on",(i,s)=>this.events.on(i,s)),G(this,"once",(i,s)=>this.events.once(i,s)),G(this,"off",(i,s)=>this.events.off(i,s)),G(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),G(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),G(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),G(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),G(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||Pn.name,this.metadata=Dw(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:qi(Bs({level:(e==null?void 0:e.logger)||Pn.logger}));this.core=(e==null?void 0:e.core)||new LS(e),this.logger=Ne(t,this.name),this.session=new sD(this.core,this.logger),this.proposal=new iD(this.core,this.logger),this.pendingRequest=new nD(this.core,this.logger),this.engine=new rD(this),this.auth=new hD(this.core,this.logger)}static async init(e){const t=new pd(e);return await t.initialize(),t}get context(){return ke(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"),setTimeout(()=>{this.engine.processRelayMessageCache()},U.toMiliseconds(U.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Xi={exports:{}},Tu;function gD(){return Tu||(Tu=1,(function(r,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof vt<"u"&&vt,i=(function(){function n(){this.fetch=!1,this.DOMException=t.DOMException}return n.prototype=t,new n})();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof vt<"u"&&vt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function u(y){return y&&DataView.prototype.isPrototypeOf(y)}if(c.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(y){return y&&l.indexOf(Object.prototype.toString.call(y))>-1};function d(y){if(typeof y!="string"&&(y=String(y)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(y)||y==="")throw new TypeError('Invalid character in header field name: "'+y+'"');return y.toLowerCase()}function p(y){return typeof y!="string"&&(y=String(y)),y}function f(y){var m={next:function(){var S=y.shift();return{done:S===void 0,value:S}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function g(y){this.map={},y instanceof g?y.forEach(function(m,S){this.append(S,m)},this):Array.isArray(y)?y.forEach(function(m){if(m.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+m.length);this.append(m[0],m[1])},this):y&&Object.getOwnPropertyNames(y).forEach(function(m){this.append(m,y[m])},this)}g.prototype.append=function(y,m){y=d(y),m=p(m);var S=this.map[y];this.map[y]=S?S+", "+m:m},g.prototype.delete=function(y){delete this.map[d(y)]},g.prototype.get=function(y){return y=d(y),this.has(y)?this.map[y]:null},g.prototype.has=function(y){return this.map.hasOwnProperty(d(y))},g.prototype.set=function(y,m){this.map[d(y)]=p(m)},g.prototype.forEach=function(y,m){for(var S in this.map)this.map.hasOwnProperty(S)&&y.call(m,this.map[S],S,this)},g.prototype.keys=function(){var y=[];return this.forEach(function(m,S){y.push(S)}),f(y)},g.prototype.values=function(){var y=[];return this.forEach(function(m){y.push(m)}),f(y)},g.prototype.entries=function(){var y=[];return this.forEach(function(m,S){y.push([S,m])}),f(y)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function w(y){if(!y._noBody){if(y.bodyUsed)return Promise.reject(new TypeError("Already read"));y.bodyUsed=!0}}function E(y){return new Promise(function(m,S){y.onload=function(){m(y.result)},y.onerror=function(){S(y.error)}})}function b(y){var m=new FileReader,S=E(m);return m.readAsArrayBuffer(y),S}function _(y){var m=new FileReader,S=E(m),x=/charset=([A-Za-z0-9_-]+)/.exec(y.type),O=x?x[1]:"utf-8";return m.readAsText(y,O),S}function A(y){for(var m=new Uint8Array(y),S=new Array(m.length),x=0;x<m.length;x++)S[x]=String.fromCharCode(m[x]);return S.join("")}function T(y){if(y.slice)return y.slice(0);var m=new Uint8Array(y.byteLength);return m.set(new Uint8Array(y)),m.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(y){this.bodyUsed=this.bodyUsed,this._bodyInit=y,y?typeof y=="string"?this._bodyText=y:c.blob&&Blob.prototype.isPrototypeOf(y)?this._bodyBlob=y:c.formData&&FormData.prototype.isPrototypeOf(y)?this._bodyFormData=y:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)?this._bodyText=y.toString():c.arrayBuffer&&c.blob&&u(y)?(this._bodyArrayBuffer=T(y.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(y)||h(y))?this._bodyArrayBuffer=T(y):this._bodyText=y=Object.prototype.toString.call(y):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof y=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var y=w(this);if(y)return y;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var y=w(this);return y||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(b);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var y=w(this);if(y)return y;if(this._bodyBlob)return _(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function P(y){var m=y.toUpperCase();return I.indexOf(m)>-1?m:y}function D(y,m){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var S=m.body;if(y instanceof D){if(y.bodyUsed)throw new TypeError("Already read");this.url=y.url,this.credentials=y.credentials,m.headers||(this.headers=new g(y.headers)),this.method=y.method,this.mode=y.mode,this.signal=y.signal,!S&&y._bodyInit!=null&&(S=y._bodyInit,y.bodyUsed=!0)}else this.url=String(y);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new g(m.headers)),this.method=P(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||(function(){if("AbortController"in a){var C=new AbortController;return C.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(S),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var x=/([?&])_=[^&]*/;if(x.test(this.url))this.url=this.url.replace(x,"$1_="+new Date().getTime());else{var O=/\?/;this.url+=(O.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}D.prototype.clone=function(){return new D(this,{body:this._bodyInit})};function j(y){var m=new FormData;return y.trim().split("&").forEach(function(S){if(S){var x=S.split("="),O=x.shift().replace(/\+/g," "),C=x.join("=").replace(/\+/g," ");m.append(decodeURIComponent(O),decodeURIComponent(C))}}),m}function N(y){var m=new g,S=y.replace(/\r?\n[\t ]+/g," ");return S.split("\r").map(function(x){return x.indexOf(`
|
|
39
|
-
`)===0?x.substr(1,x.length):x}).forEach(function(x){var O=x.split(":"),C=O.shift().trim();if(C){var q=O.join(":").trim();try{m.append(C,q)}catch(k){console.warn("Response "+k.message)}}}),m}v.call(D.prototype);function B(y,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new g(m.headers),this.url=m.url||"",this._initBody(y)}v.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},B.error=function(){var y=new B(null,{status:200,statusText:""});return y.ok=!1,y.status=0,y.type="error",y};var M=[301,302,303,307,308];B.redirect=function(y,m){if(M.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:y}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,S){this.message=m,this.name=S;var x=Error(m);this.stack=x.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(y,m){return new Promise(function(S,x){var O=new D(y,m);if(O.signal&&O.signal.aborted)return x(new o.DOMException("Aborted","AbortError"));var C=new XMLHttpRequest;function q(){C.abort()}C.onload=function(){var L={statusText:C.statusText,headers:N(C.getAllResponseHeaders()||"")};O.url.indexOf("file://")===0&&(C.status<200||C.status>599)?L.status=200:L.status=C.status,L.url="responseURL"in C?C.responseURL:L.headers.get("X-Request-URL");var H="response"in C?C.response:C.responseText;setTimeout(function(){S(new B(H,L))},0)},C.onerror=function(){setTimeout(function(){x(new TypeError("Network request failed"))},0)},C.ontimeout=function(){setTimeout(function(){x(new TypeError("Network request timed out"))},0)},C.onabort=function(){setTimeout(function(){x(new o.DOMException("Aborted","AbortError"))},0)};function k(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(C.open(O.method,k(O.url),!0),O.credentials==="include"?C.withCredentials=!0:O.credentials==="omit"&&(C.withCredentials=!1),"responseType"in C&&(c.blob?C.responseType="blob":c.arrayBuffer&&(C.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof g||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(L){z.push(d(L)),C.setRequestHeader(L,p(m.headers[L]))}),O.headers.forEach(function(L,H){z.indexOf(H)===-1&&C.setRequestHeader(H,L)})}else O.headers.forEach(function(L,H){C.setRequestHeader(H,L)});O.signal&&(O.signal.addEventListener("abort",q),C.onreadystatechange=function(){C.readyState===4&&O.signal.removeEventListener("abort",q)}),C.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=g,a.Request=D,a.Response=B),o.Headers=g,o.Request=D,o.Response=B,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=t.fetch?t:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,r.exports=e})(Xi,Xi.exports)),Xi.exports}var yD=gD();const Ru=Io(yD);var mD=Object.defineProperty,wD=Object.defineProperties,bD=Object.getOwnPropertyDescriptors,Nu=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,ED=Object.prototype.propertyIsEnumerable,ju=(r,e,t)=>e in r?mD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Bu=(r,e)=>{for(var t in e||(e={}))vD.call(e,t)&&ju(r,t,e[t]);if(Nu)for(var t of Nu(e))ED.call(e,t)&&ju(r,t,e[t]);return r},Uu=(r,e)=>wD(r,bD(e));const _D={Accept:"application/json","Content-Type":"application/json"},ID="POST",Fu={headers:_D,method:ID},qu=10;let dt=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Ye.EventEmitter,this.isAvailable=!1,this.registering=!1,!eu(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}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 t=Bt(e),i=await(await Ru(this.url,Uu(Bu({},Fu),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!eu(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=Bt({id:1,jsonrpc:"2.0",method:"test",params:[]});await Ru(e,Uu(Bu({},Fu),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);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 t=typeof e.data=="string"?cr(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Fs(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return Hh(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>qu&&this.events.setMaxListeners(qu)}};const Lu="error",SD="wss://relay.walletconnect.org",DD="wc",OD="universal_provider",es=`${DD}@2:${OD}:`,fd="https://rpc.walletconnect.org/v1/",Ur="generic",PD=`${fd}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function $D(){}function Vo(r){return r==null||typeof r!="object"&&typeof r!="function"}function Ko(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function AD(r){if(Vo(r))return r;if(Array.isArray(r)||Ko(r)||r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);const e=Object.getPrototypeOf(r),t=e.constructor;if(r instanceof Date||r instanceof Map||r instanceof Set)return new t(r);if(r instanceof RegExp){const i=new t(r);return i.lastIndex=r.lastIndex,i}if(r instanceof DataView)return new t(r.buffer.slice(0));if(r instanceof Error){const i=new t(r.message);return i.stack=r.stack,i.name=r.name,i.cause=r.cause,i}if(typeof File<"u"&&r instanceof File)return new t([r],r.name,{type:r.type,lastModified:r.lastModified});if(typeof r=="object"){const i=Object.create(e);return Object.assign(i,r)}return r}function ku(r){return typeof r=="object"&&r!==null}function gd(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function yd(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const xD="[object RegExp]",md="[object String]",wd="[object Number]",bd="[object Boolean]",vd="[object Arguments]",CD="[object Symbol]",TD="[object Date]",RD="[object Map]",ND="[object Set]",jD="[object Array]",BD="[object ArrayBuffer]",UD="[object Object]",FD="[object DataView]",qD="[object Uint8Array]",LD="[object Uint8ClampedArray]",kD="[object Uint16Array]",MD="[object Uint32Array]",zD="[object Int8Array]",HD="[object Int16Array]",VD="[object Int32Array]",KD="[object Float32Array]",WD="[object Float64Array]";function GD(r,e){return Lr(r,void 0,r,new Map,e)}function Lr(r,e,t,i=new Map,s=void 0){const n=s==null?void 0:s(r,e,t,i);if(n!=null)return n;if(Vo(r))return r;if(i.has(r))return i.get(r);if(Array.isArray(r)){const o=new Array(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Lr(r[a],a,t,i,s);return Object.hasOwn(r,"index")&&(o.index=r.index),Object.hasOwn(r,"input")&&(o.input=r.input),o}if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp){const o=new RegExp(r.source,r.flags);return o.lastIndex=r.lastIndex,o}if(r instanceof Map){const o=new Map;i.set(r,o);for(const[a,c]of r)o.set(a,Lr(c,a,t,i,s));return o}if(r instanceof Set){const o=new Set;i.set(r,o);for(const a of r)o.add(Lr(a,void 0,t,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(r))return r.subarray();if(Ko(r)){const o=new(Object.getPrototypeOf(r)).constructor(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Lr(r[a],a,t,i,s);return o}if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);if(r instanceof DataView){const o=new DataView(r.buffer.slice(0),r.byteOffset,r.byteLength);return i.set(r,o),ir(o,r,t,i,s),o}if(typeof File<"u"&&r instanceof File){const o=new File([r],r.name,{type:r.type});return i.set(r,o),ir(o,r,t,i,s),o}if(r instanceof Blob){const o=new Blob([r],{type:r.type});return i.set(r,o),ir(o,r,t,i,s),o}if(r instanceof Error){const o=new r.constructor;return i.set(r,o),o.message=r.message,o.name=r.name,o.stack=r.stack,o.cause=r.cause,ir(o,r,t,i,s),o}if(typeof r=="object"&&YD(r)){const o=Object.create(Object.getPrototypeOf(r));return i.set(r,o),ir(o,r,t,i,s),o}return r}function ir(r,e,t=r,i,s){const n=[...Object.keys(e),...gd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(r,a);(c==null||c.writable)&&(r[a]=Lr(e[a],a,t,i,s))}}function YD(r){switch(yd(r)){case vd:case jD:case BD:case FD:case bd:case TD:case KD:case WD:case zD:case HD:case VD:case RD:case wd:case UD:case xD:case ND:case md:case CD:case qD:case LD:case kD:case MD:return!0;default:return!1}}function JD(r,e){return GD(r,(t,i,s,n)=>{if(typeof r=="object")switch(Object.prototype.toString.call(r)){case wd:case md:case bd:{const o=new r.constructor(r==null?void 0:r.valueOf());return ir(o,r),o}case vd:{const o={};return ir(o,r),o.length=r.length,o[Symbol.iterator]=r[Symbol.iterator],o}default:return}})}function Mu(r){return JD(r)}function zu(r){return r!==null&&typeof r=="object"&&yd(r)==="[object Arguments]"}function ZD(r){return Ko(r)}function QD(r){var t;if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const i=r[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag))!=null&&t.writable)?!1:r.toString()===`[object ${i}]`}let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function XD(r,...e){const t=e.slice(0,-1),i=e[e.length-1];let s=r;for(let n=0;n<t.length;n++){const o=t[n];s=bo(s,o,i,new Map)}return s}function bo(r,e,t,i){if(Vo(r)&&(r=Object(r)),e==null||typeof e!="object")return r;if(i.has(e))return AD(i.get(e));if(i.set(e,r),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...gd(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=r[o];if(zu(a)&&(a={...a}),zu(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Mu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const p=h[d];l[p]=c[p]}c=l}else c=[];const u=t(c,a,o,r,e,i);u!=null?r[o]=u:Array.isArray(a)||ku(c)&&ku(a)?r[o]=bo(c,a,t,i):c==null&&QD(a)?r[o]=bo({},a,t,i):c==null&&ZD(a)?r[o]=Mu(a):(c===void 0||a!==void 0)&&(r[o]=a)}return r}function eO(r,...e){return XD(r,...e,$D)}var tO=Object.defineProperty,rO=Object.defineProperties,iO=Object.getOwnPropertyDescriptors,Hu=Object.getOwnPropertySymbols,sO=Object.prototype.hasOwnProperty,nO=Object.prototype.propertyIsEnumerable,Vu=(r,e,t)=>e in r?tO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ts=(r,e)=>{for(var t in e||(e={}))sO.call(e,t)&&Vu(r,t,e[t]);if(Hu)for(var t of Hu(e))nO.call(e,t)&&Vu(r,t,e[t]);return r},oO=(r,e)=>rO(r,iO(e));function Ge(r,e,t){var i;const s=kr(r);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${fd}?chainId=${s.namespace}:${s.reference}&projectId=${t}`}function yr(r){return r.includes(":")?r.split(":")[1]:r}function Ed(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function aO(r,e){const t=Object.keys(e.namespaces).filter(s=>s.includes(r));if(!t.length)return[];const i=[];return t.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function rs(r={},e={}){const t=Ku(r),i=Ku(e);return eO(t,i)}function Ku(r){var e,t,i,s,n;const o={};if(!Kt(r))return o;for(const[a,c]of Object.entries(r)){const u=js(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],d=c.rpcMap||{},p=qr(a);o[p]=oO(ts(ts({},o[p]),c),{chains:_t(u,(e=o[p])==null?void 0:e.chains),methods:_t(l,(t=o[p])==null?void 0:t.methods),events:_t(h,(i=o[p])==null?void 0:i.events)}),(Kt(d)||Kt(((s=o[p])==null?void 0:s.rpcMap)||{}))&&(o[p].rpcMap=ts(ts({},d),(n=o[p])==null?void 0:n.rpcMap))}return o}function Wu(r){return r.includes(":")?r.split(":")[2]:r}function Gu(r){const e={};for(const[t,i]of Object.entries(r)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=js(t)?[t]:i.chains?i.chains:Ed(i.accounts);e[t]={chains:a,methods:s,events:n,accounts:o}}return e}function xn(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const _d={},Q=r=>_d[r],Cn=(r,e)=>{_d[r]=e};var cO=Object.defineProperty,uO=(r,e,t)=>e in r?cO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>uO(r,typeof e!="symbol"?e+"":e,t);class lO{constructor(e){Dr(this,"name","polkadot"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var hO=Object.defineProperty,dO=Object.defineProperties,pO=Object.getOwnPropertyDescriptors,Yu=Object.getOwnPropertySymbols,fO=Object.prototype.hasOwnProperty,gO=Object.prototype.propertyIsEnumerable,vo=(r,e,t)=>e in r?hO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ju=(r,e)=>{for(var t in e||(e={}))fO.call(e,t)&&vo(r,t,e[t]);if(Yu)for(var t of Yu(e))gO.call(e,t)&&vo(r,t,e[t]);return r},Zu=(r,e)=>dO(r,pO(e)),Or=(r,e,t)=>vo(r,typeof e!="symbol"?e+"":e,t);class yO{constructor(e){Or(this,"name","eip155"),Or(this,"client"),Or(this,"chainId"),Or(this,"namespace"),Or(this,"httpProviders"),Or(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}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)}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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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,t){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=parseInt(yr(t));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let s=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. 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 t,i,s,n,o;const a=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],u=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),h=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[u])return h==null?void 0:h[u];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Zu(Ju({},l.sessionProperties||{}),{capabilities:Zu(Ju({},h||{}),{[u]:d})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return d}async getCallStatus(e){var t,i;const s=this.client.session.get(e.topic),n=(t=s.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}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,t){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ht("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${PD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var mO=Object.defineProperty,wO=(r,e,t)=>e in r?mO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e,t)=>wO(r,typeof e!="symbol"?e+"":e,t);class bO{constructor(e){Pr(this,"name","solana"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var vO=Object.defineProperty,EO=(r,e,t)=>e in r?vO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$r=(r,e,t)=>EO(r,typeof e!="symbol"?e+"":e,t);class _O{constructor(e){$r(this,"name","cosmos"),$r(this,"client"),$r(this,"httpProviders"),$r(this,"events"),$r(this,"namespace"),$r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var IO=Object.defineProperty,SO=(r,e,t)=>e in r?IO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>SO(r,typeof e!="symbol"?e+"":e,t);class DO{constructor(e){Ar(this,"name","algorand"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var OO=Object.defineProperty,PO=(r,e,t)=>e in r?OO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e,t)=>PO(r,typeof e!="symbol"?e+"":e,t);class $O{constructor(e){xr(this,"name","cip34"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),s=yr(t);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var AO=Object.defineProperty,xO=(r,e,t)=>e in r?AO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Cr=(r,e,t)=>xO(r,typeof e!="symbol"?e+"":e,t);class CO{constructor(e){Cr(this,"name","elrond"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var TO=Object.defineProperty,RO=(r,e,t)=>e in r?TO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tr=(r,e,t)=>RO(r,typeof e!="symbol"?e+"":e,t);class NO{constructor(e){Tr(this,"name","multiversx"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var jO=Object.defineProperty,BO=(r,e,t)=>e in r?jO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rr=(r,e,t)=>BO(r,typeof e!="symbol"?e+"":e,t);class UO{constructor(e){Rr(this,"name","near"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var FO=Object.defineProperty,qO=(r,e,t)=>e in r?FO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Nr=(r,e,t)=>qO(r,typeof e!="symbol"?e+"":e,t);class LO{constructor(e){Nr(this,"name","tezos"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var kO=Object.defineProperty,MO=(r,e,t)=>e in r?kO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,jr=(r,e,t)=>MO(r,typeof e!="symbol"?e+"":e,t);class zO{constructor(e){jr(this,"name",Ur),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(s=>{const n=kr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var HO=Object.defineProperty,VO=Object.defineProperties,KO=Object.getOwnPropertyDescriptors,Qu=Object.getOwnPropertySymbols,WO=Object.prototype.hasOwnProperty,GO=Object.prototype.propertyIsEnumerable,Eo=(r,e,t)=>e in r?HO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,is=(r,e)=>{for(var t in e||(e={}))WO.call(e,t)&&Eo(r,t,e[t]);if(Qu)for(var t of Qu(e))GO.call(e,t)&&Eo(r,t,e[t]);return r},Tn=(r,e)=>VO(r,KO(e)),Xe=(r,e,t)=>Eo(r,typeof e!="symbol"?e+"":e,t);let YO=class Id{constructor(e){Xe(this,"client"),Xe(this,"namespaces"),Xe(this,"optionalNamespaces"),Xe(this,"sessionProperties"),Xe(this,"scopedProperties"),Xe(this,"events",new So),Xe(this,"rpcProviders",{}),Xe(this,"session"),Xe(this,"providerOpts"),Xe(this,"logger"),Xe(this,"uri"),Xe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:qi(Bs({level:(e==null?void 0:e.logger)||Lu})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Id(e);return await t.initialize(),t}async request(e,t,i){const[s,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:is({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>t(null,Us(n,o))).catch(o=>t(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Gu(this.session.namespaces);this.namespaces=rs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const n=Gu(s.namespaces);return this.namespaces=rs(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Ur?n.setDefaultChain(`${i}:${s}`,t):n.setDefaultChain(s,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(ht(t)){for(const i of t)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: ${t.length}`)}}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,t;if(this.client=this.providerOpts.client||await fD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Lu,relayUrl:this.providerOpts.relayUrl||SD,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("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.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(t=>qr(t)))];Cn("client",this.client),Cn("events",this.events),Cn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=aO(t,this.session),s=Ed(i),n=rs(this.namespaces,this.optionalNamespaces),o=Tn(is({},n[t]),{accounts:i,chains:s});switch(t){case"eip155":this.rpcProviders[t]=new yO({namespace:o});break;case"algorand":this.rpcProviders[t]=new DO({namespace:o});break;case"solana":this.rpcProviders[t]=new bO({namespace:o});break;case"cosmos":this.rpcProviders[t]=new _O({namespace:o});break;case"polkadot":this.rpcProviders[t]=new lO({namespace:o});break;case"cip34":this.rpcProviders[t]=new $O({namespace:o});break;case"elrond":this.rpcProviders[t]=new CO({namespace:o});break;case"multiversx":this.rpcProviders[t]=new NO({namespace:o});break;case"near":this.rpcProviders[t]=new UO({namespace:o});break;case"tezos":this.rpcProviders[t]=new LO({namespace:o});break;default:this.rpcProviders[Ur]?this.rpcProviders[Ur].updateNamespace(o):this.rpcProviders[Ur]=new zO({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:s}=e;if(s!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&ht(o)&&this.events.emit("accountsChanged",o.map(Wu))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=qr(o),u=xn(o)!==xn(a)?`${c}:${xn(a)}`:o;this.onChainChanged(u)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Tn(is({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Tn(is({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Ur]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=rs(t,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>qr(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=qr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();t||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:i}){var s,n;try{if(t===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Wu);if(!ht(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){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,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${es}/${e}${s}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${es}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${es}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(es)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const JO=YO,ZO="wc",QO="ethereum_provider",XO=`${ZO}@2:${QO}:`,eP="https://rpc.walletconnect.org/v1/",Es=["eth_sendTransaction","personal_sign"],Sd=["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"],_s=["chainChanged","accountsChanged"],Dd=["chainChanged","accountsChanged","message","disconnect","connect"],tP=async()=>{const{createAppKit:r}=await il(()=>import("./core-Y_nUy5Fn.js").then(e=>e.X),__vite__mapDeps([4,1,2]));return r};var rP=Object.defineProperty,iP=Object.defineProperties,sP=Object.getOwnPropertyDescriptors,Xu=Object.getOwnPropertySymbols,nP=Object.prototype.hasOwnProperty,oP=Object.prototype.propertyIsEnumerable,_o=(r,e,t)=>e in r?rP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Xt=(r,e)=>{for(var t in e||(e={}))nP.call(e,t)&&_o(r,t,e[t]);if(Xu)for(var t of Xu(e))oP.call(e,t)&&_o(r,t,e[t]);return r},fi=(r,e)=>iP(r,sP(e)),ze=(r,e,t)=>_o(r,typeof e!="symbol"?e+"":e,t);function Is(r){return Number(r[0].split(":")[1])}function ss(r){return`0x${r.toString(16)}`}function aP(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=r;if(!ht(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Es,events:n||_s,rpcMap:Xt({},e.length?{[Is(e)]:a[Is(e)]}:{})},u=n==null?void 0:n.filter(p=>!_s.includes(p)),l=i==null?void 0:i.filter(p=>!Es.includes(p));if(!t&&!o&&!s&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!t,d={chains:[...new Set(h?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Sd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Dd))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class Ms{constructor(){ze(this,"events",new Ye.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",XO),ze(this,"on",(e,t)=>(this.events.on(e,t),this)),ze(this,"once",(e,t)=>(this.events.once(e,t),this)),ze(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),ze(this,"off",(e,t)=>(this.events.off(e,t),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Ms;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,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 t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=aP(this.rpc);try{const n=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.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(fi(Xt({namespaces:Xt({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(d=>{a(d)}).catch(d=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Ka(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ss(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){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 s=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(fi(Xt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=s.session;if(n){const o=Ka(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ss(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}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:t}=e,{event:i}=t;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 t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",ss(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",fi(Xt({},te("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 t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",ss(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const s=(t=e==null?void 0:e.chains)!=null?t:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Es:[],c=s.length?(e==null?void 0:e.events)||_s:[],u=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(p=>this.formatChainId(p)),optionalChains:n.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Is(this.rpc.chains):Is(this.rpc.optionalChains),this.signer=await JO.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 t;try{const i=await tP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return wP}),n=s(fi(Xt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=i(fi(Xt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&ht(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&ht(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${eP}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}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(t=>this.parseAccount(t))}}const cP=Ms;var uP=Object.defineProperty,lP=Object.defineProperties,hP=Object.getOwnPropertyDescriptors,el=Object.getOwnPropertySymbols,dP=Object.prototype.hasOwnProperty,pP=Object.prototype.propertyIsEnumerable,tl=(r,e,t)=>e in r?uP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Od=(r,e)=>{for(var t in e||(e={}))dP.call(e,t)&&tl(r,t,e[t]);if(el)for(var t of el(e))pP.call(e,t)&&tl(r,t,e[t]);return r},fP=(r,e)=>lP(r,hP(e));function gP(r){if(r)return{"--w3m-font-family":r["--wcm-font-family"],"--w3m-accent":r["--wcm-accent-color"],"--w3m-color-mix":r["--wcm-background-color"],"--w3m-z-index":r["--wcm-z-index"]?Number(r["--wcm-z-index"]):void 0,"--w3m-qr-color":r["--wcm-accent-color"],"--w3m-font-size-master":r["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":r["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const yP=r=>{const[e,t]=r.split(":");return Pd({id:t,caipNetworkId:r,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function mP(r){var e,t,i,s,n,o,a;const c=(e=r.chains)==null?void 0:e.map(yP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var d;return h.id===((d=r.defaultChain)==null?void 0:d.id)}),l={projectId:r.projectId,networks:c,themeMode:r.themeMode,themeVariables:gP(r.themeVariables),chainImages:r.chainImages,connectorImages:r.walletImages,defaultNetwork:u,metadata:fP(Od({},r.metadata),{name:((t=r.metadata)==null?void 0:t.name)||"WalletConnect",description:((i=r.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=r.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=r.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:r.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(r.explorerRecommendedWalletIds)?r.explorerRecommendedWalletIds:[],excludeWalletIds:r.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(r.explorerExcludedWalletIds)?r.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=r.mobileWallets)!=null&&o.length||(a=r.desktopWallets)!=null&&a.length){const h=[...(r.mobileWallets||[]).map(f=>({id:f.id,name:f.name,links:f.links})),...(r.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],p=h.filter(f=>!d.includes(f.id));p.length&&(l.customWallets=p)}return l}function Pd(r){return Od({formatters:void 0,fees:void 0,serializers:void 0},r)}var wP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:mP,defineChain:Pd});const u$=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:cP,OPTIONAL_EVENTS:Dd,OPTIONAL_METHODS:Sd,REQUIRED_EVENTS:_s,REQUIRED_METHODS:Es,default:Ms},Symbol.toStringTag,{value:"Module"}));export{WE as A,it as B,hw as C,i_ as D,Ne as E,zo as F,qs as G,rf as H,pr as I,Us as J,fm as K,Bt as L,cr as M,So as N,qi as O,za as P,Gl as Q,nr as R,Fs as S,bt as T,tt as U,wt as V,dt as W,u$ as X,wa as a,Kp as b,_P as c,EP as d,Ds as e,DP as f,SP as g,Cp as h,rt as i,Le as j,U as k,jt as l,Yd as m,mi as n,_f as o,Ye as p,Bs as q,IP as r,zn as s,gl as t,tE as u,xE as v,sf as w,Ht as x,ke as y,fr as z};
|
|
39
|
+
`)===0?x.substr(1,x.length):x}).forEach(function(x){var O=x.split(":"),C=O.shift().trim();if(C){var q=O.join(":").trim();try{m.append(C,q)}catch(k){console.warn("Response "+k.message)}}}),m}v.call(D.prototype);function B(y,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new g(m.headers),this.url=m.url||"",this._initBody(y)}v.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},B.error=function(){var y=new B(null,{status:200,statusText:""});return y.ok=!1,y.status=0,y.type="error",y};var M=[301,302,303,307,308];B.redirect=function(y,m){if(M.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:y}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,S){this.message=m,this.name=S;var x=Error(m);this.stack=x.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(y,m){return new Promise(function(S,x){var O=new D(y,m);if(O.signal&&O.signal.aborted)return x(new o.DOMException("Aborted","AbortError"));var C=new XMLHttpRequest;function q(){C.abort()}C.onload=function(){var L={statusText:C.statusText,headers:N(C.getAllResponseHeaders()||"")};O.url.indexOf("file://")===0&&(C.status<200||C.status>599)?L.status=200:L.status=C.status,L.url="responseURL"in C?C.responseURL:L.headers.get("X-Request-URL");var H="response"in C?C.response:C.responseText;setTimeout(function(){S(new B(H,L))},0)},C.onerror=function(){setTimeout(function(){x(new TypeError("Network request failed"))},0)},C.ontimeout=function(){setTimeout(function(){x(new TypeError("Network request timed out"))},0)},C.onabort=function(){setTimeout(function(){x(new o.DOMException("Aborted","AbortError"))},0)};function k(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(C.open(O.method,k(O.url),!0),O.credentials==="include"?C.withCredentials=!0:O.credentials==="omit"&&(C.withCredentials=!1),"responseType"in C&&(c.blob?C.responseType="blob":c.arrayBuffer&&(C.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof g||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(L){z.push(d(L)),C.setRequestHeader(L,p(m.headers[L]))}),O.headers.forEach(function(L,H){z.indexOf(H)===-1&&C.setRequestHeader(H,L)})}else O.headers.forEach(function(L,H){C.setRequestHeader(H,L)});O.signal&&(O.signal.addEventListener("abort",q),C.onreadystatechange=function(){C.readyState===4&&O.signal.removeEventListener("abort",q)}),C.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=g,a.Request=D,a.Response=B),o.Headers=g,o.Request=D,o.Response=B,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=t.fetch?t:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,r.exports=e})(Xi,Xi.exports)),Xi.exports}var yD=gD();const Ru=Io(yD);var mD=Object.defineProperty,wD=Object.defineProperties,bD=Object.getOwnPropertyDescriptors,Nu=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,ED=Object.prototype.propertyIsEnumerable,ju=(r,e,t)=>e in r?mD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Bu=(r,e)=>{for(var t in e||(e={}))vD.call(e,t)&&ju(r,t,e[t]);if(Nu)for(var t of Nu(e))ED.call(e,t)&&ju(r,t,e[t]);return r},Uu=(r,e)=>wD(r,bD(e));const _D={Accept:"application/json","Content-Type":"application/json"},ID="POST",Fu={headers:_D,method:ID},qu=10;let dt=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Ye.EventEmitter,this.isAvailable=!1,this.registering=!1,!eu(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}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 t=Bt(e),i=await(await Ru(this.url,Uu(Bu({},Fu),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!eu(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=Bt({id:1,jsonrpc:"2.0",method:"test",params:[]});await Ru(e,Uu(Bu({},Fu),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);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 t=typeof e.data=="string"?cr(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Fs(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return Hh(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>qu&&this.events.setMaxListeners(qu)}};const Lu="error",SD="wss://relay.walletconnect.org",DD="wc",OD="universal_provider",es=`${DD}@2:${OD}:`,fd="https://rpc.walletconnect.org/v1/",Ur="generic",PD=`${fd}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function $D(){}function Vo(r){return r==null||typeof r!="object"&&typeof r!="function"}function Ko(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function AD(r){if(Vo(r))return r;if(Array.isArray(r)||Ko(r)||r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);const e=Object.getPrototypeOf(r),t=e.constructor;if(r instanceof Date||r instanceof Map||r instanceof Set)return new t(r);if(r instanceof RegExp){const i=new t(r);return i.lastIndex=r.lastIndex,i}if(r instanceof DataView)return new t(r.buffer.slice(0));if(r instanceof Error){const i=new t(r.message);return i.stack=r.stack,i.name=r.name,i.cause=r.cause,i}if(typeof File<"u"&&r instanceof File)return new t([r],r.name,{type:r.type,lastModified:r.lastModified});if(typeof r=="object"){const i=Object.create(e);return Object.assign(i,r)}return r}function ku(r){return typeof r=="object"&&r!==null}function gd(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function yd(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const xD="[object RegExp]",md="[object String]",wd="[object Number]",bd="[object Boolean]",vd="[object Arguments]",CD="[object Symbol]",TD="[object Date]",RD="[object Map]",ND="[object Set]",jD="[object Array]",BD="[object ArrayBuffer]",UD="[object Object]",FD="[object DataView]",qD="[object Uint8Array]",LD="[object Uint8ClampedArray]",kD="[object Uint16Array]",MD="[object Uint32Array]",zD="[object Int8Array]",HD="[object Int16Array]",VD="[object Int32Array]",KD="[object Float32Array]",WD="[object Float64Array]";function GD(r,e){return Lr(r,void 0,r,new Map,e)}function Lr(r,e,t,i=new Map,s=void 0){const n=s==null?void 0:s(r,e,t,i);if(n!=null)return n;if(Vo(r))return r;if(i.has(r))return i.get(r);if(Array.isArray(r)){const o=new Array(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Lr(r[a],a,t,i,s);return Object.hasOwn(r,"index")&&(o.index=r.index),Object.hasOwn(r,"input")&&(o.input=r.input),o}if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp){const o=new RegExp(r.source,r.flags);return o.lastIndex=r.lastIndex,o}if(r instanceof Map){const o=new Map;i.set(r,o);for(const[a,c]of r)o.set(a,Lr(c,a,t,i,s));return o}if(r instanceof Set){const o=new Set;i.set(r,o);for(const a of r)o.add(Lr(a,void 0,t,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(r))return r.subarray();if(Ko(r)){const o=new(Object.getPrototypeOf(r)).constructor(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Lr(r[a],a,t,i,s);return o}if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);if(r instanceof DataView){const o=new DataView(r.buffer.slice(0),r.byteOffset,r.byteLength);return i.set(r,o),ir(o,r,t,i,s),o}if(typeof File<"u"&&r instanceof File){const o=new File([r],r.name,{type:r.type});return i.set(r,o),ir(o,r,t,i,s),o}if(r instanceof Blob){const o=new Blob([r],{type:r.type});return i.set(r,o),ir(o,r,t,i,s),o}if(r instanceof Error){const o=new r.constructor;return i.set(r,o),o.message=r.message,o.name=r.name,o.stack=r.stack,o.cause=r.cause,ir(o,r,t,i,s),o}if(typeof r=="object"&&YD(r)){const o=Object.create(Object.getPrototypeOf(r));return i.set(r,o),ir(o,r,t,i,s),o}return r}function ir(r,e,t=r,i,s){const n=[...Object.keys(e),...gd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(r,a);(c==null||c.writable)&&(r[a]=Lr(e[a],a,t,i,s))}}function YD(r){switch(yd(r)){case vd:case jD:case BD:case FD:case bd:case TD:case KD:case WD:case zD:case HD:case VD:case RD:case wd:case UD:case xD:case ND:case md:case CD:case qD:case LD:case kD:case MD:return!0;default:return!1}}function JD(r,e){return GD(r,(t,i,s,n)=>{if(typeof r=="object")switch(Object.prototype.toString.call(r)){case wd:case md:case bd:{const o=new r.constructor(r==null?void 0:r.valueOf());return ir(o,r),o}case vd:{const o={};return ir(o,r),o.length=r.length,o[Symbol.iterator]=r[Symbol.iterator],o}default:return}})}function Mu(r){return JD(r)}function zu(r){return r!==null&&typeof r=="object"&&yd(r)==="[object Arguments]"}function ZD(r){return Ko(r)}function QD(r){var t;if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const i=r[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag))!=null&&t.writable)?!1:r.toString()===`[object ${i}]`}let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function XD(r,...e){const t=e.slice(0,-1),i=e[e.length-1];let s=r;for(let n=0;n<t.length;n++){const o=t[n];s=bo(s,o,i,new Map)}return s}function bo(r,e,t,i){if(Vo(r)&&(r=Object(r)),e==null||typeof e!="object")return r;if(i.has(e))return AD(i.get(e));if(i.set(e,r),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...gd(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=r[o];if(zu(a)&&(a={...a}),zu(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Mu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const p=h[d];l[p]=c[p]}c=l}else c=[];const u=t(c,a,o,r,e,i);u!=null?r[o]=u:Array.isArray(a)||ku(c)&&ku(a)?r[o]=bo(c,a,t,i):c==null&&QD(a)?r[o]=bo({},a,t,i):c==null&&ZD(a)?r[o]=Mu(a):(c===void 0||a!==void 0)&&(r[o]=a)}return r}function eO(r,...e){return XD(r,...e,$D)}var tO=Object.defineProperty,rO=Object.defineProperties,iO=Object.getOwnPropertyDescriptors,Hu=Object.getOwnPropertySymbols,sO=Object.prototype.hasOwnProperty,nO=Object.prototype.propertyIsEnumerable,Vu=(r,e,t)=>e in r?tO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ts=(r,e)=>{for(var t in e||(e={}))sO.call(e,t)&&Vu(r,t,e[t]);if(Hu)for(var t of Hu(e))nO.call(e,t)&&Vu(r,t,e[t]);return r},oO=(r,e)=>rO(r,iO(e));function Ge(r,e,t){var i;const s=kr(r);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${fd}?chainId=${s.namespace}:${s.reference}&projectId=${t}`}function yr(r){return r.includes(":")?r.split(":")[1]:r}function Ed(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function aO(r,e){const t=Object.keys(e.namespaces).filter(s=>s.includes(r));if(!t.length)return[];const i=[];return t.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function rs(r={},e={}){const t=Ku(r),i=Ku(e);return eO(t,i)}function Ku(r){var e,t,i,s,n;const o={};if(!Kt(r))return o;for(const[a,c]of Object.entries(r)){const u=js(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],d=c.rpcMap||{},p=qr(a);o[p]=oO(ts(ts({},o[p]),c),{chains:_t(u,(e=o[p])==null?void 0:e.chains),methods:_t(l,(t=o[p])==null?void 0:t.methods),events:_t(h,(i=o[p])==null?void 0:i.events)}),(Kt(d)||Kt(((s=o[p])==null?void 0:s.rpcMap)||{}))&&(o[p].rpcMap=ts(ts({},d),(n=o[p])==null?void 0:n.rpcMap))}return o}function Wu(r){return r.includes(":")?r.split(":")[2]:r}function Gu(r){const e={};for(const[t,i]of Object.entries(r)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=js(t)?[t]:i.chains?i.chains:Ed(i.accounts);e[t]={chains:a,methods:s,events:n,accounts:o}}return e}function xn(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const _d={},Q=r=>_d[r],Cn=(r,e)=>{_d[r]=e};var cO=Object.defineProperty,uO=(r,e,t)=>e in r?cO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>uO(r,typeof e!="symbol"?e+"":e,t);class lO{constructor(e){Dr(this,"name","polkadot"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var hO=Object.defineProperty,dO=Object.defineProperties,pO=Object.getOwnPropertyDescriptors,Yu=Object.getOwnPropertySymbols,fO=Object.prototype.hasOwnProperty,gO=Object.prototype.propertyIsEnumerable,vo=(r,e,t)=>e in r?hO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ju=(r,e)=>{for(var t in e||(e={}))fO.call(e,t)&&vo(r,t,e[t]);if(Yu)for(var t of Yu(e))gO.call(e,t)&&vo(r,t,e[t]);return r},Zu=(r,e)=>dO(r,pO(e)),Or=(r,e,t)=>vo(r,typeof e!="symbol"?e+"":e,t);class yO{constructor(e){Or(this,"name","eip155"),Or(this,"client"),Or(this,"chainId"),Or(this,"namespace"),Or(this,"httpProviders"),Or(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}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)}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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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,t){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=parseInt(yr(t));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let s=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. 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 t,i,s,n,o;const a=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],u=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),h=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[u])return h==null?void 0:h[u];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Zu(Ju({},l.sessionProperties||{}),{capabilities:Zu(Ju({},h||{}),{[u]:d})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return d}async getCallStatus(e){var t,i;const s=this.client.session.get(e.topic),n=(t=s.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}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,t){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ht("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${PD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var mO=Object.defineProperty,wO=(r,e,t)=>e in r?mO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e,t)=>wO(r,typeof e!="symbol"?e+"":e,t);class bO{constructor(e){Pr(this,"name","solana"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var vO=Object.defineProperty,EO=(r,e,t)=>e in r?vO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$r=(r,e,t)=>EO(r,typeof e!="symbol"?e+"":e,t);class _O{constructor(e){$r(this,"name","cosmos"),$r(this,"client"),$r(this,"httpProviders"),$r(this,"events"),$r(this,"namespace"),$r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var IO=Object.defineProperty,SO=(r,e,t)=>e in r?IO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>SO(r,typeof e!="symbol"?e+"":e,t);class DO{constructor(e){Ar(this,"name","algorand"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var OO=Object.defineProperty,PO=(r,e,t)=>e in r?OO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e,t)=>PO(r,typeof e!="symbol"?e+"":e,t);class $O{constructor(e){xr(this,"name","cip34"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),s=yr(t);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var AO=Object.defineProperty,xO=(r,e,t)=>e in r?AO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Cr=(r,e,t)=>xO(r,typeof e!="symbol"?e+"":e,t);class CO{constructor(e){Cr(this,"name","elrond"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var TO=Object.defineProperty,RO=(r,e,t)=>e in r?TO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tr=(r,e,t)=>RO(r,typeof e!="symbol"?e+"":e,t);class NO{constructor(e){Tr(this,"name","multiversx"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=yr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var jO=Object.defineProperty,BO=(r,e,t)=>e in r?jO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rr=(r,e,t)=>BO(r,typeof e!="symbol"?e+"":e,t);class UO{constructor(e){Rr(this,"name","near"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var FO=Object.defineProperty,qO=(r,e,t)=>e in r?FO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Nr=(r,e,t)=>qO(r,typeof e!="symbol"?e+"":e,t);class LO{constructor(e){Nr(this,"name","tezos"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var kO=Object.defineProperty,MO=(r,e,t)=>e in r?kO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,jr=(r,e,t)=>MO(r,typeof e!="symbol"?e+"":e,t);class zO{constructor(e){jr(this,"name",Ur),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(s=>{const n=kr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var HO=Object.defineProperty,VO=Object.defineProperties,KO=Object.getOwnPropertyDescriptors,Qu=Object.getOwnPropertySymbols,WO=Object.prototype.hasOwnProperty,GO=Object.prototype.propertyIsEnumerable,Eo=(r,e,t)=>e in r?HO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,is=(r,e)=>{for(var t in e||(e={}))WO.call(e,t)&&Eo(r,t,e[t]);if(Qu)for(var t of Qu(e))GO.call(e,t)&&Eo(r,t,e[t]);return r},Tn=(r,e)=>VO(r,KO(e)),Xe=(r,e,t)=>Eo(r,typeof e!="symbol"?e+"":e,t);let YO=class Id{constructor(e){Xe(this,"client"),Xe(this,"namespaces"),Xe(this,"optionalNamespaces"),Xe(this,"sessionProperties"),Xe(this,"scopedProperties"),Xe(this,"events",new So),Xe(this,"rpcProviders",{}),Xe(this,"session"),Xe(this,"providerOpts"),Xe(this,"logger"),Xe(this,"uri"),Xe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:qi(Bs({level:(e==null?void 0:e.logger)||Lu})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Id(e);return await t.initialize(),t}async request(e,t,i){const[s,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:is({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>t(null,Us(n,o))).catch(o=>t(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Gu(this.session.namespaces);this.namespaces=rs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const n=Gu(s.namespaces);return this.namespaces=rs(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Ur?n.setDefaultChain(`${i}:${s}`,t):n.setDefaultChain(s,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(ht(t)){for(const i of t)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: ${t.length}`)}}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,t;if(this.client=this.providerOpts.client||await fD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Lu,relayUrl:this.providerOpts.relayUrl||SD,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("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.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(t=>qr(t)))];Cn("client",this.client),Cn("events",this.events),Cn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=aO(t,this.session),s=Ed(i),n=rs(this.namespaces,this.optionalNamespaces),o=Tn(is({},n[t]),{accounts:i,chains:s});switch(t){case"eip155":this.rpcProviders[t]=new yO({namespace:o});break;case"algorand":this.rpcProviders[t]=new DO({namespace:o});break;case"solana":this.rpcProviders[t]=new bO({namespace:o});break;case"cosmos":this.rpcProviders[t]=new _O({namespace:o});break;case"polkadot":this.rpcProviders[t]=new lO({namespace:o});break;case"cip34":this.rpcProviders[t]=new $O({namespace:o});break;case"elrond":this.rpcProviders[t]=new CO({namespace:o});break;case"multiversx":this.rpcProviders[t]=new NO({namespace:o});break;case"near":this.rpcProviders[t]=new UO({namespace:o});break;case"tezos":this.rpcProviders[t]=new LO({namespace:o});break;default:this.rpcProviders[Ur]?this.rpcProviders[Ur].updateNamespace(o):this.rpcProviders[Ur]=new zO({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:s}=e;if(s!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&ht(o)&&this.events.emit("accountsChanged",o.map(Wu))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=qr(o),u=xn(o)!==xn(a)?`${c}:${xn(a)}`:o;this.onChainChanged(u)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Tn(is({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Tn(is({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Ur]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=rs(t,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>qr(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=qr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();t||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:i}){var s,n;try{if(t===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Wu);if(!ht(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){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,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${es}/${e}${s}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${es}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${es}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(es)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const JO=YO,ZO="wc",QO="ethereum_provider",XO=`${ZO}@2:${QO}:`,eP="https://rpc.walletconnect.org/v1/",Es=["eth_sendTransaction","personal_sign"],Sd=["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"],_s=["chainChanged","accountsChanged"],Dd=["chainChanged","accountsChanged","message","disconnect","connect"],tP=async()=>{const{createAppKit:r}=await il(()=>import("./core-JRXsheka.js").then(e=>e.X),__vite__mapDeps([4,1,2]));return r};var rP=Object.defineProperty,iP=Object.defineProperties,sP=Object.getOwnPropertyDescriptors,Xu=Object.getOwnPropertySymbols,nP=Object.prototype.hasOwnProperty,oP=Object.prototype.propertyIsEnumerable,_o=(r,e,t)=>e in r?rP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Xt=(r,e)=>{for(var t in e||(e={}))nP.call(e,t)&&_o(r,t,e[t]);if(Xu)for(var t of Xu(e))oP.call(e,t)&&_o(r,t,e[t]);return r},fi=(r,e)=>iP(r,sP(e)),ze=(r,e,t)=>_o(r,typeof e!="symbol"?e+"":e,t);function Is(r){return Number(r[0].split(":")[1])}function ss(r){return`0x${r.toString(16)}`}function aP(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=r;if(!ht(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Es,events:n||_s,rpcMap:Xt({},e.length?{[Is(e)]:a[Is(e)]}:{})},u=n==null?void 0:n.filter(p=>!_s.includes(p)),l=i==null?void 0:i.filter(p=>!Es.includes(p));if(!t&&!o&&!s&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!t,d={chains:[...new Set(h?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Sd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Dd))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class Ms{constructor(){ze(this,"events",new Ye.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",XO),ze(this,"on",(e,t)=>(this.events.on(e,t),this)),ze(this,"once",(e,t)=>(this.events.once(e,t),this)),ze(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),ze(this,"off",(e,t)=>(this.events.off(e,t),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Ms;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,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 t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=aP(this.rpc);try{const n=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.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(fi(Xt({namespaces:Xt({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(d=>{a(d)}).catch(d=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Ka(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ss(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){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 s=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(fi(Xt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=s.session;if(n){const o=Ka(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ss(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}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:t}=e,{event:i}=t;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 t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",ss(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",fi(Xt({},te("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 t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",ss(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const s=(t=e==null?void 0:e.chains)!=null?t:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Es:[],c=s.length?(e==null?void 0:e.events)||_s:[],u=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(p=>this.formatChainId(p)),optionalChains:n.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Is(this.rpc.chains):Is(this.rpc.optionalChains),this.signer=await JO.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 t;try{const i=await tP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return wP}),n=s(fi(Xt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=i(fi(Xt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&ht(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&ht(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${eP}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}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(t=>this.parseAccount(t))}}const cP=Ms;var uP=Object.defineProperty,lP=Object.defineProperties,hP=Object.getOwnPropertyDescriptors,el=Object.getOwnPropertySymbols,dP=Object.prototype.hasOwnProperty,pP=Object.prototype.propertyIsEnumerable,tl=(r,e,t)=>e in r?uP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Od=(r,e)=>{for(var t in e||(e={}))dP.call(e,t)&&tl(r,t,e[t]);if(el)for(var t of el(e))pP.call(e,t)&&tl(r,t,e[t]);return r},fP=(r,e)=>lP(r,hP(e));function gP(r){if(r)return{"--w3m-font-family":r["--wcm-font-family"],"--w3m-accent":r["--wcm-accent-color"],"--w3m-color-mix":r["--wcm-background-color"],"--w3m-z-index":r["--wcm-z-index"]?Number(r["--wcm-z-index"]):void 0,"--w3m-qr-color":r["--wcm-accent-color"],"--w3m-font-size-master":r["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":r["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const yP=r=>{const[e,t]=r.split(":");return Pd({id:t,caipNetworkId:r,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function mP(r){var e,t,i,s,n,o,a;const c=(e=r.chains)==null?void 0:e.map(yP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var d;return h.id===((d=r.defaultChain)==null?void 0:d.id)}),l={projectId:r.projectId,networks:c,themeMode:r.themeMode,themeVariables:gP(r.themeVariables),chainImages:r.chainImages,connectorImages:r.walletImages,defaultNetwork:u,metadata:fP(Od({},r.metadata),{name:((t=r.metadata)==null?void 0:t.name)||"WalletConnect",description:((i=r.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=r.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=r.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:r.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(r.explorerRecommendedWalletIds)?r.explorerRecommendedWalletIds:[],excludeWalletIds:r.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(r.explorerExcludedWalletIds)?r.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=r.mobileWallets)!=null&&o.length||(a=r.desktopWallets)!=null&&a.length){const h=[...(r.mobileWallets||[]).map(f=>({id:f.id,name:f.name,links:f.links})),...(r.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],p=h.filter(f=>!d.includes(f.id));p.length&&(l.customWallets=p)}return l}function Pd(r){return Od({formatters:void 0,fees:void 0,serializers:void 0},r)}var wP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:mP,defineChain:Pd});const u$=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:cP,OPTIONAL_EVENTS:Dd,OPTIONAL_METHODS:Sd,REQUIRED_EVENTS:_s,REQUIRED_METHODS:Es,default:Ms},Symbol.toStringTag,{value:"Module"}));export{WE as A,it as B,hw as C,i_ as D,Ne as E,zo as F,qs as G,rf as H,pr as I,Us as J,fm as K,Bt as L,cr as M,So as N,qi as O,za as P,Gl as Q,nr as R,Fs as S,bt as T,tt as U,wt as V,dt as W,u$ as X,wa as a,Kp as b,_P as c,EP as d,Ds as e,DP as f,SP as g,Cp as h,rt as i,Le as j,U as k,jt as l,Yd as m,mi as n,_f as o,Ye as p,Bs as q,IP as r,zn as s,gl as t,tE as u,xE as v,sf as w,Ht as x,ke as y,fr as z};
|