@kwespay/widget 1.0.7 → 1.0.8
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/Readme.MD +25 -28
- package/dist/esm/index.js +2 -3
- package/dist/kwespay-widget.js +2 -3
- package/dist/kwespay-widget.min.js +2 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).KwesPayWidget=t()}(this,function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:window;const t={USD:"USD",GHS:"GHS"},n=["USDT","USDC","DAI","BUSD","USDc"],r={graphqlEndpoint:"https://8284-154-161-98-26.ngrok-free.app",currency:t.USD},i={ethereum:{name:"Ethereum",chainId:1,rpcUrl:"https://eth.llamarpc.com",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",explorer:"https://etherscan.io/tx/",type:"mainnet"},polygon:{name:"Polygon",chainId:137,rpcUrl:"https://polygon-rpc.com",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",explorer:"https://polygonscan.com/tx/",type:"mainnet"},base:{name:"Base",chainId:8453,rpcUrl:"https://mainnet.base.org",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/base23.png",explorer:"https://basescan.org/tx/",type:"mainnet"},lisk:{name:"Lisk",chainId:1135,rpcUrl:"https://rpc.api.lisk.com",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/liskt.png",explorer:"https://blockscout.lisk.com/tx/",type:"mainnet"},sepolia:{name:"Sepolia",chainId:11155111,rpcUrl:"https://rpc.sepolia.org",contractAddress:"0x39bE436D6A34d0990cb71c9cBD24a5361d85e00B",logo:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",explorer:"https://sepolia.etherscan.io/tx/",type:"testnet"},polygonAmoy:{name:"Polygon Amoy",chainId:80002,rpcUrl:"https://rpc-amoy.polygon.technology",contractAddress:"0xD31dF3eBd220Fd3e190A346F8927819295d28980",logo:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",explorer:"https://amoy.polygonscan.com/tx/",type:"testnet"},baseSepolia:{name:"Base Sepolia",chainId:84532,rpcUrl:"https://sepolia.base.org",contractAddress:"0x7515b1b1BcA33E7a9ccBd5E2b93771884654De77",logo:"https://arthuremma2.github.io/img-hosting/base23.png",explorer:"https://sepolia.basescan.org/tx/",type:"testnet"},liskTestnet:{name:"Lisk Sepolia",chainId:4202,rpcUrl:"https://rpc.sepolia-api.lisk.com",contractAddress:"0xd04A78a998146EBAD04c2b68E020C06Dc3b3717f",logo:"https://arthuremma2.github.io/img-hosting/liskt.png",explorer:"https://sepolia-blockscout.lisk.com/tx/",type:"testnet"}},s={ethereum:[{symbol:"ETH",name:"Ethereum",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDT",name:"Tether USD",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,coingeckoId:"tether",binanceSymbol:"USDTUSDT"},{symbol:"USDC",name:"USD Coin",icon:"https://move-flow.github.io/assets/usd-coin-usdc-logo.svg",address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,coingeckoId:"usd-coin",binanceSymbol:"USDCUSDT"}],polygon:[{symbol:"MATIC",name:"Polygon",icon:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"matic-network",binanceSymbol:"MATICUSDT"},{symbol:"USDT",name:"Tether USD",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,coingeckoId:"tether",binanceSymbol:"USDTUSDT"}],base:[{symbol:"ETH",name:"Ethereum",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDC",name:"USD Coin",icon:"https://move-flow.github.io/assets/usd-coin-usdc-logo.svg",address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,coingeckoId:"usd-coin",binanceSymbol:"USDCUSDT"}],lisk:[{symbol:"ETH",name:"Lisk",icon:"https://arthuremma2.github.io/img-hosting/liskt.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"}],sepolia:[{symbol:"ETH",name:"Sepolia ETH",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDT",name:"Mock USDT",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0x261322E2378467dd1cF5ac60A66817223db68fA3",decimals:18,coingeckoId:"tether",binanceSymbol:"USDTUSDT"}],polygonAmoy:[{symbol:"MATIC",name:"Amoy MATIC",icon:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"matic-network",binanceSymbol:"MATICUSDT"},{symbol:"USDc",name:"Mock USDT",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0x8B0180f2101c8260d49339abfEe87927412494B4",decimals:6,coingeckoId:"tether",binanceSymbol:"USDTUSDT"}],baseSepolia:[{symbol:"ETH",name:"Base Sepolia ETH",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDC",name:"USD Coin",icon:"https://move-flow.github.io/assets/usd-coin-usdc-logo.svg",address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",decimals:6,coingeckoId:"usd-coin",binanceSymbol:"USDCUSDT"}],liskTestnet:[{symbol:"ETH",name:"Lisk Sepolia",icon:"https://arthuremma2.github.io/img-hosting/lisk-logo.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"LSK",name:"Lisk",icon:"https://arthuremma2.github.io/img-hosting/liskt.png",address:"0x8a21CF9Ba08Ae709D64Cb25AfAA951183EC9FF6D",decimals:18,coingeckoId:"LSK",binanceSymbol:"LSK"}]};var o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{};function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function c(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var l,d={exports:{}},h="object"==typeof Reflect?Reflect:null,u=h&&"function"==typeof h.apply?h.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};l=h&&"function"==typeof h.ownKeys?h.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!=e};function f(){f.init.call(this)}d.exports=f,d.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}k(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&k(e,"error",t,n)}(e,i,{once:!0})})},f.EventEmitter=f,f.prototype._events=void 0,f.prototype._eventsCount=0,f.prototype._maxListeners=void 0;var g=10;function m(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function y(e){return void 0===e._maxListeners?f.defaultMaxListeners:e._maxListeners}function w(e,t,n,r){var i,s,o,a;if(m(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]),void 0===o)o=s[t]=n,++e._eventsCount;else if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),(i=y(e))>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function b(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=b.bind(r);return i.listener=n,r.wrapFn=i,i}function E(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):A(i,i.length)}function x(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function A(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function k(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}Object.defineProperty(f,"defaultMaxListeners",{enumerable:!0,get:function(){return g},set:function(e){if("number"!=typeof e||e<0||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");g=e}}),f.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},f.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},f.prototype.getMaxListeners=function(){return y(this)},f.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)u(a,this,t);else{var c=a.length,l=A(a,c);for(n=0;n<c;++n)u(l[n],this,t)}return!0},f.prototype.addListener=function(e,t){return w(this,e,t,!1)},f.prototype.on=f.prototype.addListener,f.prototype.prependListener=function(e,t){return w(this,e,t,!0)},f.prototype.once=function(e,t){return m(t),this.on(e,v(this,e,t)),this},f.prototype.prependOnceListener=function(e,t){return m(t),this.prependListener(e,v(this,e,t)),this},f.prototype.removeListener=function(e,t){var n,r,i,s,o;if(m(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,o||t)}return this},f.prototype.off=f.prototype.removeListener,f.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,s=Object.keys(n);for(r=0;r<s.length;++r)"removeListener"!==(i=s[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},f.prototype.listeners=function(e){return E(this,e,!0)},f.prototype.rawListeners=function(e){return E(this,e,!1)},f.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):x.call(e,t)},f.prototype.listenerCount=x,f.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]};var I=d.exports,C=a(I),S=window&&window.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))},P=function(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"},N=function(e){this.version=e,this.type="node",this.name="node",this.os=process.platform},_=function(e,t,n,r){this.name=e,this.version=t,this.os=n,this.bot=r,this.type="bot-device"},T=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},O=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},$=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,R=[["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",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],B=[["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 M(e){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new O:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&R.reduce(function(t,n){var r=n[0],i=n[1];if(t)return t;var s=i.exec(e);return!!s&&[r,s]},!1)}(e);if(!t)return null;var n=t[0],r=t[1];if("searchbot"===n)return new T;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<3&&(i=S(S([],i,!0),function(e){for(var t=[],n=0;n<e;n++)t.push("0");return t}(3-i.length),!0)):i=[];var s=i.join("."),o=function(e){for(var t=0,n=B.length;t<n;t++){var r=B[t],i=r[0];if(r[1].exec(e))return i}return null}(e),a=$.exec(e);if(a&&a[1])return new _(n,s,o,a[1]);return new P(n,s,o)}(navigator.userAgent):"undefined"!=typeof process&&process.version?new N(process.version.slice(1)):null}var U={},L=function(e,t){return L=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},L(e,t)};
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).KwesPayWidget=t()}(this,function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:window;const t={USD:"USD",GHS:"GHS"},n=["USDT","USDC","DAI","BUSD","USDc"],r={graphqlEndpoint:"https://api.kwespay.xyz/",currency:t.USD},i={ethereum:{name:"Ethereum",chainId:1,rpcUrl:"https://eth.llamarpc.com",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",explorer:"https://etherscan.io/tx/",type:"mainnet"},polygon:{name:"Polygon",chainId:137,rpcUrl:"https://polygon-rpc.com",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",explorer:"https://polygonscan.com/tx/",type:"mainnet"},base:{name:"Base",chainId:8453,rpcUrl:"https://mainnet.base.org",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/base23.png",explorer:"https://basescan.org/tx/",type:"mainnet"},lisk:{name:"Lisk",chainId:1135,rpcUrl:"https://rpc.api.lisk.com",contractAddress:"",logo:"https://arthuremma2.github.io/img-hosting/liskt.png",explorer:"https://blockscout.lisk.com/tx/",type:"mainnet"},sepolia:{name:"Sepolia",chainId:11155111,rpcUrl:"https://rpc.sepolia.org",contractAddress:"0x39bE436D6A34d0990cb71c9cBD24a5361d85e00B",logo:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",explorer:"https://sepolia.etherscan.io/tx/",type:"testnet"},polygonAmoy:{name:"Polygon Amoy",chainId:80002,rpcUrl:"https://rpc-amoy.polygon.technology",contractAddress:"0xD31dF3eBd220Fd3e190A346F8927819295d28980",logo:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",explorer:"https://amoy.polygonscan.com/tx/",type:"testnet"},baseSepolia:{name:"Base Sepolia",chainId:84532,rpcUrl:"https://sepolia.base.org",contractAddress:"0x7515b1b1BcA33E7a9ccBd5E2b93771884654De77",logo:"https://arthuremma2.github.io/img-hosting/base23.png",explorer:"https://sepolia.basescan.org/tx/",type:"testnet"},liskTestnet:{name:"Lisk Sepolia",chainId:4202,rpcUrl:"https://rpc.sepolia-api.lisk.com",contractAddress:"0xd04A78a998146EBAD04c2b68E020C06Dc3b3717f",logo:"https://arthuremma2.github.io/img-hosting/liskt.png",explorer:"https://sepolia-blockscout.lisk.com/tx/",type:"testnet"}},s={ethereum:[{symbol:"ETH",name:"Ethereum",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDT",name:"Tether USD",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,coingeckoId:"tether",binanceSymbol:"USDTUSDT"},{symbol:"USDC",name:"USD Coin",icon:"https://move-flow.github.io/assets/usd-coin-usdc-logo.svg",address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,coingeckoId:"usd-coin",binanceSymbol:"USDCUSDT"}],polygon:[{symbol:"MATIC",name:"Polygon",icon:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"matic-network",binanceSymbol:"MATICUSDT"},{symbol:"USDT",name:"Tether USD",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,coingeckoId:"tether",binanceSymbol:"USDTUSDT"}],base:[{symbol:"ETH",name:"Ethereum",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDC",name:"USD Coin",icon:"https://move-flow.github.io/assets/usd-coin-usdc-logo.svg",address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,coingeckoId:"usd-coin",binanceSymbol:"USDCUSDT"}],lisk:[{symbol:"ETH",name:"Lisk",icon:"https://arthuremma2.github.io/img-hosting/liskt.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"}],sepolia:[{symbol:"ETH",name:"Sepolia ETH",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDT",name:"Mock USDT",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0x261322E2378467dd1cF5ac60A66817223db68fA3",decimals:18,coingeckoId:"tether",binanceSymbol:"USDTUSDT"}],polygonAmoy:[{symbol:"MATIC",name:"Amoy MATIC",icon:"https://arthuremma2.github.io/img-hosting/Polygon_Icon.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"matic-network",binanceSymbol:"MATICUSDT"},{symbol:"USDc",name:"Mock USDT",icon:"https://move-flow.github.io/assets/tether-usdt-logo.svg",address:"0x8B0180f2101c8260d49339abfEe87927412494B4",decimals:6,coingeckoId:"tether",binanceSymbol:"USDTUSDT"}],baseSepolia:[{symbol:"ETH",name:"Base Sepolia ETH",icon:"https://arthuremma2.github.io/img-hosting/ethereum-eth.svg",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"USDC",name:"USD Coin",icon:"https://move-flow.github.io/assets/usd-coin-usdc-logo.svg",address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",decimals:6,coingeckoId:"usd-coin",binanceSymbol:"USDCUSDT"}],liskTestnet:[{symbol:"ETH",name:"Lisk Sepolia",icon:"https://arthuremma2.github.io/img-hosting/lisk-logo.png",address:"0x0000000000000000000000000000000000000000",decimals:18,coingeckoId:"ethereum",binanceSymbol:"ETHUSDT"},{symbol:"LSK",name:"Lisk",icon:"https://arthuremma2.github.io/img-hosting/liskt.png",address:"0x8a21CF9Ba08Ae709D64Cb25AfAA951183EC9FF6D",decimals:18,coingeckoId:"LSK",binanceSymbol:"LSK"}]};var o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{};function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function c(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var l,d={exports:{}},h="object"==typeof Reflect?Reflect:null,u=h&&"function"==typeof h.apply?h.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};l=h&&"function"==typeof h.ownKeys?h.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!=e};function f(){f.init.call(this)}d.exports=f,d.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}k(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&k(e,"error",t,n)}(e,i,{once:!0})})},f.EventEmitter=f,f.prototype._events=void 0,f.prototype._eventsCount=0,f.prototype._maxListeners=void 0;var g=10;function m(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function y(e){return void 0===e._maxListeners?f.defaultMaxListeners:e._maxListeners}function w(e,t,n,r){var i,s,o,a;if(m(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]),void 0===o)o=s[t]=n,++e._eventsCount;else if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),(i=y(e))>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function b(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=b.bind(r);return i.listener=n,r.wrapFn=i,i}function E(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):A(i,i.length)}function x(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function A(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function k(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}Object.defineProperty(f,"defaultMaxListeners",{enumerable:!0,get:function(){return g},set:function(e){if("number"!=typeof e||e<0||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");g=e}}),f.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},f.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},f.prototype.getMaxListeners=function(){return y(this)},f.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)u(a,this,t);else{var c=a.length,l=A(a,c);for(n=0;n<c;++n)u(l[n],this,t)}return!0},f.prototype.addListener=function(e,t){return w(this,e,t,!1)},f.prototype.on=f.prototype.addListener,f.prototype.prependListener=function(e,t){return w(this,e,t,!0)},f.prototype.once=function(e,t){return m(t),this.on(e,v(this,e,t)),this},f.prototype.prependOnceListener=function(e,t){return m(t),this.prependListener(e,v(this,e,t)),this},f.prototype.removeListener=function(e,t){var n,r,i,s,o;if(m(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,o||t)}return this},f.prototype.off=f.prototype.removeListener,f.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,s=Object.keys(n);for(r=0;r<s.length;++r)"removeListener"!==(i=s[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},f.prototype.listeners=function(e){return E(this,e,!0)},f.prototype.rawListeners=function(e){return E(this,e,!1)},f.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):x.call(e,t)},f.prototype.listenerCount=x,f.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]};var I=d.exports,C=a(I),S=window&&window.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))},P=function(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"},N=function(e){this.version=e,this.type="node",this.name="node",this.os=process.platform},_=function(e,t,n,r){this.name=e,this.version=t,this.os=n,this.bot=r,this.type="bot-device"},T=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},O=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},$=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,R=[["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",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],B=[["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 M(e){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new O:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&R.reduce(function(t,n){var r=n[0],i=n[1];if(t)return t;var s=i.exec(e);return!!s&&[r,s]},!1)}(e);if(!t)return null;var n=t[0],r=t[1];if("searchbot"===n)return new T;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<3&&(i=S(S([],i,!0),function(e){for(var t=[],n=0;n<e;n++)t.push("0");return t}(3-i.length),!0)):i=[];var s=i.join("."),o=function(e){for(var t=0,n=B.length;t<n;t++){var r=B[t],i=r[0];if(r[1].exec(e))return i}return null}(e),a=$.exec(e);if(a&&a[1])return new _(n,s,o,a[1]);return new P(n,s,o)}(navigator.userAgent):"undefined"!=typeof process&&process.version?new N(process.version.slice(1)):null}var U={},L=function(e,t){return L=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},L(e,t)};
|
|
2
2
|
/*! *****************************************************************************
|
|
3
3
|
Copyright (c) Microsoft Corporation.
|
|
4
4
|
|
|
@@ -37,7 +37,7 @@ const Cc=BigInt(0),Sc=BigInt(1),Pc=BigInt(2);function Nc(e){const t=(Da(n=e,{adj
|
|
|
37
37
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function il(e,t){const n=t=>rl({...e,hash:t});return{...n(t),create:n}}
|
|
38
38
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const sl={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},ol={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},al={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},cl=lc(sl.p),ll=lc(ol.p),dl=lc(al.p),hl=il({...sl,Fp:cl,lowS:!1},en);il({...ol,Fp:ll,lowS:!1},nn),il({...al,Fp:dl,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},tn);
|
|
39
39
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
40
|
-
const ul=hl;function pl(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return(e=>{const t=e.replace(/([\[:])?(\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,'$1"$2n"$3');return JSON.parse(t,(e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t)})(e)}catch(t){return e}}function fl(e){return"string"==typeof e?e:(t=e,JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString()+"n":t)||"");var t}function gl(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ml(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const yl="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,wl=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bl(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),gl(e),e}let vl=class{clone(){return this._cloneInto()}};function El(e=32){if(yl&&"function"==typeof yl.getRandomValues)return yl.getRandomValues(new Uint8Array(e));if(yl&&"function"==typeof yl.randomBytes)return yl.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}let xl=class extends vl{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=wl(this.buffer)}update(e){ml(this);const{view:t,buffer:n,blockLen:r}=this,i=(e=bl(e)).length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=wl(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ml(this),function(e,t){gl(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;(function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)})(n,r-8,BigInt(8*this.length),i),this.process(n,0);const o=wl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return e.length=r,e.pos=o,e.finished=i,e.destroyed=s,r%t&&e.buffer.set(n),e}};const Al=BigInt(2**32-1),kl=BigInt(32);function Il(e,t=!1){return t?{h:Number(e&Al),l:Number(e>>kl&Al)}:{h:0|Number(e>>kl&Al),l:0|Number(e&Al)}}const Cl={fromBig:Il,split:function(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=Il(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]},toBig:(e,t)=>BigInt(e>>>0)<<kl|BigInt(t>>>0),shrSH:(e,t,n)=>e>>>n,shrSL:(e,t,n)=>e<<32-n|t>>>n,rotrSH:(e,t,n)=>e>>>n|t<<32-n,rotrSL:(e,t,n)=>e<<32-n|t>>>n,rotrBH:(e,t,n)=>e<<64-n|t>>>n-32,rotrBL:(e,t,n)=>e>>>n-32|t<<64-n,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,n)=>e<<n|t>>>32-n,rotlSL:(e,t,n)=>t<<n|e>>>32-n,rotlBH:(e,t,n)=>t<<n-32|e>>>64-n,rotlBL:(e,t,n)=>e<<n-32|t>>>64-n,add:function(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/2**32|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,add5H:(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,add5L:(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0)},[Sl,Pl]=Cl.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(e=>BigInt(e))),Nl=new Uint32Array(80),_l=new Uint32Array(80);let Tl=class extends xl{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:n,Bl:r,Ch:i,Cl:s,Dh:o,Dl:a,Eh:c,El:l,Fh:d,Fl:h,Gh:u,Gl:p,Hh:f,Hl:g}=this;return[e,t,n,r,i,s,o,a,c,l,d,h,u,p,f,g]}set(e,t,n,r,i,s,o,a,c,l,d,h,u,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|d,this.Fl=0|h,this.Gh=0|u,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)Nl[n]=e.getUint32(t),_l[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Nl[e-15],n=0|_l[e-15],r=Cl.rotrSH(t,n,1)^Cl.rotrSH(t,n,8)^Cl.shrSH(t,n,7),i=Cl.rotrSL(t,n,1)^Cl.rotrSL(t,n,8)^Cl.shrSL(t,n,7),s=0|Nl[e-2],o=0|_l[e-2],a=Cl.rotrSH(s,o,19)^Cl.rotrBH(s,o,61)^Cl.shrSH(s,o,6),c=Cl.rotrSL(s,o,19)^Cl.rotrBL(s,o,61)^Cl.shrSL(s,o,6),l=Cl.add4L(i,c,_l[e-7],_l[e-16]),d=Cl.add4H(l,r,a,Nl[e-7],Nl[e-16]);Nl[e]=0|d,_l[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:o,Cl:a,Dh:c,Dl:l,Eh:d,El:h,Fh:u,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Cl.rotrSH(d,h,14)^Cl.rotrSH(d,h,18)^Cl.rotrBH(d,h,41),w=Cl.rotrSL(d,h,14)^Cl.rotrSL(d,h,18)^Cl.rotrBL(d,h,41),b=d&u^~d&f,v=h&p^~h&g,E=Cl.add5L(y,w,v,Pl[e],_l[e]),x=Cl.add5H(E,m,t,b,Sl[e],Nl[e]),A=0|E,k=Cl.rotrSH(n,r,28)^Cl.rotrBH(n,r,34)^Cl.rotrBH(n,r,39),I=Cl.rotrSL(n,r,28)^Cl.rotrBL(n,r,34)^Cl.rotrBL(n,r,39),C=n&i^n&o^i&o,S=r&s^r&a^s&a;m=0|f,y=0|g,f=0|u,g=0|p,u=0|d,p=0|h,({h:d,l:h}=Cl.add(0|c,0|l,0|x,0|A)),c=0|o,l=0|a,o=0|i,a=0|s,i=0|n,s=0|r;const P=Cl.add3L(A,I,S);n=Cl.add3H(P,x,k,C),r=0|P}({h:n,l:r}=Cl.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=Cl.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=Cl.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=Cl.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:d,l:h}=Cl.add(0|this.Eh,0|this.El,0|d,0|h)),({h:u,l:p}=Cl.add(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=Cl.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Cl.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,i,s,o,a,c,l,d,h,u,p,f,g,m,y)}roundClean(){Nl.fill(0),_l.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 Ol=function(e){const t=t=>e().update(bl(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new Tl),$l=BigInt(0),Rl=BigInt(1),Bl=BigInt(2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ml(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Ul(e){if(!Ml(e))throw new Error("Uint8Array expected")}function Ll(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const Dl=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function jl(e){Ul(e);let t="";for(let n=0;n<e.length;n++)t+=Dl[e[n]];return t}function zl(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?$l:BigInt("0x"+e)}const Hl=48,Vl=57,Fl=65,ql=70,Wl=97,Zl=102;function Kl(e){return e>=Hl&&e<=Vl?e-Hl:e>=Fl&&e<=ql?e-(Fl-10):e>=Wl&&e<=Zl?e-(Wl-10):void 0}function Gl(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=Kl(e.charCodeAt(i)),s=Kl(e.charCodeAt(i+1));if(void 0===n||void 0===s){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+s}return r}function Yl(e){return Ul(e),zl(jl(Uint8Array.from(e).reverse()))}function Jl(e,t){return Gl(e.toString(16).padStart(2*t,"0"))}function Ql(e,t){return Jl(e,t).reverse()}function Xl(e,t,n){let r;if("string"==typeof t)try{r=Gl(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Ml(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function ed(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Ul(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}const td=e=>"bigint"==typeof e&&$l<=e;function nd(e,t,n,r){if(!function(e,t,n){return td(e)&&td(t)&&td(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const rd=e=>(Bl<<BigInt(e-1))-Rl,id={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Ml(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function sd(e,t,n={}){const r=(t,n,r)=>{const i=id[n];if("function"!=typeof i)throw new Error("invalid validator function");const s=e[t];if(!(r&&void 0===s||i(s,e)))throw new Error("param "+String(t)+" is invalid. Expected "+n+", got "+s)};for(const[e,n]of Object.entries(t))r(e,n,!1);for(const[e,t]of Object.entries(n))r(e,t,!0);return e}function od(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}const ad=BigInt(0),cd=BigInt(1),ld=BigInt(2),dd=BigInt(3),hd=BigInt(4),ud=BigInt(5),pd=BigInt(8);function fd(e,t){const n=e%t;return n>=ad?n:t+n}function gd(e,t,n){if(t<ad)throw new Error("invalid exponent, negatives unsupported");if(n<=ad)throw new Error("invalid modulus");if(n===cd)return ad;let r=cd;for(;t>ad;)t&cd&&(r=r*e%n),e=e*e%n,t>>=cd;return r}function md(e,t,n){let r=e;for(;t-- >ad;)r*=r,r%=n;return r}function yd(e,t){if(e===ad)throw new Error("invert: expected non-zero number");if(t<=ad)throw new Error("invert: expected positive modulus, got "+t);let n=fd(e,t),r=t,i=ad,s=cd;for(;n!==ad;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==cd)throw new Error("invert: does not exist");return fd(i,t)}function wd(e){if(e%hd===dd){const t=(e+cd)/hd;return function(e,n){const r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}}if(e%pd===ud){const t=(e-ud)/pd;return function(e,n){const r=e.mul(n,ld),i=e.pow(r,t),s=e.mul(n,i),o=e.mul(e.mul(s,ld),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),n))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-cd)/ld;let n,r,i;for(n=e-cd,r=0;n%ld===ad;n/=ld,r++);for(i=ld;i<e&&gd(i,t,e)!==e-cd;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===r){const t=(e+cd)/hd;return function(e,n){const r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}}const s=(n+cd)/ld;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=r,c=e.pow(e.mul(e.ONE,i),n),l=e.pow(o,s),d=e.pow(o,n);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let n=e.sqr(d);t<a&&!e.eql(n,e.ONE);t++)n=e.sqr(n);const n=e.pow(c,cd<<BigInt(a-t-1));c=e.sqr(n),l=e.mul(l,n),d=e.mul(d,c),a=t}return l}}(e)}const bd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vd(e,t){const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Ed(e,t,n=!1,r={}){if(e<=ad)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:i,nByteLength:s}=vd(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:n,BITS:i,BYTES:s,MASK:rd(i),ZERO:ad,ONE:cd,create:t=>fd(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return ad<=t&&t<e},is0:e=>e===ad,isOdd:e=>(e&cd)===cd,neg:t=>fd(-t,e),eql:(e,t)=>e===t,sqr:t=>fd(t*t,e),add:(t,n)=>fd(t+n,e),sub:(t,n)=>fd(t-n,e),mul:(t,n)=>fd(t*n,e),pow:(e,t)=>function(e,t,n){if(n<ad)throw new Error("invalid exponent, negatives unsupported");if(n===ad)return e.ONE;if(n===cd)return t;let r=e.ONE,i=t;for(;n>ad;)n&cd&&(r=e.mul(r,i)),i=e.sqr(i),n>>=cd;return r}(a,e,t),div:(t,n)=>fd(t*yd(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>yd(t,e),sqrt:r.sqrt||(t=>(o||(o=wd(e)),o(a,t))),invertBatch:e=>function(e,t){const n=new Array(t.length),r=t.reduce((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r)),e.ONE),i=e.inv(r);return t.reduceRight((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r)),i),n}(a,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?Ql(e,s):Jl(e,s),fromBytes:e=>{if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);return n?Yl(e):function(e){return zl(jl(e))}(e)}});return Object.freeze(a)}const xd=BigInt(0),Ad=BigInt(1);function kd(e,t){const n=t.negate();return e?n:t}function Id(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Cd(e,t){Id(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Sd=new WeakMap,Pd=new WeakMap;function Nd(e){return Pd.get(e)||1}function _d(e,t,n,r){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,s=function(e){let t;for(t=0;e>$l;e>>=Rl,t+=1);return t}(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i);let l=i;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(i);for(let t=0;t<r.length;t++){const i=r[t],s=Number(i>>BigInt(e)&BigInt(a));c[s]=c[s].add(n[t])}let t=i;for(let e=c.length-1,n=i;e>0;e--)n=n.add(c[e]),t=t.add(n);if(l=l.add(t),0!==e)for(let e=0;e<o;e++)l=l.double()}return l}function Td(e){return function(e){const t=bd.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});sd(e,t)}(e.Fp),sd(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vd(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const Od=BigInt(0),$d=BigInt(1),Rd=BigInt(2),Bd=BigInt(8),Md={zip215:!0};function Ud(e){const t=function(e){const t=Td(e);return sd(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=t,l=Rd<<BigInt(8*a)-$d,d=n.create,h=Ed(t.n,t.nBitLength),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(e*n.inv(t))}}catch{return{isValid:!1,value:Od}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,n)=>{if(Ll("phflag",n),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){nd("coordinate "+e,t,Od,l)}function m(e){if(!(e instanceof b))throw new Error("ExtendedPoint expected")}const y=od((e,t)=>{const{ex:r,ey:i,ez:s}=e,o=e.is0();null==t&&(t=o?Bd:n.inv(s));const a=d(r*t),c=d(i*t),l=d(s*t);if(o)return{x:Od,y:$d};if(l!==$d)throw new Error("invZ was invalid");return{x:a,y:c}}),w=od(e=>{const{a:n,d:r}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:i,ey:s,ez:o,et:a}=e,c=d(i*i),l=d(s*s),h=d(o*o),u=d(h*h),p=d(c*n);if(d(h*d(p+l))!==d(u+d(r*d(c*l))))throw new Error("bad point: equation left != right (1)");if(d(i*s)!==d(o*a))throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(e,t,n,r){this.ex=e,this.ey=t,this.ez=n,this.et=r,g("x",e),g("y",t),g("z",n),g("t",r),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof b)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return g("x",t),g("y",n),new b(t,n,$d,d(t*n))}static normalizeZ(e){const t=n.invertBatch(e.map(e=>e.ez));return e.map((e,n)=>e.toAffine(t[n])).map(b.fromAffine)}static msm(e,t){return _d(b,h,e,t)}_setWindowSize(e){x.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){m(e);const{ex:t,ey:n,ez:r}=this,{ex:i,ey:s,ez:o}=e,a=d(t*o),c=d(i*r),l=d(n*o),h=d(s*r);return a===c&&l===h}is0(){return this.equals(b.ZERO)}negate(){return new b(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){const{a:e}=t,{ex:n,ey:r,ez:i}=this,s=d(n*n),o=d(r*r),a=d(Rd*d(i*i)),c=d(e*s),l=n+r,h=d(d(l*l)-s-o),u=c+o,p=u-a,f=c-o,g=d(h*p),m=d(u*f),y=d(h*f),w=d(p*u);return new b(g,m,w,y)}add(e){m(e);const{a:n,d:r}=t,{ex:i,ey:s,ez:o,et:a}=this,{ex:c,ey:l,ez:h,et:u}=e;if(n===BigInt(-1)){const e=d((s-i)*(l+c)),t=d((s+i)*(l-c)),n=d(t-e);if(n===Od)return this.double();const r=d(o*Rd*u),p=d(a*Rd*h),f=p+r,g=t+e,m=p-r,y=d(f*n),w=d(g*m),v=d(f*m),E=d(n*g);return new b(y,w,E,v)}const p=d(i*c),f=d(s*l),g=d(a*r*u),y=d(o*h),w=d((i+s)*(c+l)-p-f),v=y-g,E=y+g,x=d(f-n*p),A=d(w*v),k=d(E*x),I=d(w*x),C=d(v*E);return new b(A,k,C,I)}subtract(e){return this.add(e.negate())}wNAF(e){return x.wNAFCached(this,e,b.normalizeZ)}multiply(e){const t=e;nd("scalar",t,$d,r);const{p:n,f:i}=this.wNAF(t);return b.normalizeZ([n,i])[0]}multiplyUnsafe(e,t=b.ZERO){const n=e;return nd("scalar",n,Od,r),n===Od?E:this.is0()||n===$d?this:x.wNAFCachedUnsafe(this,n,b.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return x.unsafeLadder(this,r).is0()}toAffine(e){return y(this,e)}clearCofactor(){const{h:e}=t;return e===$d?this:this.multiplyUnsafe(e)}static fromHex(e,r=!1){const{d:i,a:s}=t,o=n.BYTES;e=Xl("pointHex",e,o),Ll("zip215",r);const a=e.slice(),c=e[o-1];a[o-1]=-129&c;const h=Yl(a),p=r?l:n.ORDER;nd("pointHex.y",h,Od,p);const f=d(h*h),g=d(f-$d),m=d(i*f-s);let{isValid:y,value:w}=u(g,m);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const v=(w&$d)===$d,E=!!(128&c);if(!r&&w===Od&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(w=d(-w)),b.fromAffine({x:w,y:h})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Ql(t,n.BYTES);return r[r.length-1]|=e&$d?128:0,r}toHex(){return jl(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,$d,d(t.Gx*t.Gy)),b.ZERO=new b(Od,$d,$d,Od);const{BASE:v,ZERO:E}=b,x=function(e,t){return{constTimeNegate:kd,hasPrecomputes:e=>1!==Nd(e),unsafeLadder(t,n,r=e.ZERO){let i=t;for(;n>xd;)n&Ad&&(r=r.add(i)),i=i.double(),n>>=Ad;return r},precomputeWindow(e,n){const{windows:r,windowSize:i}=Cd(n,t),s=[];let o=e,a=o;for(let e=0;e<r;e++){a=o,s.push(a);for(let e=1;e<i;e++)a=a.add(o),s.push(a);o=a.double()}return s},wNAF(n,r,i){const{windows:s,windowSize:o}=Cd(n,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**n-1),d=2**n,h=BigInt(n);for(let e=0;e<s;e++){const t=e*o;let n=Number(i&l);i>>=h,n>o&&(n-=d,i+=Ad);const s=t,u=t+Math.abs(n)-1,p=e%2!=0,f=n<0;0===n?c=c.add(kd(p,r[s])):a=a.add(kd(f,r[u]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=e.ZERO){const{windows:o,windowSize:a}=Cd(n,t),c=BigInt(2**n-1),l=2**n,d=BigInt(n);for(let e=0;e<o;e++){const t=e*a;if(i===xd)break;let n=Number(i&c);if(i>>=d,n>a&&(n-=l,i+=Ad),0===n)continue;let o=r[t+Math.abs(n)-1];n<0&&(o=o.negate()),s=s.add(o)}return s},getPrecomputes(e,t,n){let r=Sd.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&Sd.set(t,n(r))),r},wNAFCached(e,t,n){const r=Nd(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)},wNAFCachedUnsafe(e,t,n,r){const i=Nd(e);return 1===i?this.unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)},setWindowSize(e,n){Id(n,t),Pd.set(e,n),Sd.delete(e)}}}(b,8*a);function A(e){return fd(e,r)}function k(e){return A(Yl(e))}function I(e){const t=n.BYTES;e=Xl("private key",e,t);const r=Xl("hashed private key",s(e),2*t),i=p(r.slice(0,t)),o=r.slice(t,2*t),a=k(i),c=v.multiply(a),l=c.toRawBytes();return{head:i,prefix:o,scalar:a,point:c,pointBytes:l}}function C(e=new Uint8Array,...t){const n=ed(...t);return k(s(f(n,Xl("context",e),!!i)))}const S=Md;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,s={}){e=Xl("message",e),i&&(e=i(e));const{prefix:o,scalar:a,pointBytes:c}=I(t),l=C(s.context,o,e),d=v.multiply(l).toRawBytes(),h=A(l+C(s.context,d,c,e)*a);return nd("signature.s",h,Od,r),Xl("result",ed(d,Ql(h,n.BYTES)),2*n.BYTES)},verify:function(e,t,r,s=S){const{context:o,zip215:a}=s,c=n.BYTES;e=Xl("signature",e,2*c),t=Xl("message",t),r=Xl("publicKey",r,c),void 0!==a&&Ll("zip215",a),i&&(t=i(t));const l=Yl(e.slice(c,2*c));let d,h,u;try{d=b.fromHex(r,a),h=b.fromHex(e.slice(0,c),a),u=v.multiplyUnsafe(l)}catch{return!1}if(!a&&d.isSmallOrder())return!1;const p=C(o,h.toRawBytes(),d.toRawBytes(),t);return h.add(d.multiplyUnsafe(p)).subtract(u).clearCofactor().equals(b.ZERO)},ExtendedPoint:b,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(n.BYTES),precompute:(e=8,t=b.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}BigInt(0),BigInt(1);const Ld=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Dd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const jd=BigInt(1),zd=BigInt(2);BigInt(3);const Hd=BigInt(5),Vd=BigInt(8);function Fd(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function qd(e,t){const n=Ld,r=fd(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Ld,o=e*e%s*e%s,a=md(o,zd,s)*o%s,c=md(a,jd,s)*e%s,l=md(c,Hd,s)*c%s,d=md(l,t,s)*l%s,h=md(d,n,s)*d%s,u=md(h,r,s)*h%s,p=md(u,i,s)*u%s,f=md(p,i,s)*u%s,g=md(f,t,s)*l%s;return{pow_p_5_8:md(g,zd,s)*e%s,b2:o}}(e*fd(r*r*t,n)).pow_p_5_8;let s=fd(e*r*i,n);const o=fd(t*s*s,n),a=s,c=fd(s*Dd,n),l=o===e,d=o===fd(-e,n),h=o===fd(-e*Dd,n);return l&&(s=a),(d||h)&&(s=c),((e,t)=>(fd(e,t)&cd)===cd)(s,n)&&(s=fd(-s,n)),{isValid:l||d,value:s}}const Wd=Ed(Ld,void 0,!0),Zd=Ud({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wd,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Vd,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ol,randomBytes:El,adjustScalarBytes:Fd,uvRatio:qd}),Kd=".",Gd="base64url",Yd="utf8",Jd="utf8",Qd="did",Xd="key",eh="base58btc";function th(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function nh(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?th(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function rh(e,t){t||(t=e.reduce((e,t)=>e+t.length,0));const n=nh(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return th(n)}var ih=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(255!==n[o])throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var r=0,i=0;e[t]===c;)r++,t++;for(var s=(e.length-t)*l+1>>>0,o=new Uint8Array(s);e[t];){var d=n[e.charCodeAt(t)];if(255===d)return;for(var h=0,u=s-1;(0!==d||h<i)&&-1!==u;u--,h++)d+=a*o[u]>>>0,o[u]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=h,t++}if(" "!==e[t]){for(var p=s-i;p!==s&&0===o[p];)p++;for(var f=new Uint8Array(r+(s-p)),g=r;p!==s;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var n=0,r=0,i=0,s=t.length;i!==s&&0===t[i];)i++,n++;for(var o=(s-i)*d+1>>>0,l=new Uint8Array(o);i!==s;){for(var h=t[i],u=0,p=o-1;(0!==h||u<r)&&-1!==p;p--,u++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");r=u,i++}for(var f=o-r;f!==o&&0===l[f];)f++;for(var g=c.repeat(n);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var n=h(e);if(n)return n;throw new Error(`Non-${t} character`)}}},sh=ih;const oh=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};let ah=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ch=class{constructor(e,t,n){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return dh(this,e)}},lh=class{constructor(e){this.decoders=e}or(e){return dh(this,e)}decode(e){const t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const dh=(e,t)=>new lh({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});let hh=class{constructor(e,t,n,r){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=r,this.encoder=new ah(e,t,n),this.decoder=new ch(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const uh=({name:e,prefix:t,encode:n,decode:r})=>new hh(e,t,n,r),ph=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=sh(n,t);return uh({prefix:e,name:t,encode:r,decode:e=>oh(i(e))})},fh=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>uh({prefix:t,name:e,encode:e=>((e,t,n)=>{const r="="===t[t.length-1],i=(1<<n)-1;let s="",o=0,a=0;for(let r=0;r<e.length;++r)for(a=a<<8|e[r],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s})(e,r,n),decode:t=>((e,t,n,r)=>{const i={};for(let e=0;e<t.length;++e)i[t[e]]=e;let s=e.length;for(;"="===e[s-1];)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let t=0;t<s;++t){const s=i[e[t]];if(void 0===s)throw new SyntaxError(`Non-${r} character`);c=c<<n|s,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,r,n,e)}),gh=uh({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var mh=Object.freeze({__proto__:null,identity:gh});const yh=fh({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wh=Object.freeze({__proto__:null,base2:yh});const bh=fh({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vh=Object.freeze({__proto__:null,base8:bh});const Eh=ph({prefix:"9",name:"base10",alphabet:"0123456789"});var xh=Object.freeze({__proto__:null,base10:Eh});const Ah=fh({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kh=fh({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ih=Object.freeze({__proto__:null,base16:Ah,base16upper:kh});const Ch=fh({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sh=fh({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ph=fh({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nh=fh({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_h=fh({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Th=fh({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oh=fh({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$h=fh({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rh=fh({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bh=Object.freeze({__proto__:null,base32:Ch,base32upper:Sh,base32pad:Ph,base32padupper:Nh,base32hex:_h,base32hexupper:Th,base32hexpad:Oh,base32hexpadupper:$h,base32z:Rh});const Mh=ph({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Uh=ph({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Lh=Object.freeze({__proto__:null,base36:Mh,base36upper:Uh});const Dh=ph({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jh=ph({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var zh=Object.freeze({__proto__:null,base58btc:Dh,base58flickr:jh});const Hh=fh({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Vh=fh({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fh=fh({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qh=fh({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wh=Object.freeze({__proto__:null,base64:Hh,base64pad:Vh,base64url:Fh,base64urlpad:qh});const Zh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Kh=Zh.reduce((e,t,n)=>(e[n]=t,e),[]),Gh=Zh.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);const Yh=uh({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+=Kh[t],"")},decode:function(e){const t=[];for(const n of e){const e=Gh[n.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${n}`);t.push(e)}return new Uint8Array(t)}});var Jh=Object.freeze({__proto__:null,base256emoji:Yh}),Qh=function e(t,n,r){n=n||[];for(var i=r=r||0;t>=tu;)n[r++]=255&t|Xh,t/=128;for(;t&eu;)n[r++]=255&t|Xh,t>>>=7;return n[r]=0|t,e.bytes=r-i+1,n},Xh=128,eu=-128,tu=Math.pow(2,31);var nu=function e(t,n){var r,i=0,s=(n=n||0,0),o=n,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");r=t[o++],i+=s<28?(r&iu)<<s:(r&iu)*Math.pow(2,s),s+=7}while(r>=ru);return e.bytes=o-n,i},ru=128,iu=127;var su=Math.pow(2,7),ou=Math.pow(2,14),au=Math.pow(2,21),cu=Math.pow(2,28),lu=Math.pow(2,35),du=Math.pow(2,42),hu=Math.pow(2,49),uu=Math.pow(2,56),pu=Math.pow(2,63),fu={encode:Qh,decode:nu,encodingLength:function(e){return e<su?1:e<ou?2:e<au?3:e<cu?4:e<lu?5:e<du?6:e<hu?7:e<uu?8:e<pu?9:10}},gu=fu;const mu=(e,t,n=0)=>(gu.encode(e,t,n),t),yu=e=>gu.encodingLength(e),wu=(e,t)=>{const n=t.byteLength,r=yu(e),i=r+yu(n),s=new Uint8Array(i+n);return mu(e,s,0),mu(n,s,r),s.set(t,i),new bu(e,n,t,s)};let bu=class{constructor(e,t,n,r){this.code=e,this.size=t,this.digest=n,this.bytes=r}};const vu=({name:e,code:t,encode:n})=>new Eu(e,t,n);let Eu=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?wu(this.code,t):t.then(e=>wu(this.code,e))}throw Error("Unknown type, must be binary type")}};const xu=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Au=vu({name:"sha2-256",code:18,encode:xu("SHA-256")}),ku=vu({name:"sha2-512",code:19,encode:xu("SHA-512")});Object.freeze({__proto__:null,sha256:Au,sha512:ku});const Iu=oh,Cu={code:0,name:"identity",encode:Iu,digest:e=>wu(0,Iu(e))};Object.freeze({__proto__:null,identity:Cu});new TextEncoder,new TextDecoder;const Su={...mh,...wh,...vh,...xh,...Ih,...Bh,...Lh,...zh,...Wh,...Jh};function Pu(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const Nu=Pu("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),_u=Pu("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{const t=nh((e=e.substring(1)).length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Tu={utf8:Nu,"utf-8":Nu,hex:Su.base16,latin1:_u,ascii:_u,binary:_u,...Su};function Ou(e,t="utf8"){const n=Tu[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?n.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}function $u(e,t="utf8"){const n=Tu[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?n.decoder.decode(`${n.prefix}${e}`):th(globalThis.Buffer.from(e,"utf-8"))}function Ru(e){return pl(Ou($u(e,Gd),Yd))}function Bu(e){return Ou($u(fl(e),Yd),Gd)}function Mu(e){const t="z"+Ou(rh([$u("K36",eh),e]),eh);return[Qd,Xd,t].join(":")}function Uu(e){return Ou(e,Gd)}function Lu(e){const t=e.split(Kd),n=Ru(t[0]),r=Ru(t[1]),i=function(e){return $u(e,Gd)}(t[2]);return{header:n,payload:r,signature:i,data:$u(t.slice(0,2).join(Kd),Jd)}}function Du(e=El(32)){const t=Zd.getPublicKey(e);return{secretKey:rh([e,t]),publicKey:t}}async function ju(e,t,n,r,i=U.fromMiliseconds(Date.now())){const s={alg:"EdDSA",typ:"JWT"},o={iss:Mu(r.publicKey),sub:e,aud:t,iat:i,exp:i+n},a=function(e){return $u([Bu(e.header),Bu(e.payload)].join(Kd),Jd)}({header:s,payload:o});return function(e){return[Bu(e.header),Bu(e.payload),Uu(e.signature)].join(Kd)}({header:s,payload:o,signature:Zd.sign(a,r.secretKey.slice(0,32))})}const zu={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"}};function Hu(e){return(4294967296+e).toString(16).substring(1)}var Vu={normalizeInput:function(e){let t;if(e instanceof Uint8Array)t=e;else{if("string"!=typeof e)throw new Error("Input must be an string, Buffer or Uint8Array");t=(new TextEncoder).encode(e)}return t},toHex:function(e){return Array.prototype.map.call(e,function(e){return(e<16?"0":"")+e.toString(16)}).join("")},debugPrint:function(e,t,n){let r="\n"+e+" = ";for(let i=0;i<t.length;i+=2){if(32===n)r+=Hu(t[i]).toUpperCase(),r+=" ",r+=Hu(t[i+1]).toUpperCase();else{if(64!==n)throw new Error("Invalid size "+n);r+=Hu(t[i+1]).toUpperCase(),r+=Hu(t[i]).toUpperCase()}i%6==4?r+="\n"+new Array(e.length+4).join(" "):i<t.length-2&&(r+=" ")}console.log(r)},testSpeed:function(e,t,n){let r=(new Date).getTime();const i=new Uint8Array(t);for(let e=0;e<t;e++)i[e]=e%256;const s=(new Date).getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let s=0;s<n;s++){const n=e(i),s=(new Date).getTime(),o=s-r;r=s,console.log("Hashed in "+o+"ms: "+n.substring(0,20)+"..."),console.log(Math.round(t/(1<<20)/(o/1e3)*100)/100+" MB PER SECOND")}}};const Fu=Vu;function qu(e,t,n){const r=e[t]+e[n];let i=e[t+1]+e[n+1];r>=4294967296&&i++,e[t]=r,e[t+1]=i}function Wu(e,t,n,r){let i=e[t]+n;n<0&&(i+=4294967296);let s=e[t+1]+r;i>=4294967296&&s++,e[t]=i,e[t+1]=s}function Zu(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function Ku(e,t,n,r,i,s){const o=Qu[i],a=Qu[i+1],c=Qu[s],l=Qu[s+1];qu(Ju,e,t),Wu(Ju,e,o,a);let d=Ju[r]^Ju[e],h=Ju[r+1]^Ju[e+1];Ju[r]=h,Ju[r+1]=d,qu(Ju,n,r),d=Ju[t]^Ju[n],h=Ju[t+1]^Ju[n+1],Ju[t]=d>>>24^h<<8,Ju[t+1]=h>>>24^d<<8,qu(Ju,e,t),Wu(Ju,e,c,l),d=Ju[r]^Ju[e],h=Ju[r+1]^Ju[e+1],Ju[r]=d>>>16^h<<16,Ju[r+1]=h>>>16^d<<16,qu(Ju,n,r),d=Ju[t]^Ju[n],h=Ju[t+1]^Ju[n+1],Ju[t]=h>>>31^d<<1,Ju[t+1]=d>>>31^h<<1}const Gu=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Yu=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map(function(e){return 2*e})),Ju=new Uint32Array(32),Qu=new Uint32Array(32);function Xu(e,t){let n=0;for(n=0;n<16;n++)Ju[n]=e.h[n],Ju[n+16]=Gu[n];for(Ju[24]=Ju[24]^e.t,Ju[25]=Ju[25]^e.t/4294967296,t&&(Ju[28]=~Ju[28],Ju[29]=~Ju[29]),n=0;n<32;n++)Qu[n]=Zu(e.b,4*n);for(n=0;n<12;n++)Ku(0,8,16,24,Yu[16*n+0],Yu[16*n+1]),Ku(2,10,18,26,Yu[16*n+2],Yu[16*n+3]),Ku(4,12,20,28,Yu[16*n+4],Yu[16*n+5]),Ku(6,14,22,30,Yu[16*n+6],Yu[16*n+7]),Ku(0,10,20,30,Yu[16*n+8],Yu[16*n+9]),Ku(2,12,22,24,Yu[16*n+10],Yu[16*n+11]),Ku(4,14,16,26,Yu[16*n+12],Yu[16*n+13]),Ku(6,8,18,28,Yu[16*n+14],Yu[16*n+15]);for(n=0;n<16;n++)e.h[n]=e.h[n]^Ju[n]^Ju[n+16]}const ep=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function tp(e,t,n,r){if(0===e||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&16!==n.length)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&16!==r.length)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};ep.fill(0),ep[0]=e,t&&(ep[1]=t.length),ep[2]=1,ep[3]=1,n&&ep.set(n,32),r&&ep.set(r,48);for(let e=0;e<16;e++)i.h[e]=Gu[e]^Zu(ep,4*e);return t&&(np(i,t),i.c=128),i}function np(e,t){for(let n=0;n<t.length;n++)128===e.c&&(e.t+=e.c,Xu(e,!1),e.c=0),e.b[e.c++]=t[n]}function rp(e){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;Xu(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(3&n);return t}function ip(e,t,n,r,i){n=n||64,e=Fu.normalizeInput(e),r&&(r=Fu.normalizeInput(r)),i&&(i=Fu.normalizeInput(i));const s=tp(n,t,r,i);return np(s,e),rp(s)}var sp={blake2b:ip,blake2bHex:function(e,t,n,r,i){const s=ip(e,t,n,r,i);return Fu.toHex(s)},blake2bInit:tp,blake2bUpdate:np,blake2bFinal:rp};const op=Vu;function ap(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function cp(e,t,n,r,i,s){up[e]=up[e]+up[t]+i,up[r]=lp(up[r]^up[e],16),up[n]=up[n]+up[r],up[t]=lp(up[t]^up[n],12),up[e]=up[e]+up[t]+s,up[r]=lp(up[r]^up[e],8),up[n]=up[n]+up[r],up[t]=lp(up[t]^up[n],7)}function lp(e,t){return e>>>t^e<<32-t}const dp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),hp=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),up=new Uint32Array(16),pp=new Uint32Array(16);function fp(e,t){let n=0;for(n=0;n<8;n++)up[n]=e.h[n],up[n+8]=dp[n];for(up[12]^=e.t,up[13]^=e.t/4294967296,t&&(up[14]=~up[14]),n=0;n<16;n++)pp[n]=ap(e.b,4*n);for(n=0;n<10;n++)cp(0,4,8,12,pp[hp[16*n+0]],pp[hp[16*n+1]]),cp(1,5,9,13,pp[hp[16*n+2]],pp[hp[16*n+3]]),cp(2,6,10,14,pp[hp[16*n+4]],pp[hp[16*n+5]]),cp(3,7,11,15,pp[hp[16*n+6]],pp[hp[16*n+7]]),cp(0,5,10,15,pp[hp[16*n+8]],pp[hp[16*n+9]]),cp(1,6,11,12,pp[hp[16*n+10]],pp[hp[16*n+11]]),cp(2,7,8,13,pp[hp[16*n+12]],pp[hp[16*n+13]]),cp(3,4,9,14,pp[hp[16*n+14]],pp[hp[16*n+15]]);for(n=0;n<8;n++)e.h[n]^=up[n]^up[n+8]}function gp(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=t?t.length:0;if(t&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(dp),b:new Uint8Array(64),c:0,t:0,outlen:e};return r.h[0]^=16842752^n<<8^e,n>0&&(mp(r,t),r.c=64),r}function mp(e,t){for(let n=0;n<t.length;n++)64===e.c&&(e.t+=e.c,fp(e,!1),e.c=0),e.b[e.c++]=t[n]}function yp(e){for(e.t+=e.c;e.c<64;)e.b[e.c++]=0;fp(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(3&n)&255;return t}function wp(e,t,n){n=n||32,e=op.normalizeInput(e);const r=gp(n,t);return mp(r,e),yp(r)}var bp={blake2s:wp,blake2sHex:function(e,t,n){const r=wp(e,t,n);return op.toHex(r)},blake2sInit:gp,blake2sUpdate:mp,blake2sFinal:yp};var vp={blake2b:sp.blake2b,blake2bHex:sp.blake2bHex,blake2bInit:sp.blake2bInit,blake2bUpdate:sp.blake2bUpdate,blake2bFinal:sp.blake2bFinal,blake2s:bp.blake2s,blake2sHex:bp.blake2sHex,blake2sInit:bp.blake2sInit,blake2sUpdate:bp.blake2sUpdate,blake2sFinal:bp.blake2sFinal},Ep={exports:{}};function xp(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var Ap=function(e,t,n){var r=n&&n.stringify||xp;if("object"==typeof e&&null!==e){var i=t.length+1;if(1===i)return e;var s=new Array(i);s[0]=r(e);for(var o=1;o<i;o++)s[o]=r(t[o]);return s.join(" ")}if("string"!=typeof e)return e;var a=t.length;if(0===a)return e;for(var c="",l=0,d=-1,h=e&&e.length||0,u=0;u<h;){if(37===e.charCodeAt(u)&&u+1<h){switch(d=d>-1?d:0,e.charCodeAt(u+1)){case 100:case 102:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Number(t[l]),d=u+2,u++;break;case 105:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Math.floor(Number(t[l])),d=u+2,u++;break;case 79:case 111:case 106:if(l>=a||void 0===t[l])break;d<u&&(c+=e.slice(d,u));var p=typeof t[l];if("string"===p){c+="'"+t[l]+"'",d=u+2,u++;break}if("function"===p){c+=t[l].name||"<anonymous>",d=u+2,u++;break}c+=r(t[l]),d=u+2,u++;break;case 115:if(l>=a)break;d<u&&(c+=e.slice(d,u)),c+=String(t[l]),d=u+2,u++;break;case 37:d<u&&(c+=e.slice(d,u)),c+="%",d=u+2,u++,l--}++l}++u}return-1===d?e:(d<h&&(c+=e.slice(d)),c)};const kp=Ap;Ep.exports=Op;const Ip=function(){function e(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}().console||{},Cp={mapHttpRequest:Lp,mapHttpResponse:Lp,wrapRequestSerializer:Dp,wrapResponseSerializer:Dp,wrapErrorSerializer:Dp,req:Lp,res:Lp,err:Mp,errWithCause:Mp};function Sp(e,t){return"silent"===e?1/0:t.levels.values[e]}const Pp=Symbol("pino.logFuncs"),Np=Symbol("pino.hierarchy"),_p={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Tp(e,t){const n={logger:t,parent:e[Np]};t[Np]=n}function Op(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const n=e.browser.write||Ip;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},i=function(e,t){return Array.isArray(e)?e.filter(function(e){return"!stdSerializers.err"!==e}):!0===e&&Object.keys(t)}(e.browser.serialize,r);let s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);"function"==typeof n&&a.forEach(function(e){n[e]=n}),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(n);l.log||(l.log=jp),function(e,t,n){const r={};t.forEach(e=>{r[e]=n[e]?n[e]:Ip[e]||Ip[_p[e]||"log"]||jp}),e[Pp]=r}(l,a,n),Tp({},l),Object.defineProperty(l,"levelVal",{get:function(){return Sp(this.level,this)}}),Object.defineProperty(l,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,$p(this,d,l,"error"),$p(this,d,l,"fatal"),$p(this,d,l,"warn"),$p(this,d,l,"info"),$p(this,d,l,"debug"),$p(this,d,l,"trace"),o.forEach(e=>{$p(this,d,l,e)})}});const d={transmit:t,serialize:i,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:Up(e),messageKey:e.messageKey||"msg",onChild:e.onChild||jp};function h(n,s,o){if(!s)throw new Error("missing bindings for child Pino");o=o||{},i&&s.serializers&&(o.serializers=s.serializers);const a=o.serializers;if(i&&a){var c=Object.assign({},r,a),l=!0===e.browser.serialize?Object.keys(c):i;delete s.serializers,Rp([s],l,c,this._stdErrSerialize)}function d(e){this._childLevel=1+(0|e._childLevel),this.bindings=s,c&&(this.serializers=c,this._serialize=l),t&&(this._logEvent=Bp([].concat(e._logEvent.bindings,s)))}d.prototype=this;const u=new d(this);return Tp(this,u),u.child=function(...e){return h.call(this,n,...e)},u.level=o.level||this.level,n.onChild(u),u}return l.levels=function(e){const t=e.customLevels||{},n=Object.assign({},Op.levels.values,t),r=Object.assign({},Op.levels.labels,function(e){const t={};return Object.keys(e).forEach(function(n){t[e[n]]=n}),t}(t));return{values:n,labels:r}}(e),l.level=c,l.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=jp,l.serializers=r,l._serialize=i,l._stdErrSerialize=s,l.child=function(...e){return h.call(this,d,...e)},t&&(l._logEvent=Bp()),l}function $p(e,t,n,r){if(Object.defineProperty(e,r,{value:Sp(e.level,n)>Sp(r,n)?jp:n[Pp][r],writable:!0,enumerable:!0,configurable:!0}),e[r]===jp){if(!t.transmit)return;const i=Sp(t.transmit.level||e.level,n);if(Sp(r,n)<i)return}e[r]=function(e,t,n,r){return function(i){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Ip?Ip:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(Rp(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),t.asObject||t.formatters?i.call(a,...function(e,t,n,r,i){const{level:s,log:o=e=>e}=i.formatters||{},a=n.slice();let c=a[0];const l={};let d=1+(0|e._childLevel);if(d<1&&(d=1),r&&(l.time=r),s){const n=s(t,e.levels.values[t]);Object.assign(l,n)}else l.level=e.levels.values[t];if(i.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());return[o(l),...a]}if(null!==c&&"object"==typeof c){for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());c=a.length?kp(a.shift(),a):void 0}else"string"==typeof c&&(c=kp(a.shift(),a));return void 0!==c&&(l[i.messageKey]=c),[o(l)]}(this,r,o,s,t)):i.apply(a,o),t.transmit){const i=Sp(t.transmit.level||e._level,n),a=Sp(r,n);if(a<i)return;!function(e,t,n,r=!1){const i=t.send,s=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;r||Rp(n,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=n.filter(function(e){return-1===l.indexOf(e)}),e._logEvent.level.label=o,e._logEvent.level.value=a,i(o,e._logEvent,c),e._logEvent=Bp(l)}(this,{ts:s,methodLevel:r,methodValue:a,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Sp(e._level,n)},o,l)}}}(e[Pp][r])}(e,t,n,r);const i=function(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[Np];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}(e);0!==i.length&&(e[r]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(i,e[r]))}function Rp(e,t,n,r){for(const i in e)if(r&&e[i]instanceof Error)e[i]=Op.stdSerializers.err(e[i]);else if("object"==typeof e[i]&&!Array.isArray(e[i])&&t)for(const r in e[i])t.indexOf(r)>-1&&r in n&&(e[i][r]=n[r](e[i][r]))}function Bp(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function Mp(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)void 0===t[n]&&(t[n]=e[n]);return t}function Up(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?zp:Hp}function Lp(){return{}}function Dp(e){return e}function jp(){}function zp(){return!1}function Hp(){return Date.now()}Op.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Op.stdSerializers=Cp,Op.stdTimeFunctions=Object.assign({},{nullTime:zp,epochTime:Hp,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),Ep.exports.default=Op,Ep.exports.pino=Op;const Vp="info",Fp="custom_context",qp=1024e3;var Wp=Object.defineProperty,Zp=(e,t,n)=>((e,t,n)=>t in e?Wp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);let Kp=class{constructor(e){Zp(this,"nodeValue"),Zp(this,"sizeInBytes"),Zp(this,"next"),this.nodeValue=e,this.sizeInBytes=(new TextEncoder).encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Gp=class{constructor(e){Zp(this,"lengthInNodes"),Zp(this,"sizeInBytes"),Zp(this,"head"),Zp(this,"tail"),Zp(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new Kp(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;null!==t;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}};function Yp(e){return"string"==typeof e?e:(e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString()+"n":t))(e)||""}var Jp=Object.defineProperty,Qp=(e,t,n)=>((e,t,n)=>t in e?Jp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);let Xp=class{constructor(e,t=qp){Qp(this,"logs"),Qp(this,"level"),Qp(this,"levelValue"),Qp(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Ep.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Gp(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Ep.exports.levels.values.error?console.error(e):t===Ep.exports.levels.values.warn?console.warn(e):t===Ep.exports.levels.values.debug?console.debug(e):t===Ep.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Yp({timestamp:(new Date).toISOString(),log:e}));const t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Gp(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Yp({extraMetadata:e})),new Blob(t,{type:"application/json"})}};var ef=Object.defineProperty,tf=(e,t,n)=>((e,t,n)=>t in e?ef(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);let nf=class{constructor(e,t=qp){tf(this,"baseChunkLogger"),this.baseChunkLogger=new Xp(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=t,n.download=`walletconnect-logs-${(new Date).toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(t)}};var rf=Object.defineProperty,sf=(e,t,n)=>((e,t,n)=>t in e?rf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);let of=class{constructor(e,t=qp){sf(this,"baseChunkLogger"),this.baseChunkLogger=new Xp(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var af=Object.defineProperty,cf=Object.defineProperties,lf=Object.getOwnPropertyDescriptors,df=Object.getOwnPropertySymbols,hf=Object.prototype.hasOwnProperty,uf=Object.prototype.propertyIsEnumerable,pf=(e,t,n)=>t in e?af(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ff=(e,t)=>{for(var n in t||(t={}))hf.call(t,n)&&pf(e,n,t[n]);if(df)for(var n of df(t))uf.call(t,n)&&pf(e,n,t[n]);return e},gf=(e,t)=>cf(e,lf(t));function mf(e){return gf(ff({},e),{level:e?.level||Vp})}function yf(e,t=Fp){return e[t]||""}function wf(e,t,n=Fp){const r=function(e,t,n=Fp){const r=yf(e,n);return r.trim()?`${r}/${t}`:t}(e,t,n);return function(e,t,n=Fp){return e[n]=t,e}(e.child({context:r}),r,n)}function bf(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const n=gf(ff({},e.opts),{level:"string"==typeof e.loggerOverride?e.loggerOverride:null==(t=e.opts)?void 0:t.level});return typeof window<"u"?function(e){var t,n;const r=new nf(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Ep.exports(gf(ff({},e.opts),{level:"trace",browser:gf(ff({},null==(n=e.opts)?void 0:n.browser),{write:e=>r.write(e)})})),chunkLoggerController:r}}(gf(ff({},e),{opts:n})):function(e){var t,n;const r=new of(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Ep.exports(gf(ff({},e.opts),{level:"trace",browser:gf(ff({},null==(n=e.opts)?void 0:n.browser),{write:e=>r.write(e)})}),r),chunkLoggerController:r}}(gf(ff({},e),{opts:n}))}function vf(e){const[t,n]=e.split(":");return{namespace:t,reference:n}}function Ef(e,t=[]){const n=[];return Object.keys(e).forEach(r=>{if(t.length&&!t.includes(r))return;const i=e[r];n.push(...i.accounts)}),n}function xf(e,t){return e.includes(":")?[e]:t.chains||[]}const Af={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}},kf={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 If(e,t){const{message:n,code:r}=kf[e];return{message:t?`${n} ${t}`:n,code:r}}function Cf(e,t){const{message:n,code:r}=Af[e];return{message:t?`${n} ${t}`:n,code:r}}const Sf="react-native",Pf="node",Nf="browser",_f="unknown",Tf="js";function Of(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function $f(){return!ge()&&!!me()&&"ReactNative"===navigator.product}function Rf(){return!Of()&&!!me()&&!!ge()}function Bf(){return $f()?Sf:Of()?Pf:Rf()?Nf:_f}function Mf(){try{return $f()&&typeof e<"u"&&typeof e?.Application<"u"?e.Application?.applicationId:void 0}catch{return}}function Uf(){return be()||{name:"",description:"",url:"",icons:[""]}}function Lf(t,n,r){const i=function(){if(Bf()===Sf&&typeof e<"u"&&typeof e?.Platform<"u"){const{OS:t,Version:n}=e.Platform;return[t,n].join("-")}const t=M();if(null===t)return"unknown";const n=t.os?t.os.replace(" ","").toLowerCase():"unknown";return"browser"===t.type?[n,t.name,t.version].join("-"):[n,t.version].join("-")}(),s=function(){const e=Bf();return e===Nf?[e,ye()?.host||"unknown"].join(":"):e}();return[[t,n].join("-"),[Tf,r].join("-"),i,s].join("/")}function Df({protocol:e,version:t,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),d={auth:i,ua:Lf(e,t,r),projectId:s,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=function(e,t){const n=new URLSearchParams(e);return Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,t])=>{null!=t&&n.set(e,String(t))}),n.toString()}(l[1]||"",d);return l[0]+"?"+h}function jf(e,t){return e.filter(e=>t.includes(e)).length===e.length}function zf(e){return Object.fromEntries(e.entries())}function Hf(e){return new Map(Object.entries(e))}function Vf(e=U.FIVE_MINUTES,t){const n=U.toMiliseconds(e||U.FIVE_MINUTES);let r,i,s,o;return{resolve:e=>{s&&r&&(clearTimeout(s),r(e),o=Promise.resolve(e))},reject:e=>{s&&i&&(clearTimeout(s),i(e))},done:()=>new Promise((e,a)=>{if(o)return e(o);s=setTimeout(()=>{const e=If("EXPIRED"),n=new Error(t||e.message);n.code=e.code,a(n)},n),r=e,i=a})}}function Ff(e,t,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),t);try{r(await e)}catch(e){i(e)}clearTimeout(s)})}function qf(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function Wf(e){const[t,n]=e.split(":"),r={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof n)r.topic=n;else{if("id"!==t||!Number.isInteger(Number(n)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${n}`);r.id=Number(n)}return r}function Zf(e,t){return U.fromMiliseconds(Date.now()+U.toMiliseconds(e))}function Kf(e){return Date.now()>=U.toMiliseconds(e)}function Gf(e,t){return`${e}${t?`:${t}`:""}`}function Yf(e=[],t=[]){return[...new Set([...e,...t])]}async function Jf({id:t,topic:n,wcDeepLink:r}){try{if(!r)return;const i=("string"==typeof r?JSON.parse(r):r)?.href;if("string"!=typeof i)return;const s=function(e,t,n){const r=`requestId=${t}&sessionTopic=${n}`;e.endsWith("/")&&(e=e.slice(0,-1));let i=`${e}`;if(e.startsWith("https://t.me")){i=`${i}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const n=(new TextEncoder).encode(e),r=new Array(n.length);for(let e=0;e<n.length;e++)r[e]=String.fromCharCode(n[e]);const i=btoa(r.join(""));return t?i.replace(/[=]/g,""):i}(r,!0)}`}else i=`${i}/wc?${r}`;return i}(i,t,n),o=Bf();if(o===Nf){if(!ge()?.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(s)}else o===Sf&&typeof e?.Linking<"u"&&await e.Linking.openURL(s)}catch(e){console.error(e)}}function Qf(e,t){if(!e.includes(t))return null;const n=e.split(/([&,?,=])/),r=n.indexOf(t);return n[r+2]}function Xf(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function eg(){return typeof process<"u"&&"true"===process.env.IS_VITEST}function tg(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return(new TextDecoder).decode(r)}let ng=class{constructor({limit:e}){this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const e=this.set.values().next().value;e&&this.set.delete(e)}this.set.add(e)}}has(e){return this.set.has(e)}};const rg="https://rpc.walletconnect.org/v1";function ig(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function sg(e){const t=`Ethereum Signed Message:\n${e.length}`,n=(new TextEncoder).encode(t+e);return"0x"+Xo($t(n),"base16")}async function og(e,t,n,r,i,s){switch(n.t){case"eip191":return await function(e,t,n){const r=$i(n);return ds({payload:sg(t),signature:r}).toLowerCase()===e.toLowerCase()}(e,t,n.s);case"eip1271":return await async function(e,t,n,r,i,s){const o=vf(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c=n.substring(2),l=(c.length/2).toString(16).padStart(64,"0"),d=o+(t.startsWith("0x")?t:sg(t)).substring(2)+a+l+c,h=await fetch(`${s||rg}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:ag(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:u}=await h.json();return!!u&&u.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function ag(){return Date.now()+Math.floor(1e3*Math.random())}function cg(e){const t=ig(e),n=(new TextEncoder).encode("TransactionData::"),r=new Uint8Array(n.length+t.length);r.set(n),r.set(t,n.length);const i=Fi(r,{dkLen:32});return as.encode(i)}function lg(e){const t=new Uint8Array(en(function(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("object"==typeof e&&e?.data)return new Uint8Array(Object.values(e.data));if("object"==typeof e&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}(e)));return as.encode(t)}function dg(e){const t=function(e,t){return new Gs(t).decode(e)}(ig(e)).txn;if(!t)throw new Error("Invalid signed transaction: missing 'txn' field");const n=(s=t,new Ls(o).encodeSharedRef(s)),r=Qs([(new TextEncoder).encode("TX"),new Uint8Array(n)]),i=rn(r);var s,o;return os.encode(i).replace(/=+$/,"")}function hg(e){const t=[];let n=BigInt(e);for(;n>=0x80n;)t.push(Number(0x7fn&n|0x80n)),n>>=7n;return t.push(Number(n)),new Uint8Array(t)}function ug(e){const t=ig(e.signed.bodyBytes),n=ig(e.signed.authInfoBytes),r=ig(e.signature.signature),i=[];i.push(new Uint8Array([10])),i.push(hg(t.length)),i.push(t),i.push(new Uint8Array([18])),i.push(hg(n.length)),i.push(n),i.push(new Uint8Array([26])),i.push(hg(r.length)),i.push(r);const s=Qs(i);return Xo(en(s),"base16").toUpperCase()}const pg="did:pkh:",fg={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},gg=e=>e?.split(":"),mg=e=>{const t=e&&gg(e);if(t)return t[2]+":"+t[3]},yg=e=>{const t=e&&gg(e);if(t)return t.pop()};async function wg(e){const{cacao:t,projectId:n}=e,{s:r,p:i}=t,s=bg(i,i.iss),o=yg(i.iss);return await og(o,s,r,mg(i.iss),n)}const bg=(e,t)=>{const n=(e=>{const t=e&&gg(e);if(t)return e.includes(pg)?t[2]:t[0]})(t);if(!n)throw new Error("Invalid issuer: "+t);const r=`${e.domain} wants you to sign in with your ${(e=>e?fg[e]||e:"")(n)} account:`,i=yg(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0;const o=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${(e=>{const t=e&&gg(e);if(t)return e.includes(pg)?t[3]:t[1]})(t)}`,l=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,h=e.exp?`Expiration Time: ${e.exp}`:void 0,u=e.nbf?`Not Before: ${e.nbf}`:void 0,p=e.requestId?`Request ID: ${e.requestId}`:void 0,f=e.resources?`Resources:${e.resources.map(e=>`\n- ${e}`).join("")}`:void 0,g=Pg(e.resources);if(g){s=function(e="",t){vg(t);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(n))return e;const r=[];let i=0;Object.keys(t.att).forEach(e=>{const n=Object.keys(t.att[e]).map(e=>({ability:e.split("/")[0],action:e.split("/")[1]}));n.sort((e,t)=>e.action.localeCompare(t.action));const s={};n.forEach(e=>{s[e.ability]||(s[e.ability]=[]),s[e.ability].push(e.action)});const o=Object.keys(s).map(t=>(i++,`(${i}) '${t}': '${s[t].join("', '")}' for '${e}'.`));r.push(o.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${e?e+" ":""}${o}`}(s,Ag(g))}return[r,i,"",s,"",o,a,c,l,d,h,u,p,f].filter(e=>null!=e).join("\n")};function vg(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(!t?.length)throw new Error("No resources found in `att` property");t.forEach(t=>{const n=e.att[t];if(Array.isArray(n))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof n)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(n).forEach(e=>{const t=n[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach(t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)})})})}function Eg(e,t,n={}){t=t?.sort((e,t)=>e.localeCompare(t));const r=t.map(t=>({[`${e}/${t}`]:[n]}));return Object.assign({},...r)}function xg(e){return vg(e),`urn:recap:${function(e){const t=JSON.stringify(e),n=(new TextEncoder).encode(t),r=new Array(n.length);for(let e=0;e<n.length;e++)r[e]=String.fromCharCode(n[e]);return btoa(r.join(""))}(e).replace(/=/g,"")}`}function Ag(e){const t=function(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return JSON.parse((new TextDecoder).decode(r))}(e.replace("urn:recap:",""));return vg(t),t}function kg(e,t,n){const r=function(e,t,n,r={}){return n?.sort((e,t)=>e.localeCompare(t)),{att:{[e]:Eg(t,n,r)}}}(e,t,n);return xg(r)}function Ig(e,t){const n=function(e,t){vg(e),vg(t);const n=Object.keys(e.att).concat(Object.keys(t.att)).sort((e,t)=>e.localeCompare(t)),r={att:{}};return n.forEach(n=>{Object.keys(e.att?.[n]||{}).concat(Object.keys(t.att?.[n]||{})).sort((e,t)=>e.localeCompare(t)).forEach(i=>{r.att[n]={...r.att[n],[i]:e.att[n]?.[i]||t.att[n]?.[i]}})}),r}(Ag(e),Ag(t));return xg(n)}function Cg(e){const t=Ag(e);vg(t);const n=t.att?.eip155;return n?Object.keys(n).map(e=>e.split("/")[1]):[]}function Sg(e){const t=Ag(e);vg(t);const n=[];return Object.values(t.att).forEach(e=>{Object.values(e).forEach(e=>{e?.[0]?.chains&&n.push(e[0].chains)})}),[...new Set(n.flat())]}function Pg(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}const Ng="base10",_g="base16",Tg="base64pad",Og="base64url",$g="utf8";function Rg(){return Xo(yt(32),_g)}function Bg(e){return Xo(sn(Qo(e,_g)),_g)}function Mg(e){return Xo(sn(Qo(e,$g)),_g)}function Ug(e){return Qo(`${e}`,Ng)}function Lg(e){return Number(Xo(e,Ng))}function Dg(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function jg(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+"=".repeat(n)}function zg(e){if(2===Lg(e.type))return Xo(Qs([e.type,e.sealed]),Tg);if(1===Lg(e.type)){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Xo(Qs([e.type,e.senderPublicKey,e.iv,e.sealed]),Tg)}return Xo(Qs([e.type,e.iv,e.sealed]),Tg)}function Hg(e){const t=Qo((e.encoding||Tg)===Og?jg(e.encoded):e.encoded,Tg),n=t.slice(0,1);if(1===Lg(n)){const e=33,r=e+12,i=t.slice(1,e),s=t.slice(e,r);return{type:n,sealed:t.slice(r),iv:s,senderPublicKey:i}}if(2===Lg(n)){return{type:n,sealed:t.slice(1),iv:yt(12)}}const r=t.slice(1,13);return{type:n,sealed:t.slice(13),iv:r}}function Vg(e){const t=e?.type||0;if(1===t){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Fg(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function qg(e){return 2===e.type}function Wg(e,t){const[n,r,i]=e.split("."),s=Qo(jg(i),Tg);if(64!==s.length)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=sn(`${n}.${r}`),l=function(e){const t=Qo(jg(e.x),Tg),n=Qo(jg(e.y),Tg);return Qs([new Uint8Array([4]),t,n])}(t);if(!ul.verify(Qs([o,a]),c,l))throw new Error("Invalid signature");return Lu(e).payload}function Zg(e){return e?.relay||{protocol:"irn"}}function Kg(e){const t=zu[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Gg(e,t="-"){const n={},r="relay"+t;return Object.keys(e).forEach(t=>{if(t.startsWith(r)){const i=t.replace(r,""),s=e[t];n[i]=s}}),n}function Yg(e){if(!e.includes("wc:")){const t=tg(e);t?.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),n=-1!==e.indexOf("?")?e.indexOf("?"):void 0,r=e.substring(0,t),i=e.substring(t+1,n).split("@"),s=typeof n<"u"?e.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:r,topic:Jg(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:Gg(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Jg(e){return e.startsWith("//")?e.substring(2):e}function Qg(e,t="-"){const n={};return Object.keys(e).forEach(r=>{const i=r,s="relay"+t+i;e[i]&&(n[s]=e[i])}),n}function Xg(e){const t=new URLSearchParams,n={...Qg(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(n).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,n])=>{void 0!==n&&t.append(e,String(n))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function em(e,t,n){return`${e}?wc_ev=${n}&topic=${t}`}function tm(e){const t=[];return e.forEach(e=>{const[n,r]=e.split(":");t.push(`${n}:${r}`)}),t}function nm(e){const t=[];return Object.values(e).forEach(e=>{t.push(...tm(e.accounts))}),[...new Set(t)]}function rm(e){return e.includes(":")}function im(e){return rm(e)?e.split(":")[0]:e}function sm(e){const t={};if(!cm(e))return t;for(const[n,r]of Object.entries(e)){const e=rm(n)?[n]:r.chains,i=r.methods||[],s=r.events||[],o=im(n);t[o]={...t[o],chains:Yf(e,t[o]?.chains),methods:Yf(i,t[o]?.methods),events:Yf(s,t[o]?.events)}}return t}function om(e,t){t=t.map(e=>e.replace("did:pkh:",""));const n=function(e){const t={};return e?.forEach(e=>{const[n,r]=e.split(":");t[n]||(t[n]={accounts:[],chains:[],events:[],methods:[]}),t[n].accounts.push(e),t[n].chains?.push(`${n}:${r}`)}),t}(t);for(const[t,r]of Object.entries(n))r.methods?r.methods=Yf(r.methods,e):r.methods=e,r.events=["chainChanged","accountsChanged"];return n}function am(e,t){return!!Array.isArray(e)}function cm(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function lm(e){return typeof e>"u"}function dm(e,t){return!(!t||!lm(e))||"string"==typeof e&&!!e.trim().length}function hm(e,t){return!(!t||!lm(e))||"number"==typeof e&&!isNaN(e)}function um(e){return!(!dm(e,!1)||!e.includes(":"))&&2===e.split(":").length}function pm(e){let t=!0;return am(e)?e.length&&(t=e.every(e=>dm(e,!1))):t=!1,t}function fm(e,t,n){let r=null;return Object.entries(e).forEach(([e,i])=>{if(r)return;const s=function(e,t,n){let r=null;return am(t)&&t.length?t.forEach(e=>{r||um(e)||(r=Cf("UNSUPPORTED_CHAINS",`${n}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):um(e)||(r=Cf("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}(e,xf(e,i),`${t} ${n}`);s&&(r=s)}),r}function gm(e,t){let n=null;return am(e)?e.forEach(e=>{n||function(e){if(dm(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&um(e)}}return!1}(e)||(n=Cf("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):n=Cf("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function mm(e,t){let n=null;return Object.values(e).forEach(e=>{if(n)return;const r=function(e,t){let n=null;return pm(e?.methods)?pm(e?.events)||(n=Cf("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):n=Cf("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),n}(e,`${t}, namespace`);r&&(n=r)}),n}function ym(e,t){let n=null;if(e&&cm(e)){const r=mm(e,t);r&&(n=r);const i=function(e,t){let n=null;return Object.values(e).forEach(e=>{if(n)return;const r=gm(e?.accounts,`${t} namespace`);r&&(n=r)}),n}(e,t);i&&(n=i)}else n=If("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return n}function wm(e){return dm(e.protocol,!0)}function bm(e){return typeof e<"u"&&null!==typeof e}function vm(e,t){return!(!um(t)||!nm(e).includes(t))}function Em(e,t,n){return!!dm(n,!1)&&function(e,t){const n=[];return Object.values(e).forEach(e=>{tm(e.accounts).includes(t)&&n.push(...e.methods)}),n}(e,t).includes(n)}function xm(e,t,n){return!!dm(n,!1)&&function(e,t){const n=[];return Object.values(e).forEach(e=>{tm(e.accounts).includes(t)&&n.push(...e.events)}),n}(e,t).includes(n)}function Am(e,t,n){let r=null;const i=function(e){const t={};return Object.keys(e).forEach(n=>{n.includes(":")?t[n]=e[n]:e[n].chains?.forEach(r=>{t[r]={methods:e[n].methods,events:e[n].events}})}),t}(e),s=function(e){const t={};return Object.keys(e).forEach(n=>{n.includes(":")?t[n]=e[n]:tm(e[n].accounts)?.forEach(r=>{t[r]={accounts:e[n].accounts.filter(e=>e.includes(`${r}:`)),methods:e[n].methods,events:e[n].events}})}),t}(t),o=Object.keys(i),a=Object.keys(s),c=km(Object.keys(e)),l=km(Object.keys(t)),d=c.filter(e=>!l.includes(e));return d.length&&(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),jf(o,a)||(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||r)return;const i=tm(t[e].accounts);i.includes(e)||(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${i.toString()}`))}),o.forEach(e=>{r||(jf(i[e].methods,s[e].methods)?jf(i[e].events,s[e].events)||(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${e}`)):r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${e}`))}),r}function km(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Im(){const t=Bf();return new Promise(n=>{switch(t){case Nf:n(Rf()&&navigator?.onLine);break;case Sf:n(async function(){return!($f()&&typeof e<"u"&&e?.NetInfo)||(await(e?.NetInfo.fetch()))?.isConnected}());break;default:n(!0)}})}function Cm(t){switch(Bf()){case Nf:!function(e){!$f()&&Rf()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}(t);break;case Sf:!function(t){$f()&&typeof e<"u"&&e?.NetInfo&&e?.NetInfo.addEventListener(e=>t(e?.isConnected))}(t)}}const Sm={};let Pm=class{static get(e){return Sm[e]}static set(e,t){Sm[e]=t}static delete(e){delete Sm[e]}};function Nm({publicKey:e,signature:t,payload:n}){const r=_m(n.method),i=128|parseInt(n.version?.toString()||"4"),s=function(e){const t=as.decode(e)[0];return 42===t?0:60===t?2:1}(n.address),o="00"===n.era?new Uint8Array([0]):_m(n.era);if(1!==o.length&&2!==o.length)throw new Error("Invalid era length");const a=parseInt(n.nonce,16),c=new Uint8Array([255&a,a>>8&255]),l=BigInt(`0x${function(e){return e.startsWith("0x")?e.slice(2):e}(n.tip)}`),d=function(e){if(e<64n)return new Uint8Array([Number(e<<2n)]);if(e<16384n){const t=e<<2n|0x01n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn)])}if(e<1n<<30n){const t=e<<2n|0x02n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}throw new Error("BigInt compact encoding not supported > 2^30")}(l),h=new Uint8Array([0,...e,s,...t,...o,...c,...d,...r]),u=function(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){const t=e<<2|1;return new Uint8Array([255&t,t>>8&255])}if(e<1<<30){const t=e<<2|2;return new Uint8Array([255&t,t>>8&255,t>>16&255,t>>24&255])}throw new Error("Compact encoding > 2^30 not supported")}(h.length+1);return new Uint8Array([...u,i,...h])}function _m(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Tm(e){const t=_m(e.signature),n=function(e){const t=as.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}(e.transaction.address);return function(e){const t=_m(e);return"0x"+Xo(vp.blake2b(t,void 0,32),"base16")}(Xo(Nm({publicKey:n,signature:t,payload:e.transaction}),"base16"))}function Om({logger:e,name:t}){const n="string"==typeof e?bf({opts:{level:e,name:t}}).logger:e;return n.level="string"==typeof e?e:e.level,n}class $m{}let Rm=class extends $m{constructor(e){super()}};const Bm=U.FIVE_SECONDS,Mm="heartbeat_pulse";let Um=class e extends Rm{constructor(e){super(e),this.events=new I.EventEmitter,this.interval=Bm,this.interval=e?.interval||Bm}static async init(t){const n=new e(t);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}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 initialize(){this.intervalRef=setInterval(()=>this.pulse(),U.toMiliseconds(this.interval))}pulse(){this.events.emit(Mm)}};const Lm=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,Dm=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,jm=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function zm(e,t){if(!("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t))return t;!function(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}(e)}function Hm(e,t={}){if("string"!=typeof e)return e;if('"'===e[0]&&'"'===e[e.length-1]&&-1===e.indexOf("\\"))return e.slice(1,-1);const n=e.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!jm.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(Lm.test(e)||Dm.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,zm)}return JSON.parse(e)}catch(n){if(t.strict)throw n;return e}}function Vm(e,...t){try{return(n=e(...t))&&"function"==typeof n.then?n:Promise.resolve(n)}catch(e){return Promise.reject(e)}var n}function Fm(e){if(function(e){const t=typeof e;return null===e||"object"!==t&&"function"!==t}(e))return String(e);if(function(e){const t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}(e)||Array.isArray(e))return JSON.stringify(e);if("function"==typeof e.toJSON)return Fm(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const qm="base64:";function Wm(e){return"string"==typeof e?e:qm+function(e){if(globalThis.Buffer)return Buffer.from(e).toString("base64");return globalThis.btoa(String.fromCodePoint(...e))}(e)}function Zm(e){return"string"!=typeof e?e:e.startsWith(qm)?function(e){if(globalThis.Buffer)return Buffer.from(e,"base64");return Uint8Array.from(globalThis.atob(e),e=>e.codePointAt(0))}(e.slice(7)):e}function Km(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Gm(...e){return Km(e.join(":"))}function Ym(e){return(e=Km(e))?e+":":""}const Jm=()=>{const e=new Map;return{name:"memory",getInstance:()=>e,hasItem:t=>e.has(t),getItem:t=>e.get(t)??null,getItemRaw:t=>e.get(t)??null,setItem(t,n){e.set(t,n)},setItemRaw(t,n){e.set(t,n)},removeItem(t){e.delete(t)},getKeys:()=>[...e.keys()],clear(){e.clear()},dispose(){e.clear()}}};function Qm(e={}){const t={mounts:{"":e.driver||Jm()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=e=>{for(const n of t.mountpoints)if(e.startsWith(n))return{base:n,relativeKey:e.slice(n.length),driver:t.mounts[n]};return{base:"",relativeKey:e,driver:t.mounts[""]}},r=(e,n)=>t.mountpoints.filter(t=>t.startsWith(e)||n&&e.startsWith(t)).map(n=>({relativeBase:e.length>n.length?e.slice(n.length):void 0,mountpoint:n,driver:t.mounts[n]})),i=(e,n)=>{if(t.watching){n=Km(n);for(const r of t.watchListeners)r(e,n)}},s=async()=>{if(t.watching){for(const e in t.unwatch)await t.unwatch[e]();t.unwatch={},t.watching=!1}},o=(e,t,r)=>{const i=new Map,s=e=>{let t=i.get(e.base);return t||(t={driver:e.driver,base:e.base,items:[]},i.set(e.base,t)),t};for(const r of e){const e="string"==typeof r,i=Km(e?r:r.key),o=e?void 0:r.value,a=e||!r.options?t:{...t,...r.options},c=n(i);s(c).items.push({key:i,value:o,relativeKey:c.relativeKey,options:a})}return Promise.all([...i.values()].map(e=>r(e))).then(e=>e.flat())},a={hasItem(e,t={}){e=Km(e);const{relativeKey:r,driver:i}=n(e);return Vm(i.hasItem,r,t)},getItem(e,t={}){e=Km(e);const{relativeKey:r,driver:i}=n(e);return Vm(i.getItem,r,t).then(e=>Hm(e))},getItems:(e,t={})=>o(e,t,e=>e.driver.getItems?Vm(e.driver.getItems,e.items.map(e=>({key:e.relativeKey,options:e.options})),t).then(t=>t.map(t=>({key:Gm(e.base,t.key),value:Hm(t.value)}))):Promise.all(e.items.map(t=>Vm(e.driver.getItem,t.relativeKey,t.options).then(e=>({key:t.key,value:Hm(e)}))))),getItemRaw(e,t={}){e=Km(e);const{relativeKey:r,driver:i}=n(e);return i.getItemRaw?Vm(i.getItemRaw,r,t):Vm(i.getItem,r,t).then(e=>Zm(e))},async setItem(e,t,r={}){if(void 0===t)return a.removeItem(e);e=Km(e);const{relativeKey:s,driver:o}=n(e);o.setItem&&(await Vm(o.setItem,s,Fm(t),r),o.watch||i("update",e))},async setItems(e,t){await o(e,t,async e=>{if(e.driver.setItems)return Vm(e.driver.setItems,e.items.map(e=>({key:e.relativeKey,value:Fm(e.value),options:e.options})),t);e.driver.setItem&&await Promise.all(e.items.map(t=>Vm(e.driver.setItem,t.relativeKey,Fm(t.value),t.options)))})},async setItemRaw(e,t,r={}){if(void 0===t)return a.removeItem(e,r);e=Km(e);const{relativeKey:s,driver:o}=n(e);if(o.setItemRaw)await Vm(o.setItemRaw,s,t,r);else{if(!o.setItem)return;await Vm(o.setItem,s,Wm(t),r)}o.watch||i("update",e)},async removeItem(e,t={}){"boolean"==typeof t&&(t={removeMeta:t}),e=Km(e);const{relativeKey:r,driver:s}=n(e);s.removeItem&&(await Vm(s.removeItem,r,t),(t.removeMeta||t.removeMata)&&await Vm(s.removeItem,r+"$",t),s.watch||i("remove",e))},async getMeta(e,t={}){"boolean"==typeof t&&(t={nativeOnly:t}),e=Km(e);const{relativeKey:r,driver:i}=n(e),s=Object.create(null);if(i.getMeta&&Object.assign(s,await Vm(i.getMeta,r,t)),!t.nativeOnly){const e=await Vm(i.getItem,r+"$",t).then(e=>Hm(e));e&&"object"==typeof e&&("string"==typeof e.atime&&(e.atime=new Date(e.atime)),"string"==typeof e.mtime&&(e.mtime=new Date(e.mtime)),Object.assign(s,e))}return s},setMeta(e,t,n={}){return this.setItem(e+"$",t,n)},removeMeta(e,t={}){return this.removeItem(e+"$",t)},async getKeys(e,t={}){e=Ym(e);const n=r(e,!0);let i=[];const s=[];let o=!0;for(const e of n){e.driver.flags?.maxDepth||(o=!1);const n=await Vm(e.driver.getKeys,e.relativeBase,t);for(const t of n){const n=e.mountpoint+Km(t);i.some(e=>n.startsWith(e))||s.push(n)}i=[e.mountpoint,...i.filter(t=>!t.startsWith(e.mountpoint))]}const a=void 0!==t.maxDepth&&!o;return s.filter(n=>(!a||function(e,t){if(void 0===t)return!0;let n=0,r=e.indexOf(":");for(;r>-1;)n++,r=e.indexOf(":",r+1);return n<=t}(n,t.maxDepth))&&function(e,t){return t?e.startsWith(t)&&"$"!==e[e.length-1]:"$"!==e[e.length-1]}(n,e))},async clear(e,t={}){e=Ym(e),await Promise.all(r(e,!1).map(async e=>{if(e.driver.clear)return Vm(e.driver.clear,e.relativeBase,t);if(e.driver.removeItem){const n=await e.driver.getKeys(e.relativeBase||"",t);return Promise.all(n.map(n=>e.driver.removeItem(n,t)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(e=>ey(e)))},watch:async e=>(await(async()=>{if(!t.watching){t.watching=!0;for(const e in t.mounts)t.unwatch[e]=await Xm(t.mounts[e],i,e)}})(),t.watchListeners.push(e),async()=>{t.watchListeners=t.watchListeners.filter(t=>t!==e),0===t.watchListeners.length&&await s()}),async unwatch(){t.watchListeners=[],await s()},mount(e,n){if((e=Ym(e))&&t.mounts[e])throw new Error(`already mounted at ${e}`);return e&&(t.mountpoints.push(e),t.mountpoints.sort((e,t)=>t.length-e.length)),t.mounts[e]=n,t.watching&&Promise.resolve(Xm(n,i,e)).then(n=>{t.unwatch[e]=n}).catch(console.error),a},async unmount(e,n=!0){(e=Ym(e))&&t.mounts[e]&&(t.watching&&e in t.unwatch&&(t.unwatch[e]?.(),delete t.unwatch[e]),n&&await ey(t.mounts[e]),t.mountpoints=t.mountpoints.filter(t=>t!==e),delete t.mounts[e])},getMount(e=""){e=Km(e)+":";const t=n(e);return{driver:t.driver,base:t.base}},getMounts(e="",t={}){e=Km(e);return r(e,t.parents).map(e=>({driver:e.driver,base:e.mountpoint}))},keys:(e,t={})=>a.getKeys(e,t),get:(e,t={})=>a.getItem(e,t),set:(e,t,n={})=>a.setItem(e,t,n),has:(e,t={})=>a.hasItem(e,t),del:(e,t={})=>a.removeItem(e,t),remove:(e,t={})=>a.removeItem(e,t)};return a}function Xm(e,t,n){return e.watch?e.watch((e,r)=>t(e,n+r)):()=>{}}async function ey(e){"function"==typeof e.dispose&&await Vm(e.dispose)}function ty(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function ny(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const r=ty(n);return(e,n)=>r.then(r=>n(r.transaction(t,e).objectStore(t)))}let ry;function iy(){return ry||(ry=ny("keyval-store","keyval")),ry}function sy(e,t=iy()){return t("readonly",t=>ty(t.get(e)))}function oy(e=iy()){return e("readonly",e=>{if(e.getAllKeys)return ty(e.getAllKeys());const t=[];return function(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},ty(e.transaction)}(e,e=>t.push(e.key)).then(()=>t)})}var ay=(e={})=>{const t=e.base&&e.base.length>0?`${e.base}:`:"",n=e=>t+e;let r;return e.dbName&&e.storeName&&(r=ny(e.dbName,e.storeName)),{name:"idb-keyval",options:e,hasItem:async e=>!(typeof await sy(n(e),r)>"u"),getItem:async e=>await sy(n(e),r)??null,setItem:(e,t)=>function(e,t,n=iy()){return n("readwrite",n=>(n.put(t,e),ty(n.transaction)))}(n(e),t,r),removeItem:e=>function(e,t=iy()){return t("readwrite",t=>(t.delete(e),ty(t.transaction)))}(n(e),r),getKeys:()=>oy(r),clear:()=>function(e=iy()){return e("readwrite",e=>(e.clear(),ty(e.transaction)))}(r)}};let cy=class{constructor(){this.indexedDb=Qm({driver:ay({dbName:"WALLET_CONNECT_V2_INDEXED_DB",storeName:"keyvaluestorage"})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(null!==t)return t}async setItem(e,t){await this.indexedDb.setItem(e,fl(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ly=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof e<"u"?e:typeof self<"u"?self:{},dy={exports:{}};function hy(e){var t;return[e[0],pl(null!=(t=e[1])?t:"")]}!function(){let e;function t(){}e=t,e.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},e.prototype.setItem=function(e,t){this[e]=String(t)},e.prototype.removeItem=function(e){delete this[e]},e.prototype.clear=function(){const e=this;Object.keys(e).forEach(function(t){e[t]=void 0,delete e[t]})},e.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},e.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ly<"u"&&ly.localStorage?dy.exports=ly.localStorage:typeof window<"u"&&window.localStorage?dy.exports=window.localStorage:dy.exports=new t}();let uy=class{constructor(){this.localStorage=dy.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(hy)}async getItem(e){const t=this.localStorage.getItem(e);if(null!==t)return pl(t)}async setItem(e,t){this.localStorage.setItem(e,fl(t))}async removeItem(e){this.localStorage.removeItem(e)}};const py=async(e,t)=>{t.length&&t.forEach(async t=>{await e.removeItem(t)})};let fy=class{constructor(){this.initialized=!1,this.setInitialized=e=>{this.storage=e,this.initialized=!0};const e=new uy;this.storage=e;try{(async(e,t,n)=>{const r="wc_storage_version",i=await t.getItem(r);if(i&&i>=1)return void n(t);const s=await e.getKeys();if(!s.length)return void n(t);const o=[];for(;s.length;){const n=s.shift();if(!n)continue;const r=n.toLowerCase();if(r.includes("wc@")||r.includes("walletconnect")||r.includes("wc_")||r.includes("wallet_connect")){const r=await e.getItem(n);await t.setItem(n,r),o.push(n)}}await t.setItem(r,1),n(t),py(e,o)})(e,new cy,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}},gy=class extends $m{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},my=class extends $m{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}},yy=class{constructor(e,t){this.logger=e,this.core=t}},wy=class extends $m{constructor(e,t){super(),this.relayer=e,this.logger=t}},by=class extends $m{constructor(e){super()}},vy=class{constructor(e,t,n,r){this.core=e,this.logger=t,this.name=n}},Ey=class extends $m{constructor(e,t){super(),this.relayer=e,this.logger=t}},xy=class extends $m{constructor(e,t){super(),this.core=e,this.logger=t}},Ay=class{constructor(e,t,n){this.core=e,this.logger=t,this.store=n}},ky=class{constructor(e,t){this.projectId=e,this.logger=t}},Iy=class{constructor(e,t,n){this.core=e,this.logger=t,this.telemetryEnabled=n}},Cy=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},Sy=class{constructor(e){this.client=e}};const Py="PARSE_ERROR",Ny="INVALID_REQUEST",_y="METHOD_NOT_FOUND",Ty="INVALID_PARAMS",Oy="INTERNAL_ERROR",$y="SERVER_ERROR",Ry=[-32700,-32600,-32601,-32602,-32603],By={[Py]:{code:-32700,message:"Parse error"},[Ny]:{code:-32600,message:"Invalid Request"},[_y]:{code:-32601,message:"Method not found"},[Ty]:{code:-32602,message:"Invalid params"},[Oy]:{code:-32603,message:"Internal error"},[$y]:{code:-32e3,message:"Server error"}},My=$y;function Uy(e){return Object.keys(By).includes(e)?By[e]:By[My]}function Ly(e,t,n){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${t}`):e}var Dy,jy={},zy={};var Hy,Vy={};function Fy(e=3){return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function qy(e=6){return BigInt(Fy(e))}function Wy(e,t,n){return{id:n||Fy(),jsonrpc:"2.0",method:e,params:t}}function Zy(e,t){return{id:e,jsonrpc:"2.0",result:t}}function Ky(e,t,n){return{id:e,jsonrpc:"2.0",error:Gy(t)}}function Gy(e,t){return void 0===e?Uy(Oy):("string"==typeof e&&(e=Object.assign(Object.assign({},Uy($y)),{message:e})),n=e.code,Ry.includes(n)&&(e=function(e){const t=Object.values(By).find(t=>t.code===e);return t||By[My]}(e.code)),e);var n}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=q;t.__exportStar(function(){if(Dy)return zy;function e(){return(null==o?void 0:o.crypto)||(null==o?void 0:o.msCrypto)||{}}function t(){const t=e();return t.subtle||t.webkitSubtle}return Dy=1,Object.defineProperty(zy,"__esModule",{value:!0}),zy.isBrowserCryptoAvailable=zy.getSubtleCrypto=zy.getBrowerCrypto=void 0,zy.getBrowerCrypto=e,zy.getSubtleCrypto=t,zy.isBrowserCryptoAvailable=function(){return!!e()&&!!t()},zy}(),e),t.__exportStar(function(){if(Hy)return Vy;function e(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product}function t(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}return Hy=1,Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.isBrowser=Vy.isNode=Vy.isReactNative=void 0,Vy.isReactNative=e,Vy.isNode=t,Vy.isBrowser=function(){return!e()&&!t()},Vy}(),e)}(jy);let Yy=class{},Jy=class extends Yy{constructor(){super()}},Qy=class extends Jy{constructor(e){super()}};function Xy(e,t){const n=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return void 0!==n&&new RegExp(t).test(n)}function ew(e){return Xy(e,"^https?:")}function tw(e){return Xy(e,"^wss?:")}function nw(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function rw(e){return nw(e)&&"method"in e}function iw(e){return nw(e)&&(sw(e)||ow(e))}function sw(e){return"result"in e}function ow(e){return"error"in e}let aw=class extends Qy{constructor(e){super(e),this.events=new I.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(Wy(e.method,e.params||[],e.id||qy().toString()),t)}async requestStrict(e,t){return new Promise(async(n,r)=>{if(!this.connection.connected)try{await this.open()}catch(e){r(e)}this.events.on(`${e.id}`,e=>{ow(e)?r(e.error):n(e.result)});try{await this.connection.send(e,t)}catch(e){r(e)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),iw(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&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(),"string"==typeof e&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};var cw,lw;const dw=e=>e.split("?")[0],hw=typeof WebSocket<"u"?WebSocket:typeof e<"u"&&typeof e.WebSocket<"u"?e.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:lw?cw:(lw=1,cw=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")});let uw=class{constructor(e){if(this.url=e,this.events=new I.EventEmitter,this.registering=!1,!tw(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)=>{typeof this.socket>"u"?t(new Error("Connection already closed")):(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close())})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(fl(e))}catch(t){this.onError(e.id,t)}}register(t=this.url){if(!tw(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise((e,t)=>{this.events.once("register_error",e=>{this.resetMaxListeners(),t(e)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const i=jy.isReactNative()?void 0:{rejectUnauthorized:(o=t,!new RegExp("wss?://localhost(:d{2,5})?").test(o))},s=new hw(t,[],i);var o;typeof WebSocket<"u"||typeof e<"u"&&typeof e.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?s.onerror=e=>{const t=e;r(this.emitError(t.error))}:s.on("error",e=>{r(this.emitError(e))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),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="string"==typeof e.data?pl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),r=Ky(e,n.message||n.toString());this.events.emit("payload",r)}parseError(e,t=this.url){return Ly(e,dw(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${dw(this.url)}`));return this.events.emit("register_error",t),t}};function pw(e){return null!=e&&"function"!=typeof e&&function(e){return Number.isSafeInteger(e)&&e>=0}(e.length)}function fw(e){return"__proto__"===e}function gw(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function mw(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function yw(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const ww="[object RegExp]",bw="[object String]",vw="[object Number]",Ew="[object Boolean]",xw="[object Arguments]",Aw="[object Symbol]",kw="[object Date]",Iw="[object Map]",Cw="[object Set]",Sw="[object Array]",Pw="[object ArrayBuffer]",Nw="[object Object]",_w="[object DataView]",Tw="[object Uint8Array]",Ow="[object Uint8ClampedArray]",$w="[object Uint16Array]",Rw="[object Uint32Array]",Bw="[object Int8Array]",Mw="[object Int16Array]",Uw="[object Int32Array]",Lw="[object Float32Array]",Dw="[object Float64Array]";function jw(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function zw(e,t,n,r=new Map,i=void 0){const s=i?.(e,t,n,r);if(void 0!==s)return s;if(gw(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){const t=new Array(e.length);r.set(e,t);for(let s=0;s<e.length;s++)t[s]=zw(e[s],s,n,r,i);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;r.set(e,t);for(const[s,o]of e)t.set(s,zw(o,s,n,r,i));return t}if(e instanceof Set){const t=new Set;r.set(e,t);for(const s of e)t.add(zw(s,void 0,n,r,i));return t}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e.subarray();if(jw(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);r.set(e,t);for(let s=0;s<e.length;s++)t[s]=zw(e[s],s,n,r,i);return t}if(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,t),Hw(t,e,n,r,i),t}if("undefined"!=typeof File&&e instanceof File){const t=new File([e],e.name,{type:e.type});return r.set(e,t),Hw(t,e,n,r,i),t}if("undefined"!=typeof Blob&&e instanceof Blob){const t=new Blob([e],{type:e.type});return r.set(e,t),Hw(t,e,n,r,i),t}if(e instanceof Error){const t=new e.constructor;return r.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,Hw(t,e,n,r,i),t}if(e instanceof Boolean){const t=new Boolean(e.valueOf());return r.set(e,t),Hw(t,e,n,r,i),t}if(e instanceof Number){const t=new Number(e.valueOf());return r.set(e,t),Hw(t,e,n,r,i),t}if(e instanceof String){const t=new String(e.valueOf());return r.set(e,t),Hw(t,e,n,r,i),t}if("object"==typeof e&&function(e){switch(yw(e)){case xw:case Sw:case Pw:case _w:case Ew:case kw:case Lw:case Dw:case Bw:case Mw:case Uw:case Iw:case vw:case Nw:case ww:case Cw:case bw:case Aw:case Tw:case Ow:case $w:case Rw:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return r.set(e,t),Hw(t,e,n,r,i),t}return e}function Hw(e,t,n=e,r,i){const s=[...Object.keys(t),...mw(t)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=zw(t[a],a,n,r,i))}}function Vw(e,t){return function(e,t){return zw(e,void 0,e,new Map,t)}(e,(t,n,r,i)=>{if("object"==typeof e){if(yw(e)===Nw&&"function"!=typeof e.constructor){const t={};return i.set(e,t),Hw(t,e,r,i),t}switch(Object.prototype.toString.call(e)){case vw:case bw:case Ew:{const t=new e.constructor(e?.valueOf());return Hw(t,e),t}case xw:{const t={};return Hw(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function Fw(e){return Vw(e)}function qw(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===yw(e)}function Ww(e){return"object"==typeof e&&null!==e}function Zw(e){return Ww(e)&&pw(e)}function Kw(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function Gw(e,t,n,r,i,s,o){const a=o(e,t,n,r,i,s);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return Yw(e,t,s,o)}return Yw(e,t,s,o)}function Yw(e,t,n,r){if(Object.is(e,t))return!0;let i=yw(e),s=yw(t);if(i===xw&&(i=Nw),s===xw&&(s=Nw),i!==s)return!1;switch(i){case bw:return e.toString()===t.toString();case vw:{const n=e.valueOf(),r=t.valueOf();return(o=n)===(a=r)||Number.isNaN(o)&&Number.isNaN(a)}case Ew:case kw:case Aw:return Object.is(e.valueOf(),t.valueOf());case ww:return e.source===t.source&&e.flags===t.flags;case"[object Function]":return e===t}var o,a;const c=(n=n??new Map).get(e),l=n.get(t);if(null!=c&&null!=l)return c===t;n.set(e,t),n.set(t,e);try{switch(i){case Iw:if(e.size!==t.size)return!1;for(const[i,s]of e.entries())if(!t.has(i)||!Gw(s,t.get(i),i,e,t,n,r))return!1;return!0;case Cw:{if(e.size!==t.size)return!1;const i=Array.from(e.values()),s=Array.from(t.values());for(let o=0;o<i.length;o++){const a=i[o],c=s.findIndex(i=>Gw(a,i,void 0,e,t,n,r));if(-1===c)return!1;s.splice(c,1)}return!0}case Sw:case Tw:case Ow:case $w:case Rw:case"[object BigUint64Array]":case Bw:case Mw:case Uw:case"[object BigInt64Array]":case Lw:case Dw:if("undefined"!=typeof Buffer&&Buffer.isBuffer(e)!==Buffer.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Gw(e[i],t[i],i,e,t,n,r))return!1;return!0;case Pw:return e.byteLength===t.byteLength&&Yw(new Uint8Array(e),new Uint8Array(t),n,r);case _w:return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Yw(new Uint8Array(e),new Uint8Array(t),n,r);case"[object Error]":return e.name===t.name&&e.message===t.message;case Nw:{if(!(Yw(e.constructor,t.constructor,n,r)||Kw(e)&&Kw(t)))return!1;const i=[...Object.keys(e),...mw(e)],s=[...Object.keys(t),...mw(t)];if(i.length!==s.length)return!1;for(let s=0;s<i.length;s++){const o=i[s],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!Gw(a,t[o],o,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Jw(){}function Qw(e,t){return function(e,t,n){return Gw(e,t,void 0,void 0,void 0,void 0,n)}(e,t,Jw)}function Xw(e){return jw(e)}function eb(e){if("object"!=typeof e)return!1;if(null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];if(null==t)return!1;return!!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function tb(e,t,n,r){if(gw(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(r.has(t))return function(e){if(gw(e))return e;if(Array.isArray(e)||jw(e)||e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(null==t)return Object.assign(Object.create(t),e);const n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){const t=new n(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new n(e.errors,e.message,{cause:e.cause}):new n(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}if("undefined"!=typeof File&&e instanceof File)return new n([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const n=Object.create(t);return Object.assign(n,e)}return e}(r.get(t));if(r.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const i=[...Object.keys(t),...mw(t)];for(let s=0;s<i.length;s++){const o=i[s];if(fw(o))continue;let a=t[o],c=e[o];if(qw(a)&&(a={...a}),qw(c)&&(c={...c}),"undefined"!=typeof Buffer&&Buffer.isBuffer(a)&&(a=Fw(a)),Array.isArray(a))if(Array.isArray(c)){const e=[],t=Reflect.ownKeys(c);for(let n=0;n<t.length;n++){const r=t[n];e[r]=c[r]}c=e}else if(Zw(c)){const e=[];for(let t=0;t<c.length;t++)e[t]=c[t];c=e}else c=[];const l=n(c,a,o,e,t,r);void 0!==l?e[o]=l:Array.isArray(a)||Ww(c)&&Ww(a)&&(eb(c)||eb(a)||Xw(c)||Xw(a))?e[o]=tb(c,a,n,r):null==c&&eb(a)?e[o]=tb({},a,n,r):null==c&&Xw(a)?e[o]=Fw(a):void 0!==c&&void 0===a||(e[o]=a)}return e}function nb(e,...t){return function(e,...t){const n=t.slice(0,-1),r=t[t.length-1];let i=e;for(let e=0;e<n.length;e++)i=tb(i,n[e],r,new Map);return i}(e,...t,Jw)}const rb="core",ib=`wc@2:${rb}:`,sb="error",ob={database:":memory:"},ab="client_ed25519_seed",cb=U.ONE_DAY,lb=U.SIX_HOURS,db="wss://relay.walletconnect.org",hb="relayer_message",ub="relayer_message_ack",pb="relayer_connect",fb="relayer_disconnect",gb="relayer_error",mb="relayer_connection_stalled",yb="relayer_publish",wb="payload",bb="connect",vb="disconnect",Eb="error",xb="2.23.9",Ab={link_mode:"link_mode",relay:"relay"},kb="inbound",Ib="outbound",Cb="WALLETCONNECT_LINK_MODE_APPS",Sb="subscription_created",Pb="subscription_deleted",Nb="subscription_sync",_b="subscription_resubscribed",Tb={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}}},Ob="pairing_create",$b="pairing_expire",Rb="pairing_delete",Bb="pairing_ping",Mb="history_created",Ub="history_updated",Lb="history_deleted",Db="history_sync",jb="expirer_created",zb="expirer_deleted",Hb="expirer_expired",Vb="expirer_sync",Fb="https://verify.walletconnect.org",qb=Fb,Wb=`${qb}/v3`,Zb=["https://verify.walletconnect.com",Fb],Kb="pairing_started",Gb="pairing_uri_validation_success",Yb="pairing_uri_not_expired",Jb="store_new_pairing",Qb="subscribing_pairing_topic",Xb="subscribe_pairing_topic_success",ev="existing_pairing",tv="pairing_not_expired",nv="emit_inactive_pairing",rv="emit_session_proposal",iv="no_internet_connection",sv="malformed_pairing_uri",ov="active_pairing_already_exists",av="subscribe_pairing_topic_failure",cv="pairing_expired",lv="proposal_listener_not_found",dv="session_approve_started",hv="session_namespaces_validation_success",uv="subscribing_session_topic",pv="subscribe_session_topic_success",fv="session_approve_publish_success",gv="store_session",mv="session_request_response_started",yv="session_request_response_validation_success",wv="session_request_response_publish_started",bv="no_internet_connection",vv="proposal_expired",Ev="subscribe_session_topic_failure",xv="session_approve_namespace_validation_failure",Av="proposal_not_found",kv="session_request_response_validation_failure",Iv="session_request_response_publish_failure",Cv="authenticated_session_approve_started",Sv="create_authenticated_session_topic",Pv="cacaos_verified",Nv="store_authenticated_session",_v="subscribing_authenticated_session_topic",Tv="subscribe_authenticated_session_topic_success",Ov="publishing_authenticated_session_approve",$v="no_internet_connection",Rv="invalid_cacao",Bv="subscribe_authenticated_session_topic_failure",Mv="authenticated_session_approve_publish_failure",Uv="authenticated_session_pending_request_not_found";let Lv=class{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name="keychain",this.version="0.3",this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=wf(t,this.name)}get context(){return yf(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,zf(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Hf(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Dv=class{constructor(e,t,n){this.core=e,this.logger=t,this.name="crypto",this.randomSessionIdentifier=Rg(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const e=Mu(Du(await this.getClientSeed()).publicKey);return this.clientId=e,e},this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=Dc.utils.randomPrivateKey(),t=Dc.getPublicKey(e);return{privateKey:Xo(e,_g),publicKey:Xo(t,_g)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Du(await this.getClientSeed()),n=this.randomSessionIdentifier,r=cb;return await ju(n,e,r,t)},this.generateSharedKey=(e,t,n)=>{this.isInitialized();const r=function(e,t){const n=Dc.getSharedSecret(Qo(e,_g),Qo(t,_g));return Xo(Aa(sn,n,void 0,void 0,32),_g)}(this.getPrivateKey(e),t);return this.setSymKey(r,n)},this.setSymKey=async(e,t)=>{this.isInitialized();const n=t||Bg(e);return await this.keychain.set(n,e),n},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,n)=>{this.isInitialized();const r=Vg(n),i=fl(t);if(qg(r))return function(e,t){const n=Ug(2),r=yt(12),i=zg({type:n,sealed:Qo(e,$g),iv:r});return t===Og?Dg(i):i}(i,n?.encoding);if(Fg(r)){const t=r.senderPublicKey,n=r.receiverPublicKey;e=await this.generateSharedKey(t,n)}const s=this.getSymKey(e),{type:o,senderPublicKey:a}=r;return function(e){const t=Ug(typeof e.type<"u"?e.type:0);if(1===Lg(t)&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof e.senderPublicKey<"u"?Qo(e.senderPublicKey,_g):void 0,r=typeof e.iv<"u"?Qo(e.iv,_g):yt(12),i=Qo(e.symKey,_g),s=zg({type:t,sealed:ba(i,r).encrypt(Qo(e.message,$g)),iv:r,senderPublicKey:n});return e.encoding===Og?Dg(s):s}({type:o,symKey:s,message:i,senderPublicKey:a,encoding:n?.encoding})},this.decode=async(e,t,n)=>{this.isInitialized();const r=function(e,t){const n=Hg({encoded:e,encoding:t?.encoding});return Vg({type:Lg(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?Xo(n.senderPublicKey,_g):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,n);if(qg(r)){const e=function(e,t){const{sealed:n}=Hg({encoded:e,encoding:t});return Xo(n,$g)}(t,n?.encoding);return pl(e)}if(Fg(r)){const t=r.receiverPublicKey,n=r.senderPublicKey;e=await this.generateSharedKey(t,n)}try{const r=function(e){const t=Qo(e.symKey,_g),{sealed:n,iv:r}=Hg({encoded:e.encoded,encoding:e.encoding}),i=ba(t,r).decrypt(n);if(null===i)throw new Error("Failed to decrypt");return Xo(i,$g)}({symKey:this.getSymKey(e),encoded:t,encoding:n?.encoding});return pl(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=(e,t=Tg)=>Lg(Hg({encoded:e,encoding:t}).type),this.getPayloadSenderPublicKey=(e,t=Tg)=>{const n=Hg({encoded:e,encoding:t});return n.senderPublicKey?Xo(n.senderPublicKey,_g):void 0},this.core=e,this.logger=wf(t,this.name),this.keychain=n||new Lv(this.core,this.logger)}get context(){return yf(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(ab)}catch{e=Rg(),await this.keychain.set(ab,e)}return Qo(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},jv=class extends yy{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t,n)=>{this.isInitialized();const r=Mg(t);let i=this.messages.get(e);if(typeof i>"u"&&(i={}),typeof i[r]<"u")return r;if(i[r]=t,this.messages.set(e,i),n===kb){const n=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,{...n,[r]:t})}return await this.persist(),r},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.getWithoutAck=e=>{this.isInitialized();const t={};for(const n of e){const e=this.messagesWithoutClientAck.get(n)||{};t[n]=Object.values(e)}return t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[Mg(t)]<"u"},this.ack=async(e,t)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(e);if(typeof n>"u")return;delete n[Mg(t)],0===Object.keys(n).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,n),await this.persist()},this.del=async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()},this.logger=wf(e,this.name),this.core=t}get context(){return yf(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,zf(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,zf(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Hf(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Hf(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},zv=class extends wy{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new I.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=U.toMiliseconds(U.ONE_MINUTE),this.initialPublishTimeout=U.toMiliseconds(15*U.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(e,t,n)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:n}});const r=n?.ttl||lb,i=n?.prompt||!1,s=n?.tag||0,o=n?.id||qy().toString(),a=Kg(Zg().protocol),c={id:o,method:n?.publishMethod||a.publish,params:{topic:e,message:t,ttl:r,prompt:i,tag:s,attestation:n?.attestation,...n?.tvf}},l=`Failed to publish payload, please try again. id:${o} tag:${s}`;try{lm(c.params?.prompt)&&delete c.params?.prompt,lm(c.params?.tag)&&delete c.params?.tag;const r=new Promise(async e=>{const t=({id:n})=>{c.id?.toString()===n.toString()&&(this.removeRequestFromQueue(n),this.relayer.events.removeListener(yb,t),e())};this.relayer.events.on(yb,t);const r=Ff(new Promise((e,t)=>{this.rpcPublish(c,n).then(e).catch(e=>{this.logger.warn(e,e?.message),t(e)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${o} tag:${s}`);try{await r,this.events.removeListener(yb,t)}catch(e){this.queue.set(o,{request:c,opts:n,attempt:1}),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:o,topic:e,message:t,opts:n}}),await Ff(r,this.publishTimeout,l)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),n?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(o)}},this.publishCustom=async e=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:e});const{payload:t,opts:n={}}=e,{attestation:r,tvf:i,publishMethod:s,prompt:o,tag:a,ttl:c=U.FIVE_MINUTES}=n,l=n.id||qy().toString(),d=Kg(Zg().protocol),h=s||d.publish,u={id:l,method:h,params:{...t,ttl:c,prompt:o,tag:a,attestation:r,...i}},p=`Failed to publish custom payload, please try again. id:${l} tag:${a}`;try{lm(u.params?.prompt)&&delete u.params?.prompt,lm(u.params?.tag)&&delete u.params?.tag;const e=new Promise(async e=>{const t=({id:n})=>{u.id?.toString()===n.toString()&&(this.removeRequestFromQueue(n),this.relayer.events.removeListener(yb,t),e())};this.relayer.events.on(yb,t);const r=Ff(new Promise((e,t)=>{this.rpcPublish(u,n).then(e).catch(e=>{this.logger.warn(e,e?.message),t(e)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${h} id:${l} tag:${a}`);try{await r,this.events.removeListener(yb,t)}catch(e){this.queue.set(l,{request:u,opts:n,attempt:1}),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,payload:t,opts:n}}),await Ff(e,this.publishTimeout,p)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),n?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(l)}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=wf(t,this.name),this.registerEventListeners()}get context(){return yf(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(yb,{...e,...t}),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const n=e.attempt+1;this.queue.set(t,{...e,attempt:n}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${e.request.params?.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Mm,()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(mb);this.checkQueue()}),this.relayer.on(ub,e=>{this.removeRequestFromQueue(e.id.toString())})}},Hv=class{constructor(){this.map=new Map,this.set=(e,t)=>{const n=this.get(e);this.exists(e,t)||this.map.set(e,[...n,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,t))return;const r=n.filter(e=>e!==t);r.length?this.map.set(e,r):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Vv=class extends Ey{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new Hv,this.events=new I.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.subscribeTimeout=U.toMiliseconds(U.ONE_MINUTE),this.initialSubscribeTimeout=U.toMiliseconds(15*U.ONE_SECOND),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const n=Zg(t),r={topic:e,relay:n,transportType:t?.transportType};t?.internal?.skipSubscribe||this.pending.set(e,r);const i=await this.rpcSubscribe(e,n,t);return"string"==typeof i&&(this.onSubscribe(i,r),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),i}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=e=>new Promise(t=>{t(this.topicMap.topics.includes(e))}),this.isKnownTopic=e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))}),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(Mm,async()=>{await this.checkPending()}),this.events.on(Sb,async e=>{const t=Sb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Pb,async e=>{const t=Pb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})},this.relayer=e,this.logger=wf(t,this.name),this.clientId=""}get context(){return yf(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 n=!1;try{n=this.getSubscription(e).topic===t}catch{}return n}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 n=this.topicMap.get(e);await Promise.all(n.map(async n=>await this.unsubscribeById(e,n,t)))}async unsubscribeById(e,t,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}});try{const r=Cf("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r);const i=Zg(n);await this.restartToComplete({topic:e,id:t,relay:i}),await this.rpcUnsubscribe(e,t,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,n){const r=await this.getSubscriptionId(e);if(n?.internal?.skipSubscribe)return r;(!n||n?.transportType===Ab.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const i={method:Kg(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});const s=n?.internal?.throwOnFailedPublish;try{if(n?.transportType===Ab.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(i).catch(e=>this.logger.warn(e))},U.toMiliseconds(U.ONE_SECOND)),r;const t=new Promise(async t=>{const n=r=>{r.topic===e&&(this.events.removeListener(Sb,n),t(r.id))};this.events.on(Sb,n);try{const r=await Ff(new Promise((e,t)=>{this.relayer.request(i).catch(e=>{this.logger.warn(e,e?.message),t(e)}).then(e)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Sb,n),t(r)}catch{}}),o=await Ff(t,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&s)throw new Error(`Subscribing to ${e} failed, please try again`);return o?r:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(mb),s)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t={method:Kg(e[0].relay.protocol).batchSubscribe,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await Ff(new Promise((e,n)=>{this.relayer.request(t).then(e).catch(e=>{this.logger.warn(e),n(e)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(mb),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:Kg(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map(e=>e.topic)}};let n;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{n=await await Ff(new Promise((e,n)=>{this.relayer.request(t).catch(e=>{this.logger.warn(e),n(e)}).then(e)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(mb)}return n}rpcUnsubscribe(e,t,n){const r={method:Kg(n.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,{...t,id:e}),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,{...e}),this.pending.delete(e.topic)})}async onUnsubscribe(e,t,n){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,n),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,{...t}),this.topicMap.set(t.topic,e),this.events.emit(Sb,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:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Pb,{...n,reason:t})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Nb)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<t;n++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit(_b)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(e=>e.topic===this.subscriptions.get(e.id)?.topic)){const{message:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e))return this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),void e.forEach(e=>{this.pending.set(e.topic,e)});this.onBatchSubscribe(await Promise.all(e.map(async e=>({...e,id:await this.getSubscriptionId(e.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 function(e){return new Promise(t=>setTimeout(t,e))}(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}=If("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 Mg(e+await this.getClientId())}},Fv=class extends by{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new I.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=U.toMiliseconds(15*U.ONE_SECOND),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=U.toMiliseconds(2*U.ONE_SECOND),this.stalledRestartMaxInterval=U.toMiliseconds(U.THIRTY_SECONDS),this.request=async e=>{this.logger.debug("Publishing Request Payload");const t=e.id||qy().toString();await this.toEstablishConnection();try{this.logger.trace({id:t,method:e.method,topic:e.params?.topic},"relayer.request - publishing...");const n=`${t}:${e.params?.tag||""}`;this.requestsInFlight.push(n);const r=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter(e=>e!==n),r}catch(e){throw this.logger.debug(`Failed to Publish Request: ${t}`),e}},this.resetPingTimeout=()=>{Of()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(e){this.logger.warn(e,e?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=e=>{this.onProviderPayload(e),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(pb)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(gb,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(e=>this.logger.warn(e))},this.registerProviderListeners=()=>{this.provider.on(wb,this.onPayloadHandler),this.provider.on(bb,this.onConnectHandler),this.provider.on(vb,this.onDisconnectHandler),this.provider.on(Eb,this.onProviderErrorHandler)},this.core=t.core,this.logger=Om({logger:t.logger??"error",name:this.name}),this.messages=new jv(this.logger,t.core),this.subscriber=new Vv(this,this.logger),this.publisher=new zv(this,this.logger),this.projectId=t.projectId,this.relayUrl=t.relayUrl||db,$f()&&typeof e<"u"&&typeof e?.Platform<"u"&&"android"===e?.Platform.OS?this.packageName=Mf():$f()&&typeof e<"u"&&typeof e?.Platform<"u"&&"ios"===e?.Platform.OS&&(this.bundleId=Mf()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return yf(this.logger)}get connected(){return 1===this.provider?.connection?.socket?.readyState}get connecting(){return 0===this.provider?.connection?.socket?.readyState||void 0!==this.connectPromise}async publish(e,t,n){this.isInitialized(),await this.publisher.publish(e,t,n),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Ab.relay},Ib)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){this.isInitialized(),(!t?.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const n=t?.internal?.throwOnFailedPublish??!0;let r,i=this.subscriber.topicMap.get(e)?.[0]||"";const s=t=>{t.topic===e&&(this.subscriber.off(Sb,s),r())};return await Promise.all([new Promise(e=>{r=e,this.subscriber.on(Sb,s)}),new Promise((r,s)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:n},...t}).then(e=>{i=e||i,r()}).catch(e=>{n?s(e):r()})})]),i}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 Ff(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(e){if(this.subscriber.hasAnyTopics){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=this.connect(e).finally(()=>{this.connectPromise=void 0}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.info("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await Im())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort((e,t)=>e.publishedAt-t.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:n}=e;if(!t.sessionExists){const e={topic:n,expiry:Zf(U.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,e)}this.events.emit(hb,e),await this.recordMessageEvent(e,kb)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let t=1;try{for(;t<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise((e,t)=>{const n=()=>{t(new Error("Connection interrupted while trying to connect"))};this.provider.once(vb,n),Ff(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>e()).catch(t).finally(()=>{this.provider.off(vb,n),clearTimeout(this.reconnectTimeout)})}),await new Promise((e,t)=>{const n=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(vb,n),this.subscriber.start().then(e).catch(t).finally(()=>{this.provider.off(vb,n)})}),this.hasExperiencedNetworkDisruption=!1}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(e=>setTimeout(e,U.toMiliseconds(1*t))),t++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(Of())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await Ff(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new aw(new uw(Df({sdkVersion:xb,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:n,message:r}=e;await this.messages.set(n,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:n}=e;if(!n||0===n.length)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),rw(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:n,message:r,publishedAt:i,attestation:s}=t.data,o={topic:n,message:r,publishedAt:i,transportType:Ab.relay,attestation:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:t.id,...o}),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else iw(e)&&this.events.emit(ub,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,kb),this.events.emit(hb,e))}async acknowledgePayload(e){const t=Zy(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(wb,this.onPayloadHandler),this.provider.off(bb,this.onConnectHandler),this.provider.off(vb,this.onDisconnectHandler),this.provider.off(Eb,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Im();Cm(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(e=>this.logger.error(e,e?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Mm,async()=>{if(!(this.transportExplicitlyClosed||this.connected||Rf()&&ge()&&"visible"!==ge()?.visibilityState))try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}),this.events.on(mb,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const e=0===this.stalledRestartBackoff?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${e?` in ${e}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(e){this.logger.error(e,e?.message)}finally{this.stalledRestartInProgress=!1}},e)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(fb),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed)return void(this.reconnectInProgress=!1);this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},U.toMiliseconds(.1))}}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}},qv=class extends vy{constructor(e,t,n,r=ib,i=void 0){super(e,t,n,r),this.core=e,this.logger=t,this.name=n,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{this.getKey&&null!==e&&!lm(e)?this.map.set(this.getKey(e),e):function(e){return e?.proposer?.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)}),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(n=>Qw(t[n],e[n]))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const n={...this.getData(e),...t};this.map.set(e,n),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())},this.logger=wf(t,this.name),this.storagePrefix=r,this.getKey=i}get context(){return yf(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:t}=If("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}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:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wv=class{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new C,this.initialized=!1,this.storagePrefix=ib,this.ignoredPayloadTypes=[1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async e=>{this.isInitialized();const t=Rg(),n=await this.core.crypto.setSymKey(t),r=Zf(U.FIVE_MINUTES),i={protocol:"irn"},s={topic:n,expiry:r,relay:i,active:!1,methods:e?.methods},o=Xg({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:t,relay:i,expiryTimestamp:r,methods:e?.methods});return this.events.emit(Ob,s),this.core.expirer.set(n,r),await this.pairings.set(n,s),await this.core.relayer.subscribe(n,{transportType:e?.transportType,internal:e?.internal}),{topic:n,uri:o}},this.pair=async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[Kb]}});this.isValidPair(e,t);const{topic:n,symKey:r,relay:i,expiryTimestamp:s,methods:o}=Yg(e.uri);let a;if(t.props.properties.topic=n,t.addTrace(Gb),t.addTrace(Yb),this.pairings.keys.includes(n)){if(a=this.pairings.get(n),t.addTrace(ev),a.active)throw t.setError(ov),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);t.addTrace(tv)}const c=s||Zf(U.FIVE_MINUTES),l={topic:n,relay:i,expiry:c,active:!1,methods:o};this.core.expirer.set(n,c),await this.pairings.set(n,l),t.addTrace(Jb),e.activatePairing&&await this.activate({topic:n}),this.events.emit(Ob,l),t.addTrace(nv),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(r,n),t.addTrace(Qb);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(iv)}try{await this.core.relayer.subscribe(n,{relay:i})}catch(e){throw t.setError(av),e}return t.addTrace(Xb),l},this.activate=async({topic:e})=>{this.isInitialized();const t=Zf(U.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:n,resolve:r,reject:i}=Vf();this.events.once(Gf("pairing_ping",e),({error:e})=>{e?i(e):r()}),await n()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Cf("USER_DISCONNECTED")),await this.deletePairing(t))},this.formatUriFromPairing=e=>{this.isInitialized();const{topic:t,relay:n,expiry:r,methods:i}=e,s=this.core.crypto.keychain.get(t);return Xg({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:s,relay:n,expiryTimestamp:r,methods:i})},this.sendRequest=async(e,t,n)=>{const r=Wy(t,n),i=await this.core.crypto.encode(e,r),s=Tb[t].req;return this.core.history.set(e,r),this.core.relayer.publish(e,i,s),r.id},this.sendResult=async(e,t,n)=>{const r=Zy(e,n),i=await this.core.crypto.encode(t,r),s=(await this.core.history.get(t,e)).request.method,o=Tb[s].res;await this.core.relayer.publish(t,i,o),await this.core.history.resolve(r)},this.sendError=async(e,t,n)=>{const r=Ky(e,n),i=await this.core.crypto.encode(t,r),s=(await this.core.history.get(t,e)).request.method,o=Tb[s]?Tb[s].res:Tb.unregistered_method.res;await this.core.relayer.publish(t,i,o),await this.core.history.resolve(r)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Cf("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter(e=>Kf(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))},this.onRelayEventRequest=async e=>{const{topic:t,payload:n}=e;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,n);default:return await this.onUnknownRpcMethodRequest(t,n)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:n}=e,r=(await this.core.history.get(t,n.id)).request.method;return"wc_pairingPing"===r?this.onPairingPingResponse(t,n):this.onUnknownRpcMethodResponse(r)},this.onPairingPingRequest=async(e,t)=>{const{id:n}=t;try{this.isValidPing({topic:e}),await this.sendResult(n,e,!0),this.events.emit(Bb,{id:n,topic:e})}catch(t){await this.sendError(n,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:n}=t;setTimeout(()=>{sw(t)?this.events.emit(Gf("pairing_ping",n),{}):ow(t)&&this.events.emit(Gf("pairing_ping",n),{error:t.error})},500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:n}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(Rb,{id:n,topic:e})}catch(t){await this.sendError(n,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:n,method:r}=t;try{if(this.registeredMethods.includes(r))return;const t=Cf("WC_METHOD_UNSUPPORTED",r);await this.sendError(n,e,t),this.logger.error(t)}catch(t){await this.sendError(n,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Cf("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=(e,t)=>{if(!bm(e)){const{message:n}=If("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(sv),new Error(n)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(dm(e,!1))return!!t(e)||t(tg(e))}catch{}return!1}(e.uri)){const{message:n}=If("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(sv),new Error(n)}const n=Yg(e?.uri);if(!n?.relay?.protocol){const{message:e}=If("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(sv),new Error(e)}if(!n?.symKey){const{message:e}=If("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(sv),new Error(e)}if(n?.expiryTimestamp&&U.toMiliseconds(n?.expiryTimestamp)<Date.now()){t.setError(cv);const{message:e}=If("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}},this.isValidPing=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!dm(e,!1)){const{message:t}=If("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=If("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=If("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=wf(t,this.name),this.pairings=new qv(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yf(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(hb,async e=>{const{topic:t,message:n,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==Ab.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const e=await this.core.crypto.decode(t,n);rw(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):iw(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,n)}catch(e){this.logger.error(e)}})}registerExpirerEvents(){this.core.expirer.on(Hb,async e=>{const{topic:t}=Wf(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit($b,{topic:t}))})}},Zv=class extends my{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new I.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.records.set(e.id,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:n}),this.records.has(t.id))return;const r={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:n,expiry:Zf(U.THIRTY_DAYS)};this.records.set(r.id,r),this.persist(),this.events.emit(Mb,r)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response<"u"||(t.response=ow(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(Ub,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach(n=>{if(n.topic===e){if(typeof t<"u"&&n.id!==t)return;this.records.delete(n.id),this.events.emit(Lb,n)}}),this.persist()},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=wf(t,this.name)}get context(){return yf(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 n={topic:t.topic,request:Wy(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(n)}),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:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Db)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(Mb,e=>{const t=Mb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ub,e=>{const t=Ub;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Lb,e=>{const t=Lb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Mm,()=>{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(Lb,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Kv=class extends xy{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new I.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.expirations.set(e.target,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const n=this.formatTarget(e),r={target:n,expiry:t};this.expirations.set(n,r),this.checkExpiry(n,r),this.events.emit(jb,{target:n,expiration:r})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),n=this.getExpiration(t);this.expirations.delete(t),this.events.emit(zb,{target:t,expiration:n})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=wf(t,this.name)}get context(){return yf(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("string"==typeof e)return function(e){return qf("topic",e)}(e);if("number"==typeof e)return function(e){return qf("id",e)}(e);const{message:t}=If("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(Vb)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:n}=t;U.toMiliseconds(n)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Hb,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Mm,()=>this.checkExpirations()),this.events.on(jb,e=>{const t=jb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Hb,e=>{const t=Hb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(zb,e=>{const t=zb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Gv=class extends Ay{constructor(e,t,n){super(e,t,n),this.core=e,this.logger=t,this.store=n,this.name="verify-api",this.verifyUrlV3=Wb,this.storagePrefix=ib,this.version=2,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds(this.publicKey?.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async e=>{if(!Rf()||this.isDevEnv)return;const t=window.location.origin,{id:n,decryptedId:r}=e,i=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${n}&decryptedId=${r}`;try{const e=ge(),t=this.startAbortTimer(5*U.ONE_SECOND),r=await new Promise((r,s)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),s("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=i,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=i=>{if(i.data&&"string"==typeof i.data)try{const s=JSON.parse(i.data);if("verify_attestation"===s.type){if(Lu(s.attestation).payload.id!==n)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),r(null===s.attestation?"":s.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})});return this.logger.debug(r,"jwt attestation"),r}catch(e){this.logger.warn(e)}return""},this.resolve=async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:n,encryptedId:r}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if(Lu(t).payload.id!==r)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!n)return;const i=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(n,i)},this.fetchAttestation=async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const n=this.startAbortTimer(5*U.ONE_SECOND),r=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(n),200===r.status?await r.json():void 0},this.getVerifyUrl=e=>{let t=e||qb;return Zb.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${qb}`),t=qb),t},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(U.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}},this.persistPublicKey=async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const n=await this.fetchAndPersistPublicKey();try{if(n)return this.validateAttestation(e,n)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))});const e=await this.fetchPromise;return this.fetchPromise=void 0,e},this.validateAttestation=(e,t)=>{const n=Wg(e,t.publicKey),r={hasExpired:U.toMiliseconds(n.exp)<Date.now(),payload:n};if(r.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:r.payload.origin,isScam:r.payload.isScam,isVerified:r.payload.isVerified}},this.logger=wf(t,this.name),this.abortController=new AbortController,this.isDevEnv=eg(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return yf(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}},Yv=class extends ky{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context="echo",this.registerDeviceToken=async e=>{const{clientId:t,token:n,notificationType:r,enableEncrypted:i=!1}=e,s=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:r,token:n,always_raw:i})})},this.logger=wf(t,this.context)}},Jv=class extends Iy{constructor(e,t,n=!0){super(e,t,n),this.core=e,this.logger=t,this.context="event-client",this.storagePrefix=ib,this.storageVersion=.1,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!eg())try{const e={eventId:Xf(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Lf(this.core.relayer.protocol,this.core.relayer.version,xb)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}},this.createEvent=e=>{const{event:t="ERROR",type:n="",properties:{topic:r,trace:i}}=e,s=Xf(),o=this.core.projectId||"",a={eventId:s,timestamp:Date.now(),props:{event:t,type:n,properties:{topic:r,trace:i}},bundleId:o,domain:this.getAppDomain(),...this.setMethods(s)};return this.telemetryEnabled&&(this.events.set(s,a),this.shouldPersist=!0),a},this.getEvent=e=>{const{eventId:t,topic:n}=e;if(t)return this.events.get(t);const r=Array.from(this.events.values()).find(e=>e.props.properties.topic===n);return r?{...r,...this.setMethods(r.eventId)}:void 0},this.deleteEvent=e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Mm,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})},this.setMethods=e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}),this.addTrace=(e,t)=>{const n=this.events.get(e);n&&(n.props.properties.trace.push(t),this.events.set(e,n),this.shouldPersist=!0)},this.setError=(e,t)=>{const n=this.events.get(e);n&&(n.props.type=t,n.timestamp=Date.now(),this.events.set(e,n),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach(e=>{this.events.set(e.eventId,{...e,...this.setMethods(e.eventId)})})}catch(e){this.logger.warn(e)}},this.submit=async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,n]of this.events)n.props.type&&e.push(n);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}},this.sendEvent=async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${xb}${t}`,{method:"POST",body:JSON.stringify(e)})},this.getAppDomain=()=>Uf().url,this.logger=wf(t,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}};const Qv=class e extends gy{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=rb,this.events=new I.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.dispatchEnvelope=({topic:e,message:t,sessionExists:n})=>{if(!e||!t)return;const r={topic:e,message:t,publishedAt:Date.now(),transportType:Ab.link_mode};this.relayer.onLinkMessageEvent(r,{sessionExists:n})};const t=this.getGlobalCore(e?.customStoragePrefix);if(t)try{return this.customStoragePrefix=t.customStoragePrefix,this.logger=t.logger,this.heartbeat=t.heartbeat,this.crypto=t.crypto,this.history=t.history,this.expirer=t.expirer,this.storage=t.storage,this.relayer=t.relayer,this.pairing=t.pairing,this.verify=t.verify,this.echoClient=t.echoClient,this.linkModeSupportedApps=t.linkModeSupportedApps,this.eventClient=t.eventClient,this.initialized=t.initialized,this.logChunkController=t.logChunkController,t}catch(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||db,this.customStoragePrefix=e?.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=mf({level:"string"==typeof e?.logger&&e.logger?e.logger:sb,name:rb}),{logger:r,chunkLoggerController:i}=bf({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=i,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=wf(r,this.name),this.heartbeat=new Um,this.crypto=new Dv(this,this.logger,e?.keychain),this.history=new Zv(this,this.logger),this.expirer=new Kv(this,this.logger),this.storage=e?.storage?e.storage:new fy({...ob,...e?.storageOptions}),this.relayer=new Fv({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Wv(this,this.logger),this.verify=new Gv(this,this.logger,this.storage),this.echoClient=new Yv(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Jv(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new e(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem("WALLETCONNECT_CLIENT_ID",r),n}get context(){return yf(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Cb,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(Cb)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,n=`${t}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e.opts?.customStoragePrefix||""}`;globalThis[t]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&"true"===process.env.DISABLE_GLOBAL_CORE}catch{return!0}}},Xv="client",eE=`wc@2:${Xv}:`,tE=Xv,nE="error",rE="WALLETCONNECT_DEEPLINK_CHOICE",iE="Proposal expired",sE=U.SEVEN_DAYS,oE={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:3*U.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:3*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}}},aE={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},cE="IDLE",lE="ACTIVE",dE={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},hE=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],uE="wc@1.5:auth:",pE=`${uE}:PUB_KEY`;let fE=class extends Sy{constructor(t){super(t),this.name="engine",this.events=new C,this.initialized=!1,this.requestQueue={state:cE,queue:[]},this.sessionRequestQueue={state:cE,queue:[]},this.emittedSessionRequests=new ng({limit:500}),this.requestQueueDelay=U.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(oE)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t={...e,requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}};await this.isValidConnect(t),t.optionalNamespaces=function(e,t){const n=sm(e),r=sm(t),i={},s=Object.keys(n).concat(Object.keys(r));for(const e of s)i[e]={chains:Yf(n[e]?.chains,r[e]?.chains),methods:Yf(n[e]?.methods,r[e]?.methods),events:Yf(n[e]?.events,r[e]?.events)};return i}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:s,scopedProperties:o,relays:a,authentication:c,walletPay:l}=t,d=c?.[0]?.ttl||oE.wc_sessionPropose.req.ttl||U.FIVE_MINUTES;this.validateRequestExpiry(d);let h,u=n,p=!1;try{if(u){const e=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),p=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),e}if(!u||!p){const{topic:e,uri:t}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=e,h=t}if(!u){const{message:e}=If("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(e)}const f=await this.client.core.crypto.generateKeyPair(),g=Zf(d),m={requiredNamespaces:r,optionalNamespaces:i,relays:a??[{protocol:"irn"}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u,...s&&{sessionProperties:s},...o&&{scopedProperties:o},id:Fy(),...(c||l)&&{requests:{authentication:c?.map(e=>{const{domain:t,chains:n,nonce:r,uri:i,exp:s,nbf:o,type:a,statement:c,requestId:l,resources:d,signatureTypes:h}=e;return{domain:t,chains:n,nonce:r,type:a??"caip122",aud:i,version:"1",iat:(new Date).toISOString(),exp:s,nbf:o,statement:c,requestId:l,resources:d,signatureTypes:h}}),walletPay:l}}},y=Gf("session_connect",m.id),{reject:w,resolve:b,done:v}=Vf(d,iE),E=({id:e})=>{if(e===m.id){this.client.events.off("proposal_expire",E);const e=this.pendingSessions.get(m.id);if(e){const{sessionTopic:t,publicKey:n}=e;Promise.all([this.client.core.relayer.unsubscribe(t),this.client.core.crypto.keychain.has(t)?this.client.core.crypto.deleteSymKey(t):Promise.resolve(),this.client.core.crypto.keychain.has(n)?this.client.core.crypto.deleteKeyPair(n):Promise.resolve()]).catch(e=>this.client.logger.warn(e))}this.pendingSessions.delete(m.id),this.events.emit(y,{error:{message:iE,code:0}})}};return this.client.events.on("proposal_expire",E),this.events.once(y,({error:e,session:t})=>{this.client.events.off("proposal_expire",E),e?w(e):t&&b(t)}),await this.setProposal(m.id,m),await this.sendProposeSession({proposal:m,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:m.id}}}).catch(e=>{throw this.deleteProposal(m.id),e}),{uri:h,approval:v}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}},this.approve=async e=>{const t=this.client.core.eventClient.createEvent({properties:{topic:e?.id?.toString(),trace:[dv]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw t.setError(bv),e}try{await this.isValidProposalId(e?.id)}catch(n){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),t.setError(Av),n}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),t.setError(xv),e}const{id:n,relayProtocol:r,namespaces:i,sessionProperties:s,scopedProperties:o,sessionConfig:a,proposalRequestsResponses:c}=e,l=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:t.eventId});const{pairingTopic:d,proposer:h,requiredNamespaces:u,optionalNamespaces:p}=l;let f=this.client.core.eventClient?.getEvent({topic:d});f||(f=this.client.core.eventClient?.createEvent({type:dv,properties:{topic:d,trace:[dv,hv]}}));const g=await this.client.core.crypto.generateKeyPair(),m=h.publicKey,y=await this.client.core.crypto.generateSharedKey(g,m),w={relay:{protocol:r??"irn"},namespaces:i,controller:{publicKey:g,metadata:this.client.metadata},expiry:Zf(sE),...s&&{sessionProperties:s},...o&&{scopedProperties:o},...a&&{sessionConfig:a},proposalRequestsResponses:c},b=Ab.relay;f.addTrace(uv);try{await this.client.core.relayer.subscribe(y,{transportType:b,internal:{skipSubscribe:!0}})}catch(e){throw f.setError(Ev),e}f.addTrace(pv);const v={...w,topic:y,requiredNamespaces:u,optionalNamespaces:p,pairingTopic:d,acknowledged:!1,self:w.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:g,transportType:Ab.relay,authentication:c?.authentication,walletPayResult:c?.walletPay};await this.client.session.set(y,v),f.addTrace(gv);try{await this.sendApproveSession({sessionTopic:y,proposal:l,pairingProposalResponse:{relay:{protocol:r??"irn"},responderPublicKey:g},sessionSettleRequest:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:n,...this.getTVFApproveParams(v)}}}),f.addTrace(fv)}catch(e){throw this.client.logger.error(e),this.client.session.delete(y,Cf("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(y),e}return this.client.core.eventClient.deleteEvent({eventId:f.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:h.metadata}),await this.deleteProposal(n),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(y,Zf(sE)),{topic:y,acknowledged:()=>Promise.resolve(this.client.session.get(y))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:n}=e;let r;try{r=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}r&&await this.sendError({id:t,topic:r,error:n,rpcOpts:oE.wc_sessionPropose.reject}),await this.deleteProposal(t)},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:n}=e,{done:r,resolve:i,reject:s}=Vf(U.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),o=Fy(),a=qy().toString(),c=this.client.session.get(t).namespaces;return this.events.once(Gf("session_update",o),({error:e})=>{e?s(e):i()}),await this.client.session.update(t,{namespaces:n}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:a}).catch(e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:c}),s(e)}),{acknowledged:r}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,n=Fy(),{done:r,resolve:i,reject:s}=Vf(U.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Gf("session_extend",n),({error:e})=>{e?s(e):i()}),await this.setExpiry(t,Zf(sE)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(e=>{s(e)}),{acknowledged:r}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:n,topic:r,expiry:i=oE.wc_sessionRequest.req.ttl}=e,s=this.client.session.get(r);s?.transportType===Ab.relay&&await this.confirmOnlineStateOrThrow();const o=Fy(),a=qy().toString(),{done:c,resolve:l,reject:d}=Vf(i,"Request expired. Please try again.");this.events.once(Gf("session_request",o),({error:e,result:t})=>{e?d(e):l(t)});const h="wc_sessionRequest",u=this.getAppLinkIfEnabled(s.peer.metadata,s.transportType);if(u)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:r,method:h,params:{request:{...n,expiryTimestamp:Zf(i)},chainId:t},expiry:i,throwOnFailedPublish:!0,appLink:u}).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:t,id:o}),await c();const p={request:{...n,expiryTimestamp:Zf(i)},chainId:t};return await Promise.all([new Promise(async e=>{await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:r,method:h,params:p,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(o,p)}).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:t,id:o}),e()}),new Promise(async e=>{if(!s.sessionConfig?.disableDeepLink){const e=await async function(e,t){let n="";try{if(Rf()&&(n=localStorage.getItem(t),n))return n;n=await e.getItem(t)}catch(e){console.error(e)}return n}(this.client.core.storage,rE);await Jf({id:o,topic:r,wcDeepLink:e})}e()}),c()]).then(e=>e[2])},this.respond=async e=>{this.isInitialized();const t=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||e?.response?.id?.toString(),trace:[mv]}});try{await this.isValidRespond(e)}catch(e){throw t.addTrace(e?.message),t.setError(kv),e}t.addTrace(yv);const{topic:n,response:r}=e,{id:i}=r,s=this.client.session.get(n);s.transportType===Ab.relay&&await this.confirmOnlineStateOrThrow();const o=this.getAppLinkIfEnabled(s.peer.metadata,s.transportType);try{t.addTrace(wv),sw(r)?await this.sendResult({id:i,topic:n,result:r.result,throwOnFailedPublish:!0,appLink:o}):ow(r)&&await this.sendError({id:i,topic:n,error:r.error,appLink:o}),this.cleanupAfterResponse(e)}catch(e){throw t.addTrace(e?.message),t.setError(Iv),e}},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=Fy(),n=qy().toString(),{done:r,resolve:i,reject:s}=Vf(U.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Gf("session_ping",e),({error:e})=>{e?s(e):i()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:n}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&(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:t}))},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:n,chainId:r}=e,i=qy().toString(),s=Fy();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:n,chainId:r},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:s})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Cf("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=If("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>function(e,t){const{requiredNamespaces:n}=t,r=Object.keys(e.namespaces),i=Object.keys(n);let s=!0;return!!jf(i,r)&&(r.forEach(t=>{const{accounts:r,methods:i,events:o}=e.namespaces[t],a=tm(r),c=n[t];jf(xf(t,c),a)&&jf(c.methods,i)&&jf(c.events,o)||(s=!1)}),s)}(t,e))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{this.isInitialized(),this.isValidAuthenticate(e);const n=t&&this.client.core.linkModeSupportedApps.includes(t)&&this.client.metadata.redirect?.linkMode,r=n?Ab.link_mode:Ab.relay;r===Ab.relay&&await this.confirmOnlineStateOrThrow();const{chains:i,statement:s="",uri:o,domain:a,nonce:c,type:l,exp:d,nbf:h,methods:u=[],expiry:p}=e,f=[...e.resources||[]],{topic:g,uri:m}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:g,uri:m}}),this.client.auth.authKeys.keys.includes(pE)){const{responseTopic:e,publicKey:t}=this.client.auth.authKeys.get(pE);e&&(await this.client.core.relayer.unsubscribe(e).catch(e=>this.client.logger.warn(e)),await this.client.auth.pairingTopics.delete(e,{message:"replaced",code:0}).catch(e=>this.client.logger.warn(e))),t&&this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteKeyPair(t)}const y=await this.client.core.crypto.generateKeyPair(),w=Bg(y);if(await Promise.all([this.client.auth.authKeys.set(pE,{responseTopic:w,publicKey:y}),this.client.auth.pairingTopics.set(w,{topic:w,pairingTopic:g})]),await this.client.core.relayer.subscribe(w,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${g}`),u.length>0){const{namespace:e}=vf(i[0]);let t=kg(e,"request",u);Pg(f)&&(t=Ig(t,f.pop())),f.push(t)}const b=p&&p>oE.wc_sessionAuthenticate.req.ttl?p:oE.wc_sessionAuthenticate.req.ttl,v={authPayload:{type:l??"caip122",chains:i,statement:s,aud:o,domain:a,version:"1",nonce:c,iat:(new Date).toISOString(),exp:d,nbf:h,resources:f},requester:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:Zf(b)},E={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:i,methods:[...new Set(["personal_sign",...u])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:g,proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:Zf(oE.wc_sessionPropose.req.ttl),id:Fy()},{done:x,resolve:A,reject:k}=Vf(b,"Request expired"),I=Fy(),C=Gf("session_connect",E.id),S=Gf("session_request",I),P=async({error:e,session:t})=>{this.events.off(S,N),e?k(e):t&&A({session:t})},N=async e=>{if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),e.error){const t=Cf("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(C,P),k(e.error.message))}await this.deleteProposal(E.id),this.events.off(C,P);const{cacaos:n,responder:i}=e.result,s=[],o=[];for(const e of n){await wg({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),k(Cf("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,n=Pg(t.resources),r=[mg(t.iss)],i=yg(t.iss);if(n){const e=Cg(n),t=Sg(n);s.push(...e),r.push(...t)}for(const e of r)o.push(`${e}:${i}`)}const a=await this.client.core.crypto.generateSharedKey(y,i.publicKey);let c;s.length>0&&(c={topic:a,acknowledged:!0,self:{publicKey:y,metadata:this.client.metadata},peer:i,controller:i.publicKey,expiry:Zf(sE),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:g,namespaces:om([...new Set(s)],[...new Set(o)]),transportType:r},await this.client.core.relayer.subscribe(a,{transportType:r}),await this.client.session.set(a,c),g&&await this.client.core.pairing.updateMetadata({topic:g,metadata:i.metadata}),c=this.client.session.get(a)),this.client.metadata.redirect?.linkMode&&i.metadata.redirect?.linkMode&&i.metadata.redirect?.universal&&t&&(this.client.core.addLinkModeSupportedApp(i.metadata.redirect.universal),this.client.session.update(a,{transportType:Ab.link_mode})),A({auths:n,session:c})};let _;this.events.once(C,P),this.events.once(S,N);try{if(n){const e=Wy("wc_sessionAuthenticate",v,I);this.client.core.history.set(g,e);const n=await this.client.core.crypto.encode("",e,{type:2,encoding:Og});_=em(t,g,n)}else await Promise.all([this.sendRequest({topic:g,method:"wc_sessionAuthenticate",params:v,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:g,method:"wc_sessionPropose",params:E,expiry:oE.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(e){throw this.events.off(C,P),this.events.off(S,N),e}return await this.setProposal(E.id,E),await this.setAuthRequest(I,{request:{...v,verifyContext:{}},pairingTopic:g,transportType:r}),{uri:_??m,response:x}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:n}=e,r=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Cv]}});try{this.isInitialized()}catch(e){throw r.setError($v),e}const i=this.getPendingAuthRequest(t);if(!i)throw r.setError(Uv),new Error(`Could not find pending auth request with id ${t}`);const s=i.transportType||Ab.relay;s===Ab.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Bg(o),l={type:1,receiverPublicKey:o,senderPublicKey:a},d=[],h=[];for(const e of n){if(!await wg({cacao:e,projectId:this.client.core.projectId})){r.setError(Rv);const e=Cf("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:l}),new Error(e.message)}r.addTrace(Pv);const{p:n}=e,i=Pg(n.resources),s=[mg(n.iss)],o=yg(n.iss);if(i){const e=Cg(i),t=Sg(i);d.push(...e),s.push(...t)}for(const e of s)h.push(`${e}:${o}`)}const u=await this.client.core.crypto.generateSharedKey(a,o);let p;if(r.addTrace(Sv),d?.length>0){p={topic:u,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:i.requester.metadata},controller:o,expiry:Zf(sE),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:om([...new Set(d)],[...new Set(h)]),transportType:s},r.addTrace(_v);try{await this.client.core.relayer.subscribe(u,{transportType:s})}catch(e){throw r.setError(Bv),e}r.addTrace(Tv),await this.client.session.set(u,p),r.addTrace(Nv),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}r.addTrace(Ov);try{await this.sendResult({topic:c,id:t,result:{cacaos:n,responder:{publicKey:a,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,s)})}catch(e){throw r.setError(Mv),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:r.eventId}),{session:p}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:n}=e,r=this.getPendingAuthRequest(t);if(!r)throw new Error(`Could not find pending auth request with id ${t}`);r.transportType===Ab.relay&&await this.confirmOnlineStateOrThrow();const i=r.requester.publicKey,s=await this.client.core.crypto.generateKeyPair(),o=Bg(i),a={type:1,receiverPublicKey:i,senderPublicKey:s};await this.sendError({id:t,topic:o,error:n,encodeOpts:a,rpcOpts:oE.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(r.requester.metadata,r.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.deleteProposal(t)},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:n}=e;return bg(t,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(n=>n.peerMetadata?.url&&n.peerMetadata?.url===e.peer.metadata.url&&n.topic&&n.topic!==t.topic);if(0===n.length)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(e=>this.client.core.pairing.disconnect({topic:e.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}},this.deleteSession=async e=>{const{topic:t,expirerHasDeleted:n=!1,emitEvent:r=!0,id:i=0}=e,{self:s}=this.client.session.get(t);await this.client.core.relayer.unsubscribe(t),await this.client.session.delete(t,Cf("USER_DISCONNECTED")),this.addToRecentlyDeleted(t,"session"),this.client.core.crypto.keychain.has(s.publicKey)&&await this.client.core.crypto.deleteKeyPair(s.publicKey),this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteSymKey(t),n||this.client.core.expirer.del(t),this.client.core.storage.removeItem(rE).catch(e=>this.client.logger.warn(e)),t===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=cE),await Promise.all(this.getPendingSessionRequests().filter(e=>e.topic===t).map(e=>this.deletePendingSessionRequest(e.id,Cf("USER_DISCONNECTED")))),r&&this.client.events.emit("session_delete",{id:i,topic:t})},this.deleteProposal=async(e,t)=>{if(t)try{const t=this.client.proposal.get(e);this.client.core.eventClient.getEvent({topic:t.pairingTopic})?.setError(vv)}catch{}await Promise.all([this.client.proposal.delete(e,Cf("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")},this.deletePendingSessionRequest=async(e,t,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),n?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(t=>t.id!==e),n&&(this.sessionRequestQueue.state=cE,this.client.events.emit("session_request_expire",{id:e}))},this.deletePendingAuthRequest=async(e,t,n=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),n?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,Zf(oE.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:n,pairingTopic:r,transportType:i=Ab.relay}=t;this.client.core.expirer.set(e,n.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:e,pairingTopic:r,verifyContext:n.verifyContext,transportType:i})},this.setPendingSessionRequest=async e=>{const{id:t,topic:n,params:r,verifyContext:i}=e,s=r.request.expiryTimestamp||Zf(oE.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,s),await this.client.pendingRequest.set(t,{id:t,topic:n,params:r,verifyContext:i})},this.sendRequest=async t=>{const{topic:n,method:r,params:i,expiry:s,relayRpcId:o,clientRpcId:a,throwOnFailedPublish:c,appLink:l,tvf:d,publishOpts:h={}}=t,u=Wy(r,i,a);let p;const f=!!l;try{const e=f?Og:Tg;p=await this.client.core.crypto.encode(n,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),e}let g;if(hE.includes(r)){const e=Mg(JSON.stringify(u)),t=Mg(p);g=await this.client.core.verify.register({id:t,decryptedId:e})}const m={...oE[r].req,...h};if(m.attestation=g,s&&(m.ttl=s),o&&(m.id=o),this.client.core.history.set(n,u),f){const t=em(l,n,p);await e.Linking.openURL(t,this.client.name)}else m.tvf={...d,correlationId:u.id},c?(m.internal={...m.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(n,p,m)):this.client.core.relayer.publish(n,p,m).catch(e=>this.client.logger.error(e));return u.id},this.sendProposeSession=async e=>{const{proposal:t,publishOpts:n}=e,r=Wy("wc_sessionPropose",t,t.id);this.client.core.history.set(t.pairingTopic,r);const i=await this.client.core.crypto.encode(t.pairingTopic,r,{encoding:Tg}),s=Mg(JSON.stringify(r)),o=Mg(i),a=await this.client.core.verify.register({id:o,decryptedId:s});await this.client.core.relayer.publishCustom({payload:{pairingTopic:t.pairingTopic,sessionProposal:i},opts:{...n,publishMethod:"wc_proposeSession",attestation:a}})},this.sendApproveSession=async e=>{const{sessionTopic:t,pairingProposalResponse:n,proposal:r,sessionSettleRequest:i,publishOpts:s}=e,o=Zy(r.id,n),a=await this.client.core.crypto.encode(r.pairingTopic,o,{encoding:Tg}),c=Wy("wc_sessionSettle",i,s?.id),l=await this.client.core.crypto.encode(t,c,{encoding:Tg});this.client.core.history.set(t,c),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:r.pairingTopic,sessionProposalResponse:a,sessionSettlementRequest:l},opts:{...s,publishMethod:"wc_approveSession"}})},this.sendResult=async t=>{const{id:n,topic:r,result:i,throwOnFailedPublish:s,encodeOpts:o,appLink:a}=t,c=Zy(n,i);let l;const d=a&&typeof e?.Linking<"u";try{const e=d?Og:Tg;l=await this.client.core.crypto.encode(r,c,{...o||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),e}let h,u;try{h=await this.client.core.history.get(r,n);const e=h.request;try{u=this.getTVFParams(n,e.params,i)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),e}if(d){const t=em(a,r,l);await e.Linking.openURL(t,this.client.name)}else{const e=h.request.method,t=oE[e].res;t.tvf={...u,correlationId:n},s?(t.internal={...t.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(r,l,t)):this.client.core.relayer.publish(r,l,t).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(c)},this.sendError=async t=>{const{id:n,topic:r,error:i,encodeOpts:s,rpcOpts:o,appLink:a}=t,c=Ky(n,i);let l;const d=a&&typeof e?.Linking<"u";try{const e=d?Og:Tg;l=await this.client.core.crypto.encode(r,c,{...s||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),e}let h;try{h=await this.client.core.history.get(r,n)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),e}if(d){const t=em(a,r,l);await e.Linking.openURL(t,this.client.name)}else{const e=h.request.method,t=o||oE[e].res;this.client.core.relayer.publish(r,l,t)}await this.client.core.history.resolve(c)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach(t=>{let n=!1;Kf(t.expiry)&&(n=!0),this.client.core.crypto.keychain.has(t.topic)||(n=!0),n&&e.push(t.topic)}),this.client.proposal.getAll().forEach(e=>{Kf(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])},this.onProviderMessageEvent=async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==lE){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=lE;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=cE}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=async e=>{const{topic:t,payload:n,attestation:r,transportType:i,encryptedId:s}=e,o=n.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:n,attestation:r,encryptedId:s});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,n);case"wc_sessionPing":return await this.onSessionPingRequest(t,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:n,attestation:r,encryptedId:s,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(t,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:n,attestation:r,encryptedId:s,transportType:i});default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:n,transportType:r}=e,i=(await this.client.core.history.get(t,n.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(t,n,r);case"wc_sessionSettle":return this.onSessionSettleResponse(t,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,n);case"wc_sessionExtend":return this.onSessionExtendResponse(t,n);case"wc_sessionPing":return this.onSessionPingResponse(t,n);case"wc_sessionRequest":return this.onSessionRequestResponse(t,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,n);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:n}=If("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:n}=e,r=this.expectedPairingMethodMap.get(t);return!(!r||r.includes(n))&&!!(r.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:n,attestation:r,encryptedId:i}=e,{params:s,id:o}=n;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(lv)),this.isValidConnect({...n.params});const a={id:o,pairingTopic:t,expiryTimestamp:s.expiryTimestamp||Zf(oE.wc_sessionPropose.req.ttl),attestation:r,encryptedId:i,...s};await this.setProposal(o,a);const c=await this.getVerifyContext({attestationId:r,hash:Mg(JSON.stringify(n)),encryptedId:i,metadata:a.proposer.metadata});e?.addTrace(rv),this.client.events.emit("session_proposal",{id:o,params:a,verifyContext:c})}catch(e){await this.sendError({id:o,topic:t,error:e,rpcOpts:oE.wc_sessionPropose.autoReject}),this.client.logger.error(e)}},this.onSessionProposeResponse=async(e,t,n)=>{const{id:r}=t;if(sw(t)){const{result:i}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});const s=this.client.proposal.get(r);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:s});const o=s.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(r,{sessionTopic:c,pairingTopic:e,proposalId:r,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if(ow(t)){await this.deleteProposal(r);const e=Gf("session_connect",r);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:n,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:n,controller:i,expiry:s,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:l,proposalRequestsResponses:d}=t.params,h=[...this.pendingSessions.values()].find(t=>t.sessionTopic===e);if(!h)return this.client.logger.error(`Pending session not found for topic ${e}`);const u=this.client.proposal.get(h.proposalId),p={topic:e,relay:n,expiry:s,namespaces:o,acknowledged:!0,pairingTopic:h.pairingTopic,requiredNamespaces:u.requiredNamespaces,optionalNamespaces:u.optionalNamespaces,controller:i.publicKey,self:{publicKey:h.publicKey,metadata:this.client.metadata},peer:{publicKey:i.publicKey,metadata:i.metadata},...a&&{sessionProperties:a},...c&&{scopedProperties:c},...l&&{sessionConfig:l},transportType:Ab.relay,authentication:d?.authentication,walletPayResult:d?.walletPay};await this.client.session.set(p.topic,p),await this.setExpiry(p.topic,p.expiry),await this.client.core.pairing.updateMetadata({topic:h.pairingTopic,metadata:p.peer.metadata}),this.pendingSessions.delete(h.proposalId),this.deleteProposal(h.proposalId,!1),this.cleanupDuplicatePairings(p),await this.sendResult({id:t.id,topic:e,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:p}),this.events.emit(Gf("session_connect",h.proposalId),{session:p})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionSettleResponse=async(e,t)=>{const{id:n}=t;sw(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Gf("session_approve",n),{})):ow(t)&&(await this.deleteSession({topic:e,emitEvent:!1}),this.events.emit(Gf("session_approve",n),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:n,id:r}=t;try{const t=`${e}_session_update`,i=Pm.get(t);if(i&&this.isRequestOutOfSync(i,r))return this.client.logger.warn(`Discarding out of sync request - ${r}`),void this.sendError({id:r,topic:e,error:Cf("INVALID_UPDATE_REQUEST")});this.isValidUpdate({topic:e,...n});try{Pm.set(t,r),await this.client.session.update(e,{namespaces:n.namespaces}),await this.sendResult({id:r,topic:e,result:!0})}catch(e){throw Pm.delete(t),e}this.client.events.emit("session_update",{id:r,topic:e,params:n})}catch(t){await this.sendError({id:r,topic:e,error:t}),this.client.logger.error(t)}},this.isRequestOutOfSync=(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3),this.onSessionUpdateResponse=(e,t)=>{const{id:n}=t,r=Gf("session_update",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);sw(t)?this.events.emit(Gf("session_update",n),{}):ow(t)&&this.events.emit(Gf("session_update",n),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:n}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Zf(sE)),await this.sendResult({id:n,topic:e,result:!0}),this.client.events.emit("session_extend",{id:n,topic:e})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionExtendResponse=(e,t)=>{const{id:n}=t,r=Gf("session_extend",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);sw(t)?this.events.emit(Gf("session_extend",n),{}):ow(t)&&this.events.emit(Gf("session_extend",n),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:n}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:n,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:e})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionPingResponse=(e,t)=>{const{id:n}=t,r=Gf("session_ping",n);setTimeout(()=>{if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners 2176`);sw(t)?this.events.emit(Gf("session_ping",n),{}):ow(t)&&this.events.emit(Gf("session_ping",n),{error:t.error})},500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:n}=t;try{await this.isValidDisconnect({topic:e,reason:t.params}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Cf("USER_DISCONNECTED")}),await this.deleteSession({topic:e,id:n})}catch(e){this.client.logger.error(e)}},this.onSessionRequest=async e=>{const{topic:t,payload:n,attestation:r,encryptedId:i,transportType:s}=e,{id:o,params:a}=n;try{await this.isValidRequest({topic:t,...a});const e=this.client.session.get(t),n={id:o,topic:t,params:a,verifyContext:await this.getVerifyContext({attestationId:r,hash:Mg(JSON.stringify(Wy("wc_sessionRequest",a,o))),encryptedId:i,metadata:e.peer.metadata,transportType:s})};await this.setPendingSessionRequest(n),s===Ab.link_mode&&e.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(n):(this.addSessionRequestToSessionRequestQueue(n),this.processSessionRequestQueue())}catch(e){await this.sendError({id:o,topic:t,error:e}),this.client.logger.error(e)}},this.onSessionRequestResponse=(e,t)=>{const{id:n}=t,r=Gf("session_request",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);sw(t)?this.events.emit(Gf("session_request",n),{result:t.result}):ow(t)&&this.events.emit(Gf("session_request",n),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:n,params:r}=t;try{const t=`${e}_session_event_${r.event.name}`,i=Pm.get(t);if(i&&this.isRequestOutOfSync(i,n))return void this.client.logger.info(`Discarding out of sync request - ${n}`);this.isValidEmit({topic:e,...r}),this.client.events.emit("session_event",{id:n,topic:e,params:r}),Pm.set(t,n)}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:n}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),sw(t)?this.events.emit(Gf("session_request",n),{result:t.result}):ow(t)&&this.events.emit(Gf("session_request",n),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{const{topic:t,payload:n,attestation:r,encryptedId:i,transportType:s}=e;try{const{requester:e,authPayload:o,expiryTimestamp:a}=n.params,c=await this.getVerifyContext({attestationId:r,hash:Mg(JSON.stringify(n)),encryptedId:i,metadata:e.metadata,transportType:s}),l={requester:e,pairingTopic:t,id:n.id,authPayload:o,verifyContext:c,expiryTimestamp:a};await this.setAuthRequest(n.id,{request:l,pairingTopic:t,transportType:s}),s===Ab.link_mode&&e.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:t,params:n.params,id:n.id,verifyContext:c})}catch(e){this.client.logger.error(e);const r=n.params.requester.publicKey,i=await this.client.core.crypto.generateKeyPair(),o=this.getAppLinkIfEnabled(n.params.requester.metadata,s),a={type:1,receiverPublicKey:r,senderPublicKey:i};await this.sendError({id:n.id,topic:t,error:e,encodeOpts:a,rpcOpts:oE.wc_sessionAuthenticate.autoReject,appLink:o})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=cE,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(t=>t.topic===e&&"wc_sessionRequest"===t.request.method).forEach(e=>{this.events.emit(Gf("session_request",e.request.id),{error:t})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===lE)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")},this.emitSessionRequest=e=>{this.emittedSessionRequests.has(e.id)?this.client.logger.warn({id:e.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${e.id}`):(this.sessionRequestQueue.state=lE,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const e=this.client.core.relayer.subscriber.topics;if(0===e.length)return;const t=new Set(this.client.session.keys),n=new Set(this.client.core.pairing.pairings.keys),r=new Set([...this.pendingSessions.values()].map(e=>e.sessionTopic));let i;if(this.client.auth.authKeys.keys.includes(pE)){const{responseTopic:e}=this.client.auth.authKeys.get(pE);i=e}for(const s of e)if(!t.has(s)&&!n.has(s)&&!r.has(s)&&s!==i){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${s}`);try{await this.client.core.relayer.subscriber.unsubscribe(s)}catch(e){this.client.logger.warn(e,`Failed to clean up orphaned subscription: ${s}`)}}},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(t=>t.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:Wy("wc_sessionPropose",{...t,requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties},t.id),attestation:t.attestation,encryptedId:t.encryptedId})},this.isValidConnect=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:n,optionalNamespaces:r,sessionProperties:i,scopedProperties:s,relays:o}=e;if(lm(t)||await this.isValidPairingTopic(t),!function(e){let t=!1;return e?e&&am(e)&&e.length&&e.forEach(e=>{t=wm(e)}):t=!0,t}(o)){const{message:e}=If("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(n&&!lm(n)&&0!==cm(n)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(n,"requiredNamespaces")}if(r&&!lm(r)&&0!==cm(r)&&this.validateNamespaces(r,"optionalNamespaces"),i&&!lm(i)&&this.validateSessionProps(i,"sessionProperties"),s&&!lm(s)){this.validateSessionProps(s,"scopedProperties");const e=Object.keys(n||{}).concat(Object.keys(r||{}));if(!Object.keys(s).every(t=>e.includes(t.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(s)}, required/optional namespaces: ${JSON.stringify(e)}`)}},this.validateNamespaces=(e,t)=>{const n=function(e,t,n){let r=null;if(e&&cm(e)){const i=mm(e,t);i&&(r=i);const s=fm(e,t,n);s&&(r=s)}else r=If("MISSING_OR_INVALID",`${t}, ${n} should be an object with data`);return r}(e,"connect()",t);if(n)throw new Error(n.message)},this.isValidApprove=async e=>{if(!bm(e))throw new Error(If("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:n,relayProtocol:r,sessionProperties:i,scopedProperties:s}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),a=ym(n,"approve()");if(a)throw new Error(a.message);const c=Am(o.requiredNamespaces,n,"approve()");if(c)throw new Error(c.message);if(!dm(r,!0)){const{message:e}=If("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(e)}if(i&&!lm(i)&&this.validateSessionProps(i,"sessionProperties"),s&&!lm(s)){this.validateSessionProps(s,"scopedProperties");const e=new Set(Object.keys(n));if(!Object.keys(s).every(t=>e.has(t.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(s)}, approved namespaces: ${Array.from(e).join(", ")}`)}},this.isValidReject=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:n}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&hm(e.code,!1)&&e.message&&dm(e.message,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:n,namespaces:r,expiry:i}=e;if(!wm(t)){const{message:e}=If("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const s=function(e,t){let n=null;return dm(e?.publicKey,!1)||(n=If("MISSING_OR_INVALID",`${t} controller public key should be a string`)),n}(n,"onSessionSettleRequest()");if(s)throw new Error(s.message);const o=ym(r,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Kf(i)){const{message:e}=If("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:n}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const r=this.client.session.get(t),i=ym(n,"update()");if(i)throw new Error(i.message);const s=Am(r.requiredNamespaces,n,"update()");if(s)throw new Error(s.message)},this.isValidExtend=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:n,chainId:r,expiry:i}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:s}=this.client.session.get(t);if(!vm(s,r)){const{message:e}=If("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(e)}if(!function(e){return!(lm(e)||!dm(e.method,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(e)}if(!Em(s,r,n.method)){const{message:e}=If("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(e)}this.validateRequestExpiry(i)},this.isValidRespond=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:n}=e;try{await this.isValidSessionTopic(t)}catch(t){throw e?.response?.id&&this.cleanupAfterResponse(e),t}if(!function(e){return!(lm(e)||lm(e.result)&&lm(e.error)||!hm(e.id,!1)||!dm(e.jsonrpc,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(e)}const r=this.client.pendingRequest.get(n.id);if(r.topic!==t){const{message:e}=If("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${r.topic}, received topic: ${t}`);throw new Error(e)}},this.isValidPing=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:n,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:i}=this.client.session.get(t);if(!vm(i,r)){const{message:e}=If("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(e)}if(!function(e){return!(lm(e)||!dm(e.name,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(e)}if(!xm(i,r,n.name)){const{message:e}=If("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:n,domain:r,nonce:i}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!dm(n,!1))throw new Error("uri is required parameter");if(!dm(r,!1))throw new Error("domain is required parameter");if(!dm(i,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(e=>vf(e).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:s}=vf(t[0]);if("eip155"!==s)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async e=>{const{attestationId:t,hash:n,encryptedId:r,metadata:i,transportType:s}=e,o={verified:{verifyUrl:i.verifyUrl||qb,validation:"UNKNOWN",origin:i.url||""}};try{if(s===Ab.link_mode){const e=this.getAppLinkIfEnabled(i,s);return o.verified.validation=e&&new URL(e).origin===new URL(i.url).origin?"VALID":"INVALID",o}const e=await this.client.core.verify.resolve({attestationId:t,hash:n,encryptedId:r,verifyUrl:i.verifyUrl});e&&(o.verified.origin=e.origin,o.verified.isScam=e.isScam,o.verified.validation=e.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(e,t)=>{Object.values(e).forEach((n,r)=>{if(null==n){const{message:i}=If("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${n} for key ${Object.keys(e)[r]}`);throw new Error(i)}})},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const n of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(n)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:n}=If("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(n)}},this.isLinkModeEnabled=(t,n)=>!(!t||n!==Ab.link_mode)&&(!0===this.client.metadata?.redirect?.linkMode&&void 0!==this.client.metadata?.redirect?.universal&&""!==this.client.metadata?.redirect?.universal&&void 0!==t?.redirect?.universal&&""!==t?.redirect?.universal&&!0===t?.redirect?.linkMode&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof e?.Linking<"u"),this.getAppLinkIfEnabled=(e,t)=>this.isLinkModeEnabled(e,t)?e?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=Qf(e,"topic")||"",n=decodeURIComponent(Qf(e,"wc_ev")||""),r=this.client.session.keys.includes(t);r&&this.client.session.update(t,{transportType:Ab.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:n,sessionExists:r})},this.registerLinkModeListeners=async()=>{if(eg()||$f()&&this.client.metadata.redirect?.linkMode){const t=e?.Linking;if(typeof t<"u"){t.addEventListener("url",this.handleLinkModeMessage,this.client.name);const e=await t.getInitialURL();e&&setTimeout(()=>{this.handleLinkModeMessage({url:e})},50)}}},this.getTVFApproveParams=e=>{try{const t=nm(e.namespaces),n=function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...e.methods)}),[...new Set(t)]}(e.namespaces),r=function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...e.events)}),[...new Set(t)]}(e.namespaces),i=e.sessionProperties;return{approvedChains:t,approvedMethods:n,approvedEvents:r,sessionProperties:i,scopedProperties:e.scopedProperties}}catch(e){return this.client.logger.warn(e,"Error getting TVF approve params"),{}}},this.getTVFParams=(e,t,n)=>{if(!t.request?.method)return{};const r={correlationId:e,rpcMethods:[t.request.method],chainId:t.chainId};try{const e=this.extractTxHashesFromResult(t.request,n);r.txHashes=e,r.contractAddresses=this.isValidContractData(t.request.params)?[t.request.params?.[0]?.to]:[]}catch(e){this.client.logger.warn(e,"Error getting TVF params")}return r},this.isValidContractData=e=>{if(!e)return!1;try{const t=e?.data||e?.[0]?.data;if(!t.startsWith("0x"))return!1;const n=t.slice(2);return!!/^[0-9a-fA-F]*$/.test(n)&&n.length%2==0}catch{}return!1},this.extractTxHashesFromResult=(e,t)=>{try{if(!t)return[];const n=e.method,r=dE[n];if("sui_signTransaction"===n)return[cg(t.transactionBytes)];if("near_signTransaction"===n)return[lg(t)];if("near_signTransactions"===n)return t.map(e=>lg(e));if("xrpl_signTransactionFor"===n||"xrpl_signTransaction"===n)return[t.tx_json?.hash];if("polkadot_signTransaction"===n)return[Tm({transaction:e.params.transactionPayload,signature:t.signature})];if("algo_signTxn"===n)return am(t)?t.map(e=>dg(e)):[dg(t)];if("cosmos_signDirect"===n)return[ug(t)];if("wallet_sendCalls"===n)return function(e){const t=[];try{if("string"==typeof e)return t.push(e),t;if("object"!=typeof e)return t;e?.id&&t.push(e.id);const n=e?.capabilities?.caip345?.transactionHashes;n&&t.push(...n)}catch(e){console.warn("getWalletSendCallsHashes failed: ",e)}return t}(t);if("string"==typeof t)return[t];const i=t[r.key];if(am(i))return"solana_signAllTransactions"===n?i.map(e=>function(e){const t=ig(e),n=t[0];if(0===n)throw new Error("No signatures found");const r=1+64*n;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const i=t.slice(1,65);return as.encode(i)}(e)):i;if("string"==typeof i)return[i]}catch(e){this.client.logger.warn(e,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,n]of Object.entries(t))for(const t of n)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hb,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:n,attestation:r,transportType:i}=e,{publicKey:s}=this.client.auth.authKeys.keys.includes(pE)?this.client.auth.authKeys.get(pE):{publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,n,{receiverPublicKey:s,encoding:i===Ab.link_mode?Og:Tg});rw(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:r,transportType:i,encryptedId:Mg(n)})):iw(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:i}),this.client.core.history.delete(t,e.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(e)}`),await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:i})),await this.client.core.relayer.messages.ack(t,n)}catch(e){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(Hb,async e=>{const{topic:t,id:n}=Wf(e.target);return n&&this.client.pendingRequest.keys.includes(n)?await this.deletePendingSessionRequest(n,If("EXPIRED"),!0):n&&this.client.auth.requests.keys.includes(n)?await this.deletePendingAuthRequest(n,If("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n})))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Ob,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Rb,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!dm(e,!1)){const{message:t}=If("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}=If("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=If("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!dm(e,!1)){const{message:t}=If("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}=If("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=If("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=If("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)){if(dm(e,!1)){const{message:t}=If("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=If("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!function(e){return"number"==typeof e}(e)){const{message:t}=If("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=If("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=If("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&!function(e,t){return hm(e,!1)&&e<=t.max&&e>=t.min}(e,aE)){const{message:t}=If("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${aE.min} and ${aE.max}`);throw new Error(t)}}},gE=class extends qv{constructor(e,t){super(e,t,"proposal",eE),this.core=e,this.logger=t}},mE=class extends qv{constructor(e,t){super(e,t,"session",eE),this.core=e,this.logger=t}},yE=class extends qv{constructor(e,t){super(e,t,"request",eE,e=>e.id),this.core=e,this.logger=t}},wE=class extends qv{constructor(e,t){super(e,t,"authKeys",uE,()=>pE),this.core=e,this.logger=t}};class bE extends qv{constructor(e,t){super(e,t,"pairingTopics",uE),this.core=e,this.logger=t}}let vE=class extends qv{constructor(e,t){super(e,t,"requests",uE,e=>e.id),this.core=e,this.logger=t}},EE=class{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new wE(this.core,this.logger),this.pairingTopics=new bE(this.core,this.logger),this.requests=new vE(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};const xE=class e extends Cy{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=tE,this.events=new I.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}},this.update=async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}},this.request=async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}},this.find=e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.authenticate=async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}},this.approveSessionAuthenticate=async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.rejectSessionAuthenticate=async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.name=e?.name||tE,this.metadata=function(e){const t=Uf();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter(e=>""!==e)),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(n){return console.warn("Error populating app metadata",n),e||t}}(e?.metadata),this.signConfig=e?.signConfig;const t=Om({logger:e?.logger||nE,name:this.name});this.logger=t,this.core=e?.core||new Qv(e),this.session=new mE(this.core,this.logger),this.proposal=new gE(this.core,this.logger),this.pendingRequest=new yE(this.core,this.logger),this.engine=new fE(this),this.auth=new EE(this.core,this.logger)}static async init(t){const n=new e(t);return await n.initialize(),n}get context(){return yf(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var AE={exports:{}};!function(e,t){var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==o&&o,r=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==o&&o||{},r="URLSearchParams"in n,i="Symbol"in n&&"iterator"in Symbol,s="FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),a="FormData"in n,c="ArrayBuffer"in n;if(c)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(e){return e&&l.indexOf(Object.prototype.toString.call(e))>-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function p(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return i&&(t[Symbol.iterator]=function(){return t}),t}function f(e){this.map={},e instanceof f?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function g(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function m(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function y(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function w(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:s&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:a&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():c&&s&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=w(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c&&(ArrayBuffer.prototype.isPrototypeOf(e)||d(e))?this._bodyArrayBuffer=w(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s&&(this.blob=function(){var e=g(this);if(e)return e;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 e=g(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(s)return this.blob().then(y);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,n,r,i,s=g(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:"utf-8",t.readAsText(e,i),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a&&(this.formData=function(){return this.text().then(x)}),this.json=function(){return this.text().then(JSON.parse)},this}f.prototype.append=function(e,t){e=h(e),t=u(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},f.prototype.delete=function(e){delete this.map[h(e)]},f.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},f.prototype.set=function(e,t){this.map[h(e)]=u(t)},f.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},f.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),p(e)},f.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),p(e)},f.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),p(e)},i&&(f.prototype[Symbol.iterator]=f.prototype.entries);var v=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function E(e,t){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,i,s=(t=t||{}).body;if(e instanceof E){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new f(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,s||null==e._bodyInit||(s=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new f(t.headers)),this.method=(r=t.method||this.method||"GET",i=r.toUpperCase(),v.indexOf(i)>-1?i:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&s)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(s),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var o=/([?&])_=[^&]*/;if(o.test(this.url))this.url=this.url.replace(o,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function x(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function A(e,t){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.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=void 0===t.statusText?"":""+t.statusText,this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},b.call(E.prototype),b.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var k=[301,302,303,307,308];A.redirect=function(e,t){if(-1===k.indexOf(t))throw new RangeError("Invalid status code");return new A(null,{status:t,headers:{location:e}})},t.DOMException=n.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function I(e,r){return new Promise(function(i,o){var a=new E(e,r);if(a.signal&&a.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var l=new XMLHttpRequest;function d(){l.abort()}if(l.onload=function(){var e,t,n={statusText:l.statusText,headers:(e=l.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();try{t.append(r,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===a.url.indexOf("file://")&&(l.status<200||l.status>599)?n.status=200:n.status=l.status,n.url="responseURL"in l?l.responseURL:n.headers.get("X-Request-URL");var r="response"in l?l.response:l.responseText;setTimeout(function(){i(new A(r,n))},0)},l.onerror=function(){setTimeout(function(){o(new TypeError("Network request failed"))},0)},l.ontimeout=function(){setTimeout(function(){o(new TypeError("Network request timed out"))},0)},l.onabort=function(){setTimeout(function(){o(new t.DOMException("Aborted","AbortError"))},0)},l.open(a.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(a.url),!0),"include"===a.credentials?l.withCredentials=!0:"omit"===a.credentials&&(l.withCredentials=!1),"responseType"in l&&(s?l.responseType="blob":c&&(l.responseType="arraybuffer")),r&&"object"==typeof r.headers&&!(r.headers instanceof f||n.Headers&&r.headers instanceof n.Headers)){var p=[];Object.getOwnPropertyNames(r.headers).forEach(function(e){p.push(h(e)),l.setRequestHeader(e,u(r.headers[e]))}),a.headers.forEach(function(e,t){-1===p.indexOf(t)&&l.setRequestHeader(t,e)})}else a.headers.forEach(function(e,t){l.setRequestHeader(t,e)});a.signal&&(a.signal.addEventListener("abort",d),l.onreadystatechange=function(){4===l.readyState&&a.signal.removeEventListener("abort",d)}),l.send(void 0===a._bodyInit?null:a._bodyInit)})}I.polyfill=!0,n.fetch||(n.fetch=I,n.Headers=f,n.Request=E,n.Response=A),t.Headers=f,t.Request=E,t.Response=A,t.fetch=I,Object.defineProperty(t,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t}(AE,AE.exports);var kE=a(AE.exports),IE=Object.defineProperty,CE=Object.defineProperties,SE=Object.getOwnPropertyDescriptors,PE=Object.getOwnPropertySymbols,NE=Object.prototype.hasOwnProperty,_E=Object.prototype.propertyIsEnumerable,TE=(e,t,n)=>t in e?IE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,OE=(e,t)=>{for(var n in t||(t={}))NE.call(t,n)&&TE(e,n,t[n]);if(PE)for(var n of PE(t))_E.call(t,n)&&TE(e,n,t[n]);return e},$E=(e,t)=>CE(e,SE(t));const RE={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"};let BE=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new I.EventEmitter,this.isAvailable=!1,this.registering=!1,!ew(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=fl(e),n=await(await kE(this.url,$E(OE({},RE),{body:t}))).json();this.onPayload({data:n})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!ew(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise((e,t)=>{this.events.once("register_error",e=>{this.resetMaxListeners(),t(e)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return t(new Error("HTTP connection is missing or invalid"));e()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=fl({id:1,jsonrpc:"2.0",method:"test",params:[]});await kE(e,$E(OE({},RE),{body:t}))}this.onOpen()}catch(e){const t=this.parseError(e);throw this.events.emit("register_error",t),this.onClose(),t}}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="string"==typeof e.data?pl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),r=Ky(e,n.message||n.toString());this.events.emit("payload",r)}parseError(e,t=this.url){return Ly(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}};const ME="error",UE="universal_provider",LE=`wc@2:${UE}:`,DE="https://rpc.walletconnect.org/v1/",jE="generic",zE=`${DE}bundler`,HE="call_status",VE="default_chain_changed";function FE(e,t,n){const r=vf(e);return t.rpcMap?.[r.reference]||`${DE}?chainId=${r.namespace}:${r.reference}&projectId=${n}`}function qE(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function WE(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t?.chains?.length&&t?.chains?.length>0))}function ZE(e={},t={}){return nb(WE(KE(e)),WE(KE(t)))}function KE(e){const t={};if(!cm(e))return t;for(const[n,r]of Object.entries(e)){const e=rm(n)?[n]:r.chains,i=r.methods||[],s=r.events||[],o=r.rpcMap||{},a=im(n);t[a]={...t[a],...r,chains:Yf(e,t[a]?.chains),methods:Yf(i,t[a]?.methods),events:Yf(s,t[a]?.events)},(cm(o)||cm(t[a]?.rpcMap||{}))&&(t[a].rpcMap={...o,...t[a]?.rpcMap})}return t}function GE(e){return e.includes(":")?e.split(":")[2]:e}function YE(e){const t={};for(const[n,r]of Object.entries(e)){const e=r.methods||[],i=r.events||[],s=r.accounts||[],o=rm(n)?[n]:r.chains?r.chains:qE(r.accounts);t[n]={chains:o,methods:e,events:i,accounts:s}}return t}function JE(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const QE={},XE=e=>QE[e],ex=(e,t)=>{QE[e]=t},tx="eip155",nx=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],rx=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,ix=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,sx=e=>Object.keys(e).filter(e=>nx.includes(e)).reduce((t,n)=>(t[n]=ox(e[n]),t),{}),ox=e=>"string"==typeof e&&function(e){try{const t=JSON.parse(e);return"object"==typeof t&&null!==t&&!Array.isArray(t)}catch{return!1}}(e)?JSON.parse(e):e;let ax,cx=class e{constructor(e){this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(t){return ax||(ax=new e(t)),ax}};async function lx(e,t){const n=vf(e.result.capabilities.caip345.caip2),r=e.result.capabilities.caip345.transactionHashes,i=await Promise.allSettled(r.map(e=>async function(e,t,n){return await n(parseInt(e)).request(Wy("eth_getTransactionReceipt",[t]))}(n.reference,e,t))),s=i.filter(e=>"fulfilled"===e.status).map(e=>e.value).filter(e=>e);i.filter(e=>"rejected"===e.status).forEach(e=>console.warn("Failed to fetch transaction receipt:",e.reason));const o=!s.length||s.some(e=>!e),a=s.every(e=>"0x1"===e?.status),c=s.every(e=>"0x0"===e?.status),l=s.some(e=>"0x0"===e?.status);let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function dx({resultId:e,storage:t}){const n=(await t.getItem(HE))?.[e];if(n&&!Kf(n.expiry))return n;await async function({resultId:e,storage:t}){const n=await t.getItem(HE);if(n){delete n[e],await t.setItem(HE,n);for(const e in n)Kf(n[e].expiry)&&delete n[e];await t.setItem(HE,n)}}({resultId:e,storage:t})}let hx=class{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=XE("events"),this.client=XE("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=cx.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(VE,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}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 n=t||FE(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new aw(new BE(n,XE("disableProviderPing")))}setHttpProvider(e,t){const n=this.createHttpProvider(e,t);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const n=parseInt(function(e){return e.includes(":")?e.split(":")[1]:e}(t));e[n]=this.createHttpProvider(n,this.namespace.rpcMap?.[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders={...this.httpProviders,[t]:this.createHttpProvider(t)},this.httpProviders[t])}async handleSwitchChain(e){let t=e.request.params?e.request.params[0]?.chainId:"0x0";t=t.startsWith("0x")?t:`0x${t}`;const n=parseInt(t,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:t}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${n}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){const t=e.request?.params?.[0],n=e.request?.params?.[1]||[];if(!t)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const r=this.client.session.get(e.topic),i=r?.sessionProperties?.capabilities||{},s=`${t}${n.length>0?n.join(","):`0x${this.chainId.toString(16)}`}`,o=i?.[s];if(o)return o;let a;try{a=((e,t,n)=>{const{sessionProperties:r={},scopedProperties:i={}}=e,s={};if(!cm(i)&&!cm(r))return;const o=sx(r);for(const e of n){const n=rx(e);if(!n)continue;s[ix(n)]=o;const r=i?.[`${tx}:${n}`];if(r){const e=r?.[`${tx}:${n}:${t}`];s[ix(n)]={...s[ix(n)],...sx(e||r)}}}for(const[e,t]of Object.entries(s))0===Object.keys(t).length&&delete s[e];return Object.keys(s).length>0?s:void 0})(r,t,n)}catch(e){console.warn("Failed to extract capabilities from session",e)}if(a)return a;const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:{...r.sessionProperties||{},capabilities:{...i||{},[s]:c}}})}catch(e){console.warn("Failed to update session with capabilities",e)}return c}async getCallStatus(e){const t=this.client.session.get(e.topic),n=t.sessionProperties?.bundler_name;if(n){const t=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const r=t.sessionProperties?.bundler_url;if(r)try{return await this.getUserOperationReceipt(r,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,r)}const i=await dx({resultId:e.request.params?.[0],storage:this.storage});if(i)try{return await lx(i,this.getHttpProvider.bind(this))}catch(e){console.warn("Failed to fetch call status from stored send calls",e,i)}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){const n=new URL(e),r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Wy("eth_getUserOperationReceipt",[t.request.params?.[0]]))});if(!r.ok)throw new Error(`Failed to fetch user operation receipt - ${r.status}`);return await r.json()}getBundlerUrl(e,t){return`${zE}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){const t=await this.client.request(e),n=e.request.params?.[0],r=t?.id,i=t?.capabilities||{},s=i?.caip345?.caip2,o=i?.caip345?.transactionHashes;return!r||!s||!o?.length||await async function({sendCalls:e,storage:t}){const n=await t.getItem(HE);await t.setItem(HE,{...n,[e.result.id]:{request:e.request,result:e.result,expiry:Zf(86400)}})}({sendCalls:{request:n,result:t},storage:this.storage}),t}},ux=class{constructor(e){this.name=jE,this.namespace=e.namespace,this.events=XE("events"),this.client=XE("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t);const n=this.chainId;this.chainId=e,this.events.emit(VE,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return vf(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace?.accounts?.forEach(t=>{const n=vf(t),r=this.namespace?.rpcMap?.[`${n.namespace}:${n.reference}`];e[n.reference]=this.createHttpProvider(t,r)}),e}getHttpProvider(e){const t=vf(e).reference,n=this.httpProviders[t];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,t){const n=this.createHttpProvider(e,t);n&&(this.httpProviders[e]=n)}createHttpProvider(e,t){const n=t||FE(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new aw(new BE(n,XE("disableProviderPing")))}};const px=class e{constructor(e){this.events=new C,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=e,this.logger=Om({logger:e.logger??ME,name:this.providerOpts.name??UE}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(t){const n=new e(t);return await n.initialize(),n}async request(e,t,n){const[r,i]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:{...e},chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,t,n,r){const i=(new Date).getTime();this.request(e,n,r).then(e=>t(null,Zy(i,e))).catch(e=>t(e,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(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Cf("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,t);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const e=YE(this.session.namespaces);this.namespaces=ZE(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}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:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await n();this.session=r;const i=YE(r.namespaces);return this.namespaces=ZE(this.namespaces,i),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[n,r]=this.validateChain(e),i=this.getProvider(n);i?i.setDefaultChain(r,t):this.session&&this.logger.warn(`Provider for namespace '${n}' not found in setDefaultChain`)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!am(t))return;for(const n of t)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}catch(e){this.logger.warn(e,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){if(this.client=this.providerOpts.client||await xE.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ME,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",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(e){throw this.logger.error(e,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[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(e=>im(e)))];ex("client",this.client),ex("events",this.events),ex("disableProviderPing",this.disableProviderPing),e.forEach(e=>{if(!this.session)return;const t=function(e,t){const n=Object.keys(t.namespaces).filter(t=>t.includes(e));if(!n.length)return[];const r=[];return n.forEach(e=>{const n=t.namespaces[e].accounts;r.push(...n)}),r}(e,this.session);if(0===t?.length)return;const n=qE(t),r={...ZE(this.namespaces,this.optionalNamespaces)[e],accounts:t,chains:n};if("eip155"===e)this.rpcProviders[e]=new hx({namespace:r});else this.rpcProviders[e]=new ux({namespace:r})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{const{topic:t}=e;t===this.session?.topic&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t,topic:n}=e;if(n!==this.session?.topic)return;const{event:r}=t;if("accountsChanged"===r.name){const e=r.data;e&&am(e)&&this.events.emit("accountsChanged",e.map(GE))}else if("chainChanged"===r.name){const e=t.chainId,n=t.event.data,r=im(e),i=JE(e)!==JE(n)?`${r}:${JE(n)}`:e;this.onChainChanged({currentCaipChainId:i})}else this.events.emit(r.name,r.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{if(e!==this.session?.topic)return;const{namespaces:n}=t,r=this.client?.session.get(e);this.session={...r,namespaces:n},this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{e.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",{...Cf("USER_DISCONNECTED"),data:e.topic}))}),this.on(VE,e=>{this.onChainChanged({...e,internal:!0})})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[jE]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{this.getProvider(e).updateNamespace(this.session?.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=ZE(t,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[t,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,n];if(t&&!Object.keys(this.namespaces||{}).map(e=>im(e)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&n)return[t,n];const r=im(Object.keys(this.namespaces)[0]);return[r,this.rpcProviders[r].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);if(i){if(this.updateNamespaceChain(r,i),n)this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:t});else{const e=this.getProvider(r);e?e.setDefaultChain(i):this.session&&this.logger.warn(`Provider for namespace '${r}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:n}){try{if(n===t)return;const r=this.session?.namespaces[e]?.accounts;if(!r)return;const i=r.filter(e=>e.includes(`${t}:`)).map(GE);if(!am(i))return;this.events.emit("accountsChanged",i)}catch(e){this.logger.warn(e,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=t):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){const n=this.session?.topic||"";await this.client.core.storage.setItem(`${LE}/${e}${n}`,t)}async getFromStore(e){const t=this.session?.topic||"";return await this.client.core.storage.getItem(`${LE}/${e}${t}`)}async deleteFromStore(e){const t=this.session?.topic||"";await this.client.core.storage.removeItem(`${LE}/${e}${t}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;const e=await this.client.core.storage.getKeys();for(const t of e)t.startsWith(LE)&&await this.client.core.storage.removeItem(t)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}},fx=["eth_sendTransaction","personal_sign"],gx=["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"],mx=["chainChanged","accountsChanged"],yx=["chainChanged","accountsChanged","message","disconnect","connect"];function wx(e){return Number(e[0].split(":")[1])}function bx(e){return`0x${e.toString(16)}`}let vx=class e{constructor(){this.events=new I.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY="wc@2:ethereum_provider:",this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(t){const n=new e;return await n.initialize(t),n}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,n){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),n)}get connected(){return!!this.signer.client&&this.signer.client.core.relayer.connected}get connecting(){return!!this.signer.client&&this.signer.client.core.relayer.connecting}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:n}=function(e){const{chains:t,optionalChains:n,methods:r,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=e;if(!am(t))throw new Error("Invalid chains");const c={chains:t,methods:r||fx,events:s||mx,rpcMap:{...t.length?{[wx(t)]:a[wx(t)]}:{}}},l=s?.filter(e=>!mx.includes(e)),d=r?.filter(e=>!fx.includes(e));if(!(n||o||i||l?.length||d?.length))return{required:t.length?c:void 0};const h={chains:[...new Set(l?.length&&d?.length||!n?c.chains.concat(n||[]):n)],methods:[...new Set(c.methods.concat(i?.length?i:gx))],events:[...new Set(c.events.concat(o?.length?o:yx))],rpcMap:a};return{required:t.length?c:void 0,optional:n.length?h:void 0}}(this.rpc);try{const r=await new Promise(async(r,i)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),i(new Error("Connection request reset. Please try again.")))}));const s=e?.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect({namespaces:{...t&&{[this.namespace]:t}},...n&&{optionalNamespaces:{[this.namespace]:n}},pairingTopic:e?.pairingTopic,scopedProperties:s}).then(e=>{r(e)}).catch(e=>{this.modal?.showErrorMessage("Unable to connect"),i(new Error(e.message))})});if(!r)return;const i=Ef(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:i),this.setAccounts(i),this.events.emit("connect",{chainId:bx(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.close()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const n=await new Promise(async(n,r)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),r(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate({...e,chains:this.rpc.chains},t).then(e=>{n(e)}).catch(e=>{this.modal?.showErrorMessage("Unable to connect"),r(new Error(e.message))})}),r=n.session;if(r){const e=Ef(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:e),this.setAccounts(e),this.events.emit("connect",{chainId:bx(this.chainId)})}return n}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.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:n}=t;"accountsChanged"===n.name?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):"chainChanged"===n.name?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.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",bx(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",{...Cf("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"string"==typeof e&&e.startsWith(`${this.namespace}:`)}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(e=>this.isCompatibleChainId(e)).map(e=>this.parseChainId(e));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",bx(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,n,r]=e.split(":");return{chainId:`${t}:${n}`,address:r}}setAccounts(e){this.accounts=e.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){const t=e?.chains??[],n=e?.optionalChains??[],r=t.concat(n);if(!r.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const i=t.length?e?.methods||fx:[],s=t.length?e?.events||mx:[],o=e?.optionalMethods||[],a=e?.optionalEvents||[],c=e?.rpcMap||this.buildRpcMap(r,e.projectId),l=e?.qrModalOptions||void 0;return{chains:t?.map(e=>this.formatChainId(e)),optionalChains:n.map(e=>this.formatChainId(e)),methods:i,events:s,optionalMethods:o,optionalEvents:a,rpcMap:c,showQrModal:!!e?.showQrModal,qrModalOptions:l,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const n={};return e.forEach(e=>{n[e]=this.getRpcUrl(e,t)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?wx(this.rpc.chains):wx(this.rpc.optionalChains),this.signer=await px.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 e;try{const t=await(async()=>{const{createAppKit:e}=await Promise.resolve().then(function(){return p5});return e})(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return Ix}),r=n({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!r.networks.length)throw new Error("No networks found for WalletConnect");e=t({...r,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:!0===this.rpc.qrModalOptions?.enableMobileFullScreen})}catch(e){throw console.warn(e),new Error("To use QR modal, please install @reown/appkit package")}if(e)try{this.modal=e}catch(e){throw this.signer.logger.error(e),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:n,rpcMap:r}=e;t&&am(t)&&(this.rpc.chains=t.map(e=>this.formatChainId(e)),t.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)})),n&&am(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(e=>this.formatChainId(e)),n.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)}))}getRpcUrl(e,t){return this.rpc.rpcMap?.[e]||`https://rpc.walletconnect.org/v1/?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?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(e=>this.signer.logger.warn(e))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return"string"==typeof e||e instanceof String?[this.parseAccount(e)]:e.map(e=>this.parseAccount(e))}};const Ex=vx;function xx(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const Ax=e=>{const[t,n]=e.split(":");return kx({id:n,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function kx(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var Ix=Object.freeze({__proto__:null,convertWCMToAppKitOptions:function(e){const t=e.chains?.map(Ax).filter(Boolean);if(0===t.length)throw new Error("At least one chain must be specified");const n=t.find(t=>t.id===e.defaultChain?.id),r={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:xx(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:n,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:"NONE"===e.explorerRecommendedWalletIds?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:"ALL"===e.explorerExcludedWalletIds?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){const t=[...(e.mobileWallets||[]).map(e=>({id:e.id,name:e.name,links:e.links})),...(e.desktopWallets||[]).map(e=>({id:e.id,name:e.name,links:{native:e.links.native,universal:e.links.universal}}))],n=[...r.featuredWalletIds||[],...r.excludeWalletIds||[]],i=t.filter(e=>!n.includes(e.id));i.length&&(r.customWallets=i)}return r},defineChain:kx}),Cx=Object.freeze({__proto__:null,EthereumProvider:Ex,OPTIONAL_EVENTS:yx,OPTIONAL_METHODS:gx,REQUIRED_EVENTS:mx,REQUIRED_METHODS:fx,default:vx});const Sx=[{name:"MetaMask",icon:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",universalLink:e=>`https://metamask.app.link/wc?uri=${encodeURIComponent(e)}`},{name:"Trust Wallet",icon:"https://trustwallet.com/assets/images/favicon.png",universalLink:e=>`https://link.trustwallet.com/wc?uri=${encodeURIComponent(e)}`},{name:"Rainbow",icon:"https://rainbow.me/favicon.ico",universalLink:e=>`https://rnbwapp.com/wc?uri=${encodeURIComponent(e)}`},{name:"Coinbase Wallet",icon:"https://www.coinbase.com/favicon.ico",universalLink:e=>`https://go.cb-w.com/wc?uri=${encodeURIComponent(e)}`}];class Px{constructor(){this.injectedProviders=[],this.selectedProvider=null,this.wcProvider=null,this.connectedAddress=null,this.connectionType=null,this._wcSessionReady=!1,this._accountsChangedHandler=null,this._chainChangedHandler=null,this._wcSessionRequestSentHandler=null,this._onWCUri=null,this._onWCConnected=null,this._onWCDisconnected=null;["isMobile","isIOS","discoverInjectedWallets","connectInjected","initWalletConnect","connectWalletConnect","getActiveChainId","getApprovedChainIds","isSessionAlive","switchNetwork","disconnect","_openWalletForApproval","_attachProviderListeners","_cleanupWC","_connectionResult","isConnected","getAddress","getProvider","getMobileWallets"].forEach(e=>{this[e]=this[e].bind(this)})}isMobile(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}isIOS(){return/iPhone|iPad|iPod/i.test(navigator.userAgent)}async getActiveChainId(){const e=this.selectedProvider;if(!e)return null;try{const t=await e.request({method:"eth_chainId"}),n=parseInt(t,16);return console.log("[WalletService] eth_chainId RPC →",n),n}catch(e){return console.error("[WalletService] eth_chainId RPC failed:",e.message),null}}getApprovedChainIds(){if(!this._wcSessionReady)return[];const e=this.wcProvider?.session?.namespaces?.eip155?.accounts??[],t=new Set;for(const n of e){const e=n.split(":"),r=parseInt(e[1],10);e.length>=3&&!isNaN(r)&&r>0&&t.add(r)}return[...t]}async isSessionAlive(){if(!this.selectedProvider)return!1;try{return await this.selectedProvider.request({method:"eth_chainId"}),!0}catch{return!1}}discoverInjectedWallets(){return new Promise(e=>{this.injectedProviders=[];const t=e=>{const{info:t,provider:n}=e.detail??{};if(!t||!n)return;const r=this.injectedProviders.some(e=>e.info.uuid===t.uuid);r||this.injectedProviders.push({info:t,provider:n})};window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{window.removeEventListener("eip6963:announceProvider",t),0===this.injectedProviders.length&&window.ethereum&&this.injectedProviders.push({info:{uuid:"legacy",name:window.ethereum.isMetaMask?"MetaMask":"Browser Wallet",icon:window.ethereum.isMetaMask?"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg":null},provider:window.ethereum}),console.log(`[WalletService] Injected providers found (${this.injectedProviders.length}):`,this.injectedProviders.map(e=>e.info.name)),e(this.injectedProviders)},300)})}async connectInjected(e){const t=this.injectedProviders[e];if(!t)throw new Error(`[WalletService] No injected provider at index ${e}`);let n;console.log(`[WalletService] Connecting injected: ${t.info.name}`);try{n=await t.provider.request({method:"eth_requestAccounts"})}catch(e){if(4001===e.code){const e=new Error("User rejected the connection");throw e.code="USER_CANCELLED",e}throw e}if(!n?.length){const e=new Error("No accounts returned");throw e.code="USER_CANCELLED",e}this.selectedProvider=t.provider,this.connectedAddress=n[0],this.connectionType="injected",this._wcSessionReady=!1,this._attachProviderListeners(t.provider);const r=await this.getActiveChainId();return console.log(`[WalletService] Injected connected — address: ${this.connectedAddress} | chain: ${r}`),this._connectionResult()}async initWalletConnect(e,t,n){const{EthereumProvider:r}=await Promise.resolve().then(function(){return Cx});if(this.wcProvider){try{await this.wcProvider.disconnect()}catch(e){}this.wcProvider=null}this._wcSessionReady=!1;const s=Object.values(i).map(e=>e.chainId),o={};Object.values(i).forEach(e=>{o[e.chainId]=e.rpcUrl}),console.log("[WalletService] Initializing WalletConnect — supported chains:",s);const a=await r.init({projectId:"3a2347dfc8ba5a336fe715a34644f490",optionalChains:s,showQrModal:!1,rpcMap:o,metadata:{name:"KwesPay",description:"Crypto payment widget",url:window.location.origin,icons:["https://arthuremma2.github.io/img-hosting/kwespay-icon.png"]}});return this._onWCUri=e,this._onWCConnected=t,this._onWCDisconnected=n,a.on("display_uri",e=>{this._onWCUri&&this._onWCUri(e)}),a.on("connect",async()=>{const e=a.session,t=e?.namespaces?.eip155?.accounts??[];if(0===t.length)return void console.error("[WalletService] WC connected but session has no accounts");const n=t[0].split(":")[2];this.wcProvider=a,this.selectedProvider=a,this.connectedAddress=n,this.connectionType="walletconnect",this._wcSessionReady=!0,this._attachProviderListeners(a);const r=await this.getActiveChainId(),i=this.getApprovedChainIds();console.log(`[WalletService] WC session ready — address: ${n} | active chain: ${r} | approved chains: [${i}]`),this._onWCConnected&&this._onWCConnected()}),a.on("disconnect",()=>{console.log("[WalletService] WC session disconnected"),this._cleanupWC(),this._onWCDisconnected&&this._onWCDisconnected()}),a.on("chainChanged",e=>{this._wcSessionReady&&console.log("[WalletService] WC chainChanged event — new chain:",parseInt(e,16))}),this._wcSessionRequestSentHandler=()=>{this.isMobile()&&(console.log("[WalletService] session_request_sent — opening wallet for approval"),this._openWalletForApproval())},a.on("session_request_sent",this._wcSessionRequestSentHandler),this.wcProvider=a,a}async connectWalletConnect(e){if(!this.wcProvider)throw new Error("[WalletService] Call initWalletConnect first");if(!e)throw new Error("[WalletService] targetChainId is required for connectWalletConnect");console.log(`[WalletService] Starting WC handshake — requesting session on chain ${e}`),await this.wcProvider.connect({optionalNamespaces:{eip155:{methods:["eth_sendTransaction","eth_signTransaction","eth_sign","personal_sign","eth_signTypedData"],chains:[`eip155:${e}`],events:["chainChanged","accountsChanged"]}}})}_openWalletForApproval(){const e=this.wcProvider?.session,t=e?.peer?.metadata?.redirect?.native,n=e?.peer?.metadata?.redirect?.universal,r=t||n;r?this.isIOS()?window.location.href=r:window.open(r,"_blank","noreferrer noopener"):console.warn("[WalletService] No redirect URI in session metadata — user must switch manually")}async switchNetwork(e,t,n,r,i){const s=this.selectedProvider;if(!s)throw new Error("[WalletService] No provider connected");const o="0x"+e.toString(16);try{await s.request({method:"wallet_switchEthereumChain",params:[{chainId:o}]})}catch(e){if(4902!==e.code&&-32603!==e.code)throw e;console.log(`[WalletService] Chain ${t} unknown to wallet — adding it`),await s.request({method:"wallet_addEthereumChain",params:[{chainId:o,chainName:t,rpcUrls:[n],nativeCurrency:{name:r,symbol:r,decimals:i}}]}),console.log(`[WalletService] Chain ${t} added and switched`)}}_attachProviderListeners(e){this._accountsChangedHandler=e=>{console.log("[WalletService] accountsChanged →",e[0]??"none"),this.connectedAddress=e[0]??null},this._chainChangedHandler=e=>{"injected"===this.connectionType&&console.log("[WalletService] chainChanged (injected) →",parseInt(e,16))},e.on("accountsChanged",this._accountsChangedHandler),e.on("chainChanged",this._chainChangedHandler)}async disconnect(){if(this.selectedProvider){try{this.selectedProvider.removeListener?.("accountsChanged",this._accountsChangedHandler)}catch(e){}try{this.selectedProvider.removeListener?.("chainChanged",this._chainChangedHandler)}catch(e){}}this._cleanupWC(),this.selectedProvider=null,this.connectedAddress=null,this.connectionType=null,this._wcSessionReady=!1,console.log("[WalletService] Disconnected")}_cleanupWC(){if(this.wcProvider){try{this.wcProvider.removeListener?.("display_uri",this._onWCUri)}catch(e){}try{this.wcProvider.removeListener?.("connect",this._onWCConnected)}catch(e){}try{this.wcProvider.removeListener?.("disconnect",this._onWCDisconnected)}catch(e){}try{this.wcProvider.removeListener?.("session_request_sent",this._wcSessionRequestSentHandler)}catch(e){}try{this.wcProvider.disconnect()}catch(e){}this.wcProvider=null}this._wcSessionReady=!1,this._onWCUri=null,this._onWCConnected=null,this._onWCDisconnected=null,this._wcSessionRequestSentHandler=null}_connectionResult(){return{address:this.connectedAddress,shortAddress:this._truncate(this.connectedAddress),provider:this.selectedProvider,connectionType:this.connectionType}}_truncate(e){return e?`${e.slice(0,6)}...${e.slice(-4)}`:""}isConnected(){return!!this.connectedAddress}getAddress(){return this.connectedAddress}getProvider(){return this.selectedProvider}getMobileWallets(){return Sx}}let Nx=class{constructor(e,t){this.apiKey=e,this.graphqlEndpoint=t,this.client=null,console.log("[KwesPay] PaymentService initialized",{apiKey:this.apiKey?.slice(0,6)+"..."})}async _initClient(){if(this.client)return;console.log("[KwesPay] Initializing SDK client...");const{KwesPayClient:e}=await Promise.resolve().then(function(){return Y9});this.client=new e({apiKey:this.apiKey}),console.log("[KwesPay] SDK client ready")}async validateAPIKey(){try{await this._initClient();const e=await this.client.validateKey();return e.isValid?{valid:!0,keyId:e.keyId,vendorInfo:e.vendorInfo,allowedVendors:e.scope.allowedVendors??null,allowedNetworks:e.scope.allowedNetworks??null,allowedTokens:e.scope.allowedTokens??null}:(console.error("[KwesPay] Invalid API key:",e.error),{valid:!1,error:e.error??"Invalid access key"})}catch(e){return console.error("[KwesPay] API key validation error:",e),{valid:!1,error:e.message}}}async getQuote(e){await this._initClient(),console.log("[KwesPay] Requesting quote...",e);const t=await this.client.quote({vendorIdentifier:e.vendorId,fiatAmount:e.fiatAmount,fiatCurrency:e.fiatCurrency||"USD",cryptoCurrency:e.cryptoCurrency,network:e.network,payerWalletAddress:e.payerWalletAddress});return console.log("[KwesPay] Quote received:",t),t}async createPayment({payload:e,walletProvider:t,onStatusUpdate:n}){await this._initClient(),console.log("[KwesPay] 💳 createPayment called",{payloadKeys:e?Object.keys(e):null,amountBaseUnits:e?.amountBaseUnits,contractAddress:e?.contractAddress,paymentId:e?.paymentId,vendorAddress:e?.vendorAddress,expiresAt:e?.expiresAt,providerType:t?.constructor?.name});try{const r=await this.client.pay({provider:t,payload:e,onStatus:e=>{console.log("[KwesPay] 📋 Payment status update:",e),n?.(e)}});return console.log("[KwesPay] ✅ Payment completed:",r),{hash:r.txHash,blockNumber:r.blockNumber,transactionReference:r.transactionReference,paymentIdBytes32:r.paymentIdBytes32}}catch(e){throw console.error("[KwesPay] ❌ createPayment error:",{message:e?.message,code:e?.code,reason:e?.reason,data:e?.data,transaction:e?.transaction?{to:e.transaction?.to,from:e.transaction?.from,value:e.transaction?.value?.toString(),gasLimit:e.transaction?.gasLimit?.toString(),data:e.transaction?.data}:void 0,receipt:e?.receipt?{status:e.receipt?.status,gasUsed:e.receipt?.gasUsed?.toString(),blockNumber:e.receipt?.blockNumber,transactionHash:e.receipt?.transactionHash}:void 0,stack:e?.stack,raw:e}),e}}async getTransactionStatus(e){await this._initClient(),console.log("[KwesPay] Fetching transaction status:",e);const t=await this.client.getTransactionStatus(e);return console.log("[KwesPay] Transaction status:",t),t}async pollTransactionStatus(e,{onStatus:t,intervalMs:n=4e3,maxAttempts:r=60}={}){await this._initClient(),console.log("[KwesPay] Starting polling...",{transactionReference:e,intervalMs:n});let i=0;return new Promise((s,o)=>{const a=setInterval(async()=>{i++;try{const n=await this.getTransactionStatus(e);console.log(`[KwesPay] Poll attempt ${i}:`,n.transactionStatus),t?.(n.transactionStatus);["completed","failed","expired","underpaid","overpaid","refunded"].includes(n.transactionStatus)?(console.log("[KwesPay] Final status reached:",n.transactionStatus),clearInterval(a),s(n)):i>=r&&(console.error("[KwesPay] Polling timeout"),clearInterval(a),o(new Error("Transaction status polling timed out.")))}catch(e){console.error("[KwesPay] Polling error:",e),i>=r&&(clearInterval(a),o(e))}},n)})}};function _x(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Tx(e,t={}){const n=new CustomEvent(`kwespay:${e}`,{detail:t,bubbles:!0,cancelable:!0});window.dispatchEvent(n)}function Ox(e){const t=e?.message??"";return 4001===e?.code||"ACTION_REJECTED"===e?.code||t.includes("rejected")||t.includes("denied")||t.includes("cancelled")?"USER_REJECTED":t.toLowerCase().includes("insufficient")?"INSUFFICIENT_BALANCE":t.includes("User rejected")||t.includes("User closed modal")||t.includes("Connection request reset")?"CONNECTION_REJECTED":t.includes("timeout")?"TIMEOUT":"UNKNOWN"}const $x={_init(){this._injectFonts(),this._injectStyles(),this._createWidgetDOM()},_injectFonts(){if(!document.querySelector('link[href*="fonts.googleapis.com/css2?family=Syne"]')){const e=document.createElement("link");e.href="https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=DM+Mono:wght@300;400;500&family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap",e.rel="stylesheet",document.head.appendChild(e)}},_injectStyles(){if(!document.getElementById("kwespay-widget-styles")){const e=document.createElement("style");e.id="kwespay-widget-styles",e.textContent="\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n\n * { margin: 0; padding: 0; box-sizing: border-box; }\n\n :root {\n --kp-bg: #0a0a0f;\n --kp-surface: #0f0f18;\n --kp-surface-2: #16161f;\n --kp-border: rgba(255,255,255,0.06);\n --kp-border-active: rgba(99,102,241,0.5);\n --kp-accent: #6366f1;\n --kp-accent-dim: rgba(99,102,241,0.1);\n --kp-accent-glow: rgba(99,102,241,0.25);\n --kp-green: #10b981;\n --kp-red: #f43f5e;\n --kp-text: #f1f0ff;\n --kp-muted: #6b6a80;\n --kp-mono: 'Inter', monospace;\n --kp-sans: 'Inter', sans-serif;\n }\n\n body.kwespay-open {\n overflow: hidden;\n touch-action: none;\n }\n\n .kwespay-overlay {\n position: fixed;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.75);\n backdrop-filter: blur(8px) saturate(1.2);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n padding: 20px;\n font-family: var(--kp-sans);\n }\n\n .kwespay-overlay.open { display: flex; }\n\n .kwespay-close-btn {\n position: absolute;\n top: 20px; right: 20px;\n background: rgba(255,255,255,0.06);\n border: 1px solid var(--kp-border);\n color: var(--kp-muted);\n width: 34px; height: 34px;\n border-radius: 8px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 18px;\n transition: all 0.15s;\n z-index: 1000000;\n }\n\n .kwespay-close-btn:hover {\n background: rgba(255,255,255,0.1);\n color: var(--kp-text);\n border-color: var(--kp-border-active);\n }\n\n .material-symbols-outlined {\n font-variation-settings: \"FILL\" 0, \"wght\" 400, \"GRAD\" 0, \"opsz\" 24;\n }\n\n .kwespay-container {\n position: relative;\n display: flex;\n height: 640px;\n max-height: 92vh;\n min-height: 520px;\n width: 100%;\n max-width: 390px;\n flex-direction: column;\n background: var(--kp-bg);\n border: 1px solid var(--kp-border);\n box-shadow:\n 0 0 0 1px rgba(255,255,255,0.03),\n 0 32px 64px rgba(0,0,0,0.9),\n 0 0 80px rgba(99,102,241,0.06);\n overflow: hidden;\n border-radius: 20px;\n font-family: var(--kp-sans);\n animation: kpSlideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;\n }\n\n @keyframes kpSlideUp {\n from { opacity: 0; transform: translateY(20px) scale(0.98); }\n to { opacity: 1; transform: translateY(0) scale(1); }\n }\n\n .step {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n display: none;\n opacity: 0;\n }\n\n .step.active {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n animation: kpFadeIn 0.2s ease forwards;\n }\n\n .step.exiting {\n animation: kpFadeOut 0.15s ease forwards;\n }\n\n @keyframes kpFadeIn {\n from { opacity: 0; transform: translateY(6px); }\n to { opacity: 1; transform: translateY(0); }\n }\n\n @keyframes kpFadeOut {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n\n .kp-topbar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 20px;\n border-bottom: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .kp-topbar-brand {\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .kp-back-btn {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border-radius: 7px;\n background: rgba(255,255,255,0.04);\n border: 1px solid var(--kp-border);\n color: var(--kp-muted);\n cursor: pointer;\n transition: all 0.15s;\n flex-shrink: 0;\n margin-right: 4px;\n }\n\n .kp-back-btn:hover {\n background: rgba(255,255,255,0.08);\n color: var(--kp-text);\n border-color: rgba(255,255,255,0.12);\n }\n\n .kp-back-btn .material-symbols-outlined { font-size: 16px; }\n\n .kp-topbar-dot {\n width: 7px; height: 7px;\n border-radius: 50%;\n background: var(--kp-accent);\n box-shadow: 0 0 8px var(--kp-accent-glow);\n animation: kpPulse 2s ease infinite;\n }\n\n @keyframes kpPulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n\n .kp-topbar-name {\n font-size: 13px;\n font-weight: 600;\n color: var(--kp-text);\n letter-spacing: -0.01em;\n }\n\n .kp-topbar-secure {\n display: flex;\n align-items: center;\n gap: 5px;\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.04em;\n font-weight: 500;\n }\n\n .kp-topbar-secure .material-symbols-outlined {\n font-size: 13px;\n color: var(--kp-green);\n }\n\n .kp-amount-block {\n padding: 20px 20px 16px;\n border-bottom: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .kp-amount-label {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.08em;\n text-transform: uppercase;\n margin-bottom: 6px;\n font-weight: 500;\n }\n\n .kp-amount-value {\n font-size: 32px;\n font-weight: 700;\n color: var(--kp-text);\n letter-spacing: -0.03em;\n line-height: 1;\n }\n\n .kp-amount-hint {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-muted);\n margin-top: 6px;\n min-height: 16px;\n font-weight: 400;\n }\n\n .kp-amount-crypto {\n font-family: var(--kp-mono);\n font-size: 12px;\n color: var(--kp-accent);\n margin-top: 6px;\n min-height: 16px;\n transition: opacity 0.2s;\n font-weight: 500;\n }\n\n .kp-amount-crypto.loading { opacity: 0.4; }\n\n .progress-section {\n padding: 14px 20px 12px;\n border-bottom: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .progress-info {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 8px;\n }\n\n .progress-step {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.06em;\n font-weight: 500;\n }\n\n .progress-label {\n font-size: 11px;\n font-weight: 600;\n color: var(--kp-accent);\n letter-spacing: 0.02em;\n text-transform: uppercase;\n }\n\n .progress-bars { display: flex; width: 100%; gap: 5px; }\n\n .progress-bar {\n height: 2px;\n flex: 1;\n border-radius: 999px;\n background: var(--kp-surface-2);\n transition: background 0.3s ease;\n }\n\n .progress-bar.active {\n background: var(--kp-accent);\n box-shadow: 0 0 8px var(--kp-accent-glow);\n }\n\n .section-hint {\n font-size: 12px;\n color: var(--kp-muted);\n margin-bottom: 14px;\n line-height: 1.6;\n font-weight: 400;\n }\n\n .content-scroll {\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n padding: 16px 20px;\n -webkit-overflow-scrolling: touch;\n }\n\n .content-scroll::-webkit-scrollbar { width: 3px; }\n .content-scroll::-webkit-scrollbar-track { background: transparent; }\n .content-scroll::-webkit-scrollbar-thumb {\n background: rgba(99,102,241,0.2);\n border-radius: 10px;\n }\n\n .item-list {\n display: flex;\n flex-direction: column;\n gap: 6px;\n margin-bottom: 6px;\n }\n\n .kp-testnet-section { margin-top: 20px; }\n\n .kp-section-divider {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.08em;\n text-transform: uppercase;\n margin-bottom: 10px;\n padding-bottom: 8px;\n border-bottom: 1px solid var(--kp-border);\n font-weight: 500;\n }\n\n .list-item {\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--kp-surface);\n padding: 12px 14px;\n border-radius: 12px;\n border: 1px solid var(--kp-border);\n cursor: pointer;\n transition: all 0.15s;\n }\n\n .list-item:hover {\n border-color: var(--kp-border-active);\n background: var(--kp-accent-dim);\n transform: translateX(2px);\n }\n\n .item-icon {\n width: 36px; height: 36px;\n border-radius: 10px;\n display: flex; align-items: center; justify-content: center;\n background: var(--kp-surface-2);\n overflow: hidden;\n border: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .item-icon img { width: 22px; height: 22px; object-fit: contain; }\n .item-info { display: flex; flex-direction: column; flex: 1; }\n .item-name-row { display: flex; align-items: center; gap: 7px; }\n\n .item-name {\n font-size: 13px;\n font-weight: 600;\n color: var(--kp-text);\n }\n\n .item-badge {\n padding: 1px 6px;\n border-radius: 4px;\n font-size: 9px;\n font-weight: 600;\n font-family: var(--kp-mono);\n letter-spacing: 0.04em;\n text-transform: uppercase;\n }\n\n .badge-testnet {\n background: rgba(251,146,60,0.08);\n color: #fb923c;\n border: 1px solid rgba(251,146,60,0.2);\n }\n\n .item-desc {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n margin-top: 3px;\n font-weight: 400;\n }\n\n .item-chevron { color: var(--kp-muted); font-size: 16px; }\n\n .token-item {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 13px 14px;\n cursor: pointer;\n transition: all 0.15s;\n border: 1px solid var(--kp-border);\n border-radius: 12px;\n margin-bottom: 6px;\n background: var(--kp-surface);\n position: relative;\n overflow: hidden;\n }\n\n .token-item:last-child { margin-bottom: 0; }\n .token-item:hover { border-color: var(--kp-border-active); background: var(--kp-accent-dim); }\n .token-item.selected { background: var(--kp-accent-dim); border-color: var(--kp-accent); }\n .token-item.selected::after {\n content: '';\n position: absolute; inset: 0;\n background: linear-gradient(90deg, rgba(99,102,241,0.08) 0%, transparent 100%);\n pointer-events: none;\n }\n .token-item.selected .token-symbol { color: var(--kp-accent); }\n\n .token-left { display: flex; align-items: center; gap: 12px; flex: 1; }\n\n .token-icon {\n width: 36px; height: 36px;\n border-radius: 10px;\n background: var(--kp-surface-2);\n border: 1px solid var(--kp-border);\n overflow: hidden;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .token-icon img { width: 22px; height: 22px; object-fit: contain; }\n .token-info { display: flex; flex-direction: column; justify-content: center; }\n\n .token-symbol {\n color: var(--kp-text);\n font-size: 13px;\n font-weight: 600;\n line-height: 1;\n margin-bottom: 3px;\n transition: color 0.15s;\n }\n\n .token-name {\n font-family: var(--kp-mono);\n color: var(--kp-muted);\n font-size: 10px;\n line-height: 1;\n font-weight: 400;\n }\n\n .token-chevron { color: var(--kp-muted); font-size: 16px; flex-shrink: 0; }\n #kwespay-tokenList { display: flex; flex-direction: column; }\n\n .bottom-action {\n padding: 12px 20px 16px;\n background: var(--kp-bg);\n border-top: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .action-btn {\n width: 100%;\n padding: 13px;\n border-radius: 12px;\n background: var(--kp-accent);\n color: white;\n font-weight: 600;\n font-size: 14px;\n border: none;\n cursor: pointer;\n transition: all 0.15s;\n font-family: var(--kp-sans);\n letter-spacing: -0.01em;\n position: relative;\n overflow: hidden;\n }\n\n .action-btn::before {\n content: '';\n position: absolute; inset: 0;\n background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, transparent 60%);\n pointer-events: none;\n }\n\n .action-btn:hover { background: #5254cc; box-shadow: 0 0 20px var(--kp-accent-glow); }\n .action-btn:active { transform: scale(0.99); }\n\n .action-btn.secondary {\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n color: var(--kp-muted);\n }\n\n .action-btn.secondary::before { display: none; }\n .action-btn.secondary:hover {\n background: var(--kp-surface-2);\n border-color: var(--kp-border-active);\n color: var(--kp-text);\n box-shadow: none;\n }\n\n .action-btn:disabled { opacity: 0.3; cursor: not-allowed; box-shadow: none; }\n\n .kp-footer {\n padding: 10px 20px 12px;\n background: var(--kp-bg);\n border-top: 1px solid var(--kp-border);\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 6px;\n flex-shrink: 0;\n }\n\n .kp-footer-lock { font-size: 11px; color: var(--kp-green); }\n\n .kp-footer-text {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.02em;\n font-weight: 400;\n }\n\n .kp-footer-text span { color: var(--kp-text); font-weight: 500; }\n\n .loading-container {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 24px 20px;\n flex: 1;\n }\n\n .spinner-wrapper {\n position: relative;\n width: 64px; height: 64px;\n display: flex; align-items: center; justify-content: center;\n margin-bottom: 20px;\n }\n\n .spinner-ring {\n position: absolute;\n width: 64px; height: 64px;\n border-radius: 50%;\n border: 2px solid transparent;\n border-top-color: var(--kp-accent);\n animation: kpSpin 0.85s linear infinite;\n }\n\n .spinner-ring-2 {\n position: absolute;\n width: 48px; height: 48px;\n border-radius: 50%;\n border: 2px solid transparent;\n border-bottom-color: rgba(99,102,241,0.3);\n animation: kpSpin 1.2s linear infinite reverse;\n }\n\n @keyframes kpSpin { to { transform: rotate(360deg); } }\n\n .spinner-icon {\n z-index: 10;\n width: 32px; height: 32px;\n background: var(--kp-accent-dim);\n border-radius: 8px;\n display: flex; align-items: center; justify-content: center;\n border: 1px solid rgba(99,102,241,0.2);\n }\n\n .spinner-icon .material-symbols-outlined { font-size: 18px; color: var(--kp-accent); }\n\n .headline {\n color: var(--kp-text);\n font-size: 18px;\n font-weight: 700;\n line-height: 1.3;\n text-align: center;\n margin-bottom: 8px;\n letter-spacing: -0.02em;\n }\n\n .body-text {\n color: var(--kp-muted);\n font-size: 13px;\n line-height: 1.6;\n text-align: center;\n padding: 0 8px;\n margin-bottom: 8px;\n font-weight: 400;\n }\n\n .success-icon {\n width: 64px; height: 64px;\n border-radius: 16px;\n background: rgba(16,185,129,0.1);\n border: 1px solid rgba(16,185,129,0.2);\n display: flex; align-items: center; justify-content: center;\n margin-bottom: 16px;\n }\n\n .success-icon .material-symbols-outlined { font-size: 36px; color: var(--kp-green); }\n\n .error-icon {\n width: 64px; height: 64px;\n border-radius: 16px;\n background: rgba(244,63,94,0.1);\n border: 1px solid rgba(244,63,94,0.2);\n display: flex; align-items: center; justify-content: center;\n margin-bottom: 16px;\n }\n\n .error-icon .material-symbols-outlined { font-size: 36px; color: var(--kp-red); }\n\n .network-status { padding: 14px 20px 0; }\n\n .status-card {\n display: flex;\n align-items: center;\n gap: 10px;\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 10px;\n padding: 10px 14px;\n }\n\n .status-icon {\n width: 24px; height: 24px;\n border-radius: 6px;\n background: var(--kp-surface-2);\n overflow: hidden; flex-shrink: 0;\n display: flex; align-items: center; justify-content: center;\n }\n\n .status-icon img { width: 16px; height: 16px; object-fit: contain; }\n .status-text { color: var(--kp-accent); font-size: 12px; font-weight: 600; flex: 1; }\n\n .kp-review-body { flex: 1; overflow-y: auto; padding: 16px 20px; }\n .kp-review-body::-webkit-scrollbar { width: 3px; }\n .kp-review-body::-webkit-scrollbar-thumb { background: rgba(99,102,241,0.2); border-radius: 10px; }\n\n .kp-review-amount {\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n border-radius: 14px;\n padding: 18px;\n margin-bottom: 12px;\n text-align: center;\n }\n\n .kp-review-fiat {\n font-size: 28px;\n font-weight: 700;\n color: var(--kp-text);\n letter-spacing: -0.03em;\n line-height: 1;\n margin-bottom: 6px;\n }\n\n .kp-review-crypto-line {\n font-family: var(--kp-mono);\n font-size: 13px;\n color: var(--kp-accent);\n font-weight: 500;\n }\n\n .kp-review-crypto-line.loading { opacity: 0.4; }\n\n .kp-detail-block {\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n border-radius: 14px;\n overflow: hidden;\n margin-bottom: 10px;\n }\n\n .kp-detail-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 11px 16px;\n border-bottom: 1px solid var(--kp-border);\n }\n\n .kp-detail-row:last-child { border-bottom: none; }\n\n .kp-detail-key {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-muted);\n letter-spacing: 0.02em;\n font-weight: 400;\n }\n\n .kp-detail-val {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-text);\n font-weight: 500;\n text-align: right;\n }\n\n .kp-detail-val.accent { color: var(--kp-accent); }\n .kp-detail-val.green { color: var(--kp-green); }\n\n .kp-fee-block {\n background: rgba(16,185,129,0.04);\n border: 1px solid rgba(16,185,129,0.1);\n border-radius: 14px;\n overflow: hidden;\n margin-bottom: 10px;\n }\n\n .kp-fee-block .kp-detail-row { border-bottom-color: rgba(16,185,129,0.08); }\n\n .kp-fee-header {\n padding: 10px 16px;\n background: rgba(16,185,129,0.06);\n border-bottom: 1px solid rgba(16,185,129,0.1);\n display: flex; align-items: center; gap: 6px;\n }\n\n .kp-fee-header-text {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-green);\n letter-spacing: 0.06em;\n text-transform: uppercase;\n font-weight: 500;\n }\n\n .kp-fee-header .material-symbols-outlined { font-size: 13px; color: var(--kp-green); }\n\n .tx-details {\n width: 100%;\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n border-radius: 14px;\n overflow: hidden;\n margin-top: 16px;\n }\n\n .tx-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 10px 16px;\n border-bottom: 1px solid var(--kp-border);\n }\n\n .tx-row:last-child { border-bottom: none; }\n\n .tx-label { font-family: var(--kp-mono); color: var(--kp-muted); font-size: 10px; letter-spacing: 0.02em; font-weight: 400; }\n .tx-value { color: var(--kp-text); font-size: 11px; font-weight: 500; font-family: var(--kp-mono); }\n .tx-hash-row { display: flex; align-items: center; gap: 8px; }\n\n .explorer-link {\n display: flex; align-items: center; justify-content: center;\n width: 24px; height: 24px;\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 6px;\n cursor: pointer;\n transition: all 0.15s;\n flex-shrink: 0;\n }\n\n .explorer-link:hover { background: rgba(99,102,241,0.2); }\n .explorer-link .material-symbols-outlined { font-size: 12px; color: var(--kp-accent); }\n\n .mobile-instruction {\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 10px;\n padding: 12px;\n margin: 12px 0 0;\n display: flex;\n align-items: flex-start;\n gap: 10px;\n }\n\n .mobile-instruction-icon { color: var(--kp-accent); font-size: 18px; flex-shrink: 0; margin-top: 1px; }\n .mobile-instruction-text { flex: 1; }\n .mobile-instruction-title { color: var(--kp-text); font-size: 12px; font-weight: 600; margin-bottom: 3px; }\n .mobile-instruction-desc { color: var(--kp-muted); font-size: 11px; line-height: 1.5; font-weight: 400; }\n\n .kp-quote-timer {\n display: flex;\n align-items: center;\n gap: 5px;\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n margin-top: 6px;\n font-weight: 400;\n }\n\n .kp-quote-timer .material-symbols-outlined { font-size: 12px; }\n .kp-quote-timer.urgent { color: #fb923c; }\n .kp-quote-timer.expired { color: var(--kp-red); }\n\n @media (max-width: 480px) {\n .kwespay-overlay {\n padding: 0;\n align-items: flex-end;\n background: rgba(0,0,0,0.6);\n }\n\n .kwespay-close-btn { top: 14px; right: 14px; }\n\n .kwespay-container {\n width: 100vw;\n max-width: 100vw;\n height: calc(100vh - 120px);\n max-height: calc(100vh - 120px);\n min-height: 60vh;\n border-radius: 20px 20px 0 0;\n animation: kpSheetUp 0.32s cubic-bezier(0.16, 1, 0.3, 1) forwards;\n border-bottom: none;\n }\n\n .kwespay-container.closing {\n animation: kpSheetDown 0.28s ease forwards;\n }\n\n .kwespay-container::before {\n content: '';\n display: block;\n position: absolute;\n top: 8px; left: 50%;\n transform: translateX(-50%);\n width: 28px; height: 3px;\n border-radius: 2px;\n background: rgba(255,255,255,0.12);\n z-index: 10;\n }\n }\n\n\n.kp-mobile-connect-status {\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 12px;\n padding: 14px 16px;\n margin-bottom: 4px;\n}\n\n.kp-mobile-status-icon {\n width: 28px; height: 28px;\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0;\n}\n\n.kp-mobile-status-text { flex: 1; }\n\n.kp-mobile-status-title {\n font-size: 13px;\n font-weight: 600;\n color: var(--kp-text);\n margin-bottom: 2px;\n}\n\n.kp-mobile-status-desc {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-muted);\n}\n\n.kp-wallet-option:active {\n transform: scale(0.98);\n background: var(--kp-accent-dim);\n border-color: var(--kp-border-active);\n}\n\n\n @keyframes kpSheetUp {\n from { transform: translateY(100%); opacity: 0.8; }\n to { transform: translateY(0); opacity: 1; }\n }\n\n @keyframes kpSheetDown {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(100%); opacity: 0; }\n }\n",document.head.appendChild(e)}},_createWidgetDOM(){document.getElementById("kwespay-widget-overlay")?.remove();const e=document.createElement("div");e.className="kwespay-overlay",e.id="kwespay-widget-overlay";const t=document.createElement("button");t.className="kwespay-close-btn",t.innerHTML="×",t.onclick=()=>this.close(),e.appendChild(t);const n=document.createElement("div");var r,i;n.className="kwespay-container",n.id="kwespay-widget-container",n.innerHTML=(r=this.config.amount,i=this.config.currency,`\n <div class="step active" id="kwespay-step0">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="loading-container" style="flex:1">\n <div class="spinner-wrapper">\n <div class="spinner-ring"></div>\n <div class="spinner-ring-2"></div>\n <div class="spinner-icon">\n <span class="material-symbols-outlined">shield_lock</span>\n </div>\n </div>\n <h2 class="headline">Initializing</h2>\n <p class="body-text">Establishing a secure payment session.</p>\n </div>\n <div class="kp-footer">\n <span class="material-symbols-outlined kp-footer-lock" style="font-size:12px">lock</span>\n <span class="kp-footer-text">Powered by · <span>KwesPay</span></span>\n </div>\n </div>\n\n <div class="step" id="kwespay-step0-invalid">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot" style="background:var(--kp-red);box-shadow:none;animation:none"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="error-icon">\n <span class="material-symbols-outlined">wifi_off</span>\n </div>\n <h2 class="headline">Payment Unavailable</h2>\n <p class="body-text">We couldn't start your payment session. Please try again or contact the store for help.</p>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-retryInitBtn">Try Again</button>\n </div>\n </div>\n\n <div class="step" id="kwespay-step1">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="kp-amount-block">\n <div class="kp-amount-label">Total due</div>\n <div class="kp-amount-value" id="kwespay-paymentAmount">${r} ${i}</div>\n <div class="kp-amount-hint">Select a network to continue</div>\n </div>\n <div class="progress-section">\n <div class="progress-info">\n <span class="progress-step">01 / 03</span>\n <span class="progress-label">Select Network</span>\n </div>\n <div class="progress-bars">\n <div class="progress-bar active"></div>\n <div class="progress-bar"></div>\n <div class="progress-bar"></div>\n </div>\n </div>\n <div class="content-scroll">\n <p class="section-hint">Choose the blockchain network you want to pay on.</p>\n <div class="item-list" id="kwespay-mainnetList"></div>\n <div class="kp-testnet-section" id="kwespay-testnetSection" style="display:none">\n <div class="kp-section-divider">Testnets</div>\n <div class="item-list" id="kwespay-testnetList"></div>\n </div>\n </div>\n </div>\n\n <div class="step" id="kwespay-step2">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-back2">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="kp-amount-block">\n <div class="kp-amount-label">Total due</div>\n <div class="kp-amount-value">${r} ${i}</div>\n <div class="kp-amount-hint">Select a token — exact amount shown at review</div>\n </div>\n <div class="progress-section">\n <div class="progress-info">\n <span class="progress-step">02 / 03</span>\n <span class="progress-label">Select Token</span>\n </div>\n <div class="progress-bars">\n <div class="progress-bar active"></div>\n <div class="progress-bar active"></div>\n <div class="progress-bar"></div>\n </div>\n </div>\n <div class="network-status">\n <div class="status-card">\n <div class="status-icon" id="kwespay-selectedNetworkIcon"></div>\n <p class="status-text" id="kwespay-selectedNetworkName">—</p>\n <span class="material-symbols-outlined" style="color:var(--kp-accent);font-size:15px">check_circle</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:10px">\n <p class="section-hint">Select the token you want to pay with. The exact crypto amount will be confirmed on the next screen.</p>\n <div id="kwespay-tokenList"></div>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-continueToWalletConnect" disabled>Connect Wallet</button>\n </div>\n </div>\n\n <div class="step" id="kwespay-step3">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-back3">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="progress-section">\n <div class="progress-info">\n <span class="progress-step">03 / 03</span>\n <span class="progress-label">Review & Pay</span>\n </div>\n <div class="progress-bars">\n <div class="progress-bar active"></div>\n <div class="progress-bar active"></div>\n <div class="progress-bar active"></div>\n </div>\n </div>\n <div class="kp-review-body">\n <div class="kp-review-amount">\n <div class="kp-review-fiat" id="kwespay-reviewFiatAmount">${r} ${i}</div>\n <div class="kp-review-crypto-line" id="kwespay-reviewCryptoLine">Fetching live quote…</div>\n <div class="kp-quote-timer" id="kwespay-quoteTimer" style="display:none;justify-content:center">\n <span class="material-symbols-outlined">schedule</span>\n <span id="kwespay-quoteTimerText">—</span>\n </div>\n </div>\n\n <div class="kp-detail-block">\n <div class="kp-detail-row">\n <span class="kp-detail-key">wallet</span>\n <span class="kp-detail-val" id="kwespay-connectedWalletAddress">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">network</span>\n <span class="kp-detail-val" id="kwespay-summaryNetwork">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">token</span>\n <span class="kp-detail-val accent" id="kwespay-summaryToken">—</span>\n </div>\n </div>\n\n <div class="kp-fee-block">\n <div class="kp-fee-header">\n <span class="material-symbols-outlined">receipt_long</span>\n <span class="kp-fee-header-text">Fee Breakdown</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">payment amount</span>\n <span class="kp-detail-val" id="kwespay-feePaymentAmount">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">platform fee (0.25%)</span>\n <span class="kp-detail-val" id="kwespay-feePlatformFee">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">vendor receives</span>\n <span class="kp-detail-val green" id="kwespay-feeVendorAmount">—</span>\n </div>\n </div>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-proceedToPayment">Pay Now</button>\n <button class="action-btn secondary" style="margin-top:8px" id="kwespay-cancelConnection">Cancel</button>\n </div>\n </div>\n\n <div class="step" id="kwespay-step4">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="spinner-wrapper">\n <div class="spinner-ring"></div>\n <div class="spinner-ring-2"></div>\n <div class="spinner-icon">\n <span class="material-symbols-outlined">payments</span>\n </div>\n </div>\n <h2 class="headline" id="kwespay-processingTitle">Processing Payment</h2>\n <p class="body-text" id="kwespay-processingText">Waiting for wallet confirmation.</p>\n <div class="mobile-instruction" id="kwespay-mobileTransactionInstruction" style="display:none">\n <span class="material-symbols-outlined mobile-instruction-icon">phone_iphone</span>\n <div class="mobile-instruction-text">\n <div class="mobile-instruction-title">Check Your Wallet App</div>\n <div class="mobile-instruction-desc">A confirmation request has been sent to your wallet. Tap Approve to complete the payment.</div>\n </div>\n </div>\n </div>\n </div>\n\n <div class="step" id="kwespay-step5">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot" style="background:var(--kp-green);box-shadow:0 0 8px rgba(16,185,129,0.4);animation:none"></div>\n <span class="kp-topbar-name">Payment Complete</span>\n </div>\n <div class="kp-topbar-secure">\n <span class="material-symbols-outlined" style="color:var(--kp-green)">check_circle</span>\n CONFIRMED\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="success-icon">\n <span class="material-symbols-outlined">check_circle</span>\n </div>\n <h2 class="headline">Payment Successful</h2>\n <p class="body-text">Your transaction has been confirmed on-chain.</p>\n <div class="tx-details">\n <div class="tx-row">\n <span class="tx-label">tx hash</span>\n <div class="tx-hash-row">\n <span class="tx-value" id="kwespay-txHash">—</span>\n <a class="explorer-link" id="kwespay-explorerLink" target="_blank" rel="noopener noreferrer">\n <span class="material-symbols-outlined">open_in_new</span>\n </a>\n </div>\n </div>\n <div class="tx-row">\n <span class="tx-label">amount paid</span>\n <span class="tx-value" id="kwespay-txFiatAmount">${r} ${i}</span>\n </div>\n <div class="tx-row">\n <span class="tx-label">crypto amount</span>\n <span class="tx-value" id="kwespay-txCryptoAmount">—</span>\n </div>\n <div class="tx-row">\n <span class="tx-label">network</span>\n <span class="tx-value" id="kwespay-txNetwork">—</span>\n </div>\n </div>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-closeSuccessBtn">Done</button>\n </div>\n <div class="kp-footer">\n <span class="material-symbols-outlined kp-footer-lock" style="font-size:12px">lock</span>\n <span class="kp-footer-text">Secured by <span>KwesPay</span> · On-chain verified</span>\n </div>\n </div>\n\n <div class="step" id="kwespay-step6">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot" style="background:var(--kp-red);box-shadow:none;animation:none"></div>\n <span class="kp-topbar-name">Payment Failed</span>\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="error-icon">\n <span class="material-symbols-outlined">error</span>\n </div>\n <h2 class="headline" id="kwespay-errorTitle">Something went wrong</h2>\n <p class="body-text" id="kwespay-errorMessage">An error occurred while processing your payment.</p>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-retryPayment">Try Again</button>\n <button class="action-btn secondary" style="margin-top:8px" id="kwespay-backToStartBtn">Start Over</button>\n </div>\n </div>\n `),e.appendChild(n),document.body.appendChild(e),this._setupEventListeners(),this._setupSwipeToClose(n)},_setupSwipeToClose(e){let t=0,n=0,r=!1;e.addEventListener("touchstart",i=>{const s=i.touches[0];s.clientY-e.getBoundingClientRect().top<=40&&(t=s.clientY,n=s.clientY,r=!0,e.style.transition="none")},{passive:!0}),e.addEventListener("touchmove",i=>{if(!r)return;n=i.touches[0].clientY;const s=n-t;s>0&&(e.style.transform=`translateY(${s}px)`)},{passive:!0}),e.addEventListener("touchend",()=>{if(!r)return;r=!1,e.style.transition="";n-t>120?this.close():e.style.transform="translateY(0)"})},_setupEventListeners(){document.getElementById("kwespay-retryInitBtn")?.addEventListener("click",()=>this._validateAPIKey()),this._renderNetworkList(),document.getElementById("kwespay-back2")?.addEventListener("click",()=>{this.state.selectedToken=null,this.state.selectedTokenConfig=null;const e=document.getElementById("kwespay-continueToWalletConnect");e&&(e.disabled=!0),this._goToStep(1)}),document.getElementById("kwespay-back3")?.addEventListener("click",async()=>{await this.walletService.disconnect(),this._clearQuoteTimer(),this._goToStep(2)}),document.getElementById("kwespay-continueToWalletConnect")?.addEventListener("click",async()=>{await this._handleWalletConnection()}),document.getElementById("kwespay-proceedToPayment")?.addEventListener("click",async()=>{await this._handlePaymentProcessing()}),document.getElementById("kwespay-cancelConnection")?.addEventListener("click",async()=>{await this.walletService.disconnect(),this._clearQuoteTimer(),Tx("paymentCancelled",{reason:"user_cancelled_review"}),this._goToStep(1)}),document.getElementById("kwespay-retryPayment")?.addEventListener("click",async()=>{this.walletService.isConnected()?(await this._loadReviewStep(),this._goToStep(3)):await this._handleWalletConnection()}),document.getElementById("kwespay-closeSuccessBtn")?.addEventListener("click",()=>this.close()),document.getElementById("kwespay-backToStartBtn")?.addEventListener("click",()=>{Tx("paymentCancelled",{reason:"user_started_over"}),this._reset(),this._goToStep(1)});const e=document.getElementById("kwespay-networkSearch");e&&e.addEventListener("input",e=>{const t=e.target.value.toLowerCase();document.querySelectorAll(".kwespay-container .list-item").forEach(e=>{const n=e.querySelector(".item-name")?.textContent.toLowerCase();n&&(e.style.display=n.includes(t)?"flex":"none")})});const t=document.getElementById("kwespay-tokenSearch");t&&t.addEventListener("input",e=>{const t=e.target.value.toLowerCase();document.querySelectorAll("#kwespay-tokenList .token-item").forEach(e=>{const n=e.querySelector(".token-name")?.textContent.toLowerCase(),r=e.querySelector(".token-symbol")?.textContent.toLowerCase();n&&r&&(e.style.display=n.includes(t)||r.includes(t)?"flex":"none")})})}},Rx={_goToStep(e){document.querySelectorAll(".kwespay-container .step").forEach(e=>e.classList.remove("active","exiting")),this._activateStep(e),this.state.currentStep=e},_activateStep(e){let t;t=.5===e?document.getElementById("kwespay-step0-invalid"):"string"==typeof e?document.getElementById(`kwespay-step-${e}`):document.getElementById(`kwespay-step${e}`),t?t.classList.add("active"):console.warn(`[KwesPayWidget] Step not found: ${e}`)},_removeCustomStep(e){document.getElementById(e)?.remove()},_showError(e,t){const n=document.getElementById("kwespay-errorTitle"),r=document.getElementById("kwespay-errorMessage");n&&(n.textContent=e),r&&(r.textContent=t),this._goToStep(6)},_reset(){this._clearQuoteTimer(),this._removeCustomStep("kwespay-step-wallet-picker"),this._removeCustomStep("kwespay-step-wc"),this.state.selectedNetwork=null,this.state.selectedNetworkName="",this.state.selectedChainId=null,this.state.selectedRpcUrl=null,this.state.selectedContractAddress=null,this.state.selectedToken=null,this.state.selectedTokenConfig=null,this.state.currentPayload=null,this.state.wcUri=null}},Bx={async _validateAPIKey(){try{const e=await this.paymentService.validateAPIKey();e.valid?(this.state.vendorInfo=e.vendorInfo,this.state.keyAllowedNetworks=e.allowedNetworks??null,this.state.keyAllowedTokens=e.allowedTokens??null,this._goToStep(1),Tx("apiKeyValidated",{vendorInfo:this.state.vendorInfo})):(this._goToStep(.5),Tx("apiKeyInvalid",{}))}catch(e){console.error("[KwesPayWidget] API key validation error:",e.message),this._goToStep(.5),Tx("apiKeyError",{error:e.message})}}},Mx={_renderNetworkList(){const e=document.getElementById("kwespay-mainnetList"),t=document.getElementById("kwespay-testnetList"),n=document.getElementById("kwespay-testnetSection");if(!e||!t)return;e.innerHTML="",t.innerHTML="";const r=this.state.keyAllowedNetworks?new Set(this.state.keyAllowedNetworks.map(e=>e.toLowerCase())):null,o=this._effectiveAllowedTokens();let a=!1;Object.entries(i).forEach(([n,i])=>{if(r&&!r.has(n.toLowerCase()))return;if(o){const e=(s[n]||[]).map(e=>e.symbol.toUpperCase());if(!o.some(t=>e.includes(t)))return}const c=document.createElement("div");c.className="list-item",c.innerHTML=`\n <div class="item-icon"><img src="${i.logo}" alt="${i.name}" /></div>\n <div class="item-info">\n <div class="item-name-row">\n <p class="item-name">${i.name}</p>\n ${"testnet"===i.type?'<span class="item-badge badge-testnet">Testnet</span>':""}\n </div>\n <p class="item-desc">${"mainnet"===i.type?"Mainnet · Production":"Testnet · Development"}</p>\n </div>\n <span class="material-symbols-outlined item-chevron">chevron_right</span>\n `,c.addEventListener("click",()=>this._handleNetworkSelection(n,i)),"mainnet"===i.type?e.appendChild(c):(t.appendChild(c),a=!0)}),n&&(n.style.display=a?"block":"none")},_renderTokenList(){if(!this.state.selectedNetwork)return;const e=document.getElementById("kwespay-tokenList");if(!e)return;const t=this._effectiveAllowedTokens();let n=s[this.state.selectedNetwork]||[];t&&(n=n.filter(e=>t.includes(e.symbol.toUpperCase()))),e.innerHTML="",0!==n.length?n.forEach(t=>{const n=document.createElement("div");n.className="token-item",n.setAttribute("data-token-symbol",t.symbol),n.innerHTML=`\n <div class="token-left">\n <div class="token-icon"><img src="${t.icon}" alt="${t.symbol}" /></div>\n <div class="token-info">\n <p class="token-symbol">${t.symbol}</p>\n <p class="token-name">${t.name}</p>\n </div>\n </div>\n <span class="material-symbols-outlined token-chevron">chevron_right</span>\n `,n.addEventListener("click",()=>this._handleTokenSelection(t)),e.appendChild(n)}):e.innerHTML='<div style="text-align:center;padding:24px;font-family:var(--kp-mono);font-size:11px;color:var(--kp-muted)">No accepted tokens on this network.</div>'},_effectiveAllowedTokens(){const e=this.state.keyAllowedTokens?.map(e=>e.toUpperCase())??null,t=this.config.acceptedTokens;return e||t?e?t?e.filter(e=>t.includes(e)):e:t:null},async _handleNetworkSelection(e,t){this.state.selectedNetwork=e,this.state.selectedNetworkName=t.name,this.state.selectedChainId=t.chainId,this.state.selectedRpcUrl=t.rpcUrl,this.state.selectedContractAddress=t.contractAddress,this.state.selectedToken=null,this.state.selectedTokenConfig=null;const n=document.getElementById("kwespay-selectedNetworkName");n&&(n.textContent=`${t.name} ${"mainnet"===t.type?"Mainnet":"Testnet"}`);const r=document.getElementById("kwespay-selectedNetworkIcon");r&&(r.innerHTML=`<img src="${t.logo}" alt="${t.name}" />`);const i=document.getElementById("kwespay-continueToWalletConnect");i&&(i.disabled=!0),this._renderTokenList(),this._goToStep(2)},_handleTokenSelection(e){document.querySelectorAll("#kwespay-tokenList .token-item").forEach(e=>e.classList.remove("selected")),document.querySelector(`#kwespay-tokenList .token-item[data-token-symbol="${e.symbol}"]`)?.classList.add("selected"),this.state.selectedToken=e.symbol,this.state.selectedTokenConfig=e;const t=document.getElementById("kwespay-continueToWalletConnect");t&&(t.disabled=!1)}},Ux={async _handleWalletConnection(){this.state.selectedToken&&this.state.selectedTokenConfig?this._renderWalletPickerStep():alert("Please select a token first")},_renderWalletPickerStep(){this._removeCustomStep("kwespay-step-wallet-picker");const e=document.getElementById("kwespay-widget-container"),t=document.createElement("div");t.className="step",t.id="kwespay-step-wallet-picker",t.innerHTML=`\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-picker-back">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">Connect Wallet</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:16px">\n <p class="section-hint">Choose how to connect your wallet.</p>\n <div class="item-list" id="kwespay-injected-list">\n <div style="text-align:center;padding:12px;font-family:var(--kp-mono);font-size:11px;color:var(--kp-muted)">Detecting wallets…</div>\n </div>\n <div class="kp-section-divider" style="margin-top:20px">Or scan QR code</div>\n <div class="item-list" id="kwespay-wc-list">\n <div class="list-item" id="kwespay-wc-option" style="cursor:pointer">\n <div class="item-icon" style="background:transparent">\n <svg width="22" height="22" viewBox="0 0 22 22" fill="none">\n <path d="M4 4C7.3 1 14.7 1 18 4C18 4 15 7.5 11 7.5C7 7.5 4 4 4 4Z" fill="#3396FF"/>\n <path d="M4 4C4 4 6.5 9 11 9C15.5 9 18 4 18 4" stroke="#3396FF" stroke-width="1.5" fill="none"/>\n <path d="M7.5 10L9.5 14L11 11L12.5 14L14.5 10" stroke="#3396FF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </div>\n <div class="item-info">\n <div class="item-name-row"><p class="item-name">WalletConnect</p></div>\n <p class="item-desc">${_x()?"Open your mobile wallet":"Scan QR with any wallet"}</p>\n </div>\n <span class="material-symbols-outlined item-chevron">chevron_right</span>\n </div>\n </div>\n </div>\n `,e.appendChild(t),t.querySelector("#kwespay-picker-back")?.addEventListener("click",()=>{this._removeCustomStep("kwespay-step-wallet-picker"),this._goToStep(2)}),t.querySelector("#kwespay-wc-option")?.addEventListener("click",()=>{this._removeCustomStep("kwespay-step-wallet-picker"),this._startWalletConnect()}),this._goToStep("wallet-picker"),this.walletService.discoverInjectedWallets().then(e=>{const t=document.getElementById("kwespay-injected-list");t&&(t.innerHTML="",0!==e.length?e.forEach((e,n)=>{const r=e.info.icon?`<img src="${e.info.icon}" alt="${e.info.name}" style="width:22px;height:22px;object-fit:contain;border-radius:6px">`:'<span class="material-symbols-outlined" style="font-size:18px;color:var(--kp-accent)">account_balance_wallet</span>',i=document.createElement("div");i.className="list-item",i.style.cursor="pointer",i.innerHTML=`\n <div class="item-icon">${r}</div>\n <div class="item-info">\n <div class="item-name-row"><p class="item-name">${e.info.name}</p></div>\n <p class="item-desc">Browser extension</p>\n </div>\n <span class="material-symbols-outlined item-chevron">chevron_right</span>\n `,i.addEventListener("click",async()=>{this._removeCustomStep("kwespay-step-wallet-picker"),await this._connectInjectedProvider(n)}),t.appendChild(i)}):t.innerHTML='<div style="text-align:center;padding:12px;font-family:var(--kp-mono);font-size:11px;color:var(--kp-muted)">No browser wallet detected.</div>')})},async _connectInjectedProvider(e){try{const t=await this.walletService.connectInjected(e);await this._onWalletConnected(t)}catch(e){if("USER_CANCELLED"===e.code||4001===e.code)return;console.error("[KwesPayWidget] Injected connect error:",e.message),this._showError("Connection Failed",e.message||"Could not connect wallet."),Tx("walletConnectionError",{error:e.message})}},async _startWalletConnect(){this._renderWCStep();try{await this.walletService.initWalletConnect(e=>this._onWCUri(e),()=>this._onWCConnected(),()=>this._onWCDisconnected()),_x()&&this._renderWCMobileStep(),await this.walletService.connectWalletConnect(this.state.selectedChainId)}catch(e){if(e.message?.includes("User rejected")||e.message?.includes("cancelled"))return;console.error("[KwesPayWidget] WC connect error:",e.message),this._showError("Connection Failed",e.message||"WalletConnect failed.")}},_renderWCStep(){this._removeCustomStep("kwespay-step-wc");const e=document.getElementById("kwespay-widget-container"),t=document.createElement("div");t.className="step",t.id="kwespay-step-wc",t.innerHTML=_x()?this._wcMobileHTML():this._wcDesktopHTML(),e.appendChild(t),t.querySelector("#kwespay-wc-back")?.addEventListener("click",async()=>{await this.walletService.disconnect(),this._removeCustomStep("kwespay-step-wc"),this._renderWalletPickerStep()}),t.querySelector("#kwespay-wc-copy")?.addEventListener("click",()=>{if(this.state.wcUri){navigator.clipboard.writeText(this.state.wcUri).catch(()=>{});const e=document.getElementById("kwespay-wc-copy");e&&(e.textContent="Copied!"),setTimeout(()=>{e&&(e.textContent="Copy URI")},2e3)}}),this._goToStep("wc")},_wcDesktopHTML:()=>'\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-wc-back">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">Scan QR Code</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:16px;display:flex;flex-direction:column;align-items:center;gap:16px">\n <p class="section-hint" style="text-align:center">Open any WalletConnect-compatible wallet app and scan the code below.</p>\n <div id="kwespay-qr-canvas" style="width:220px;height:220px;background:white;border-radius:12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--kp-border)">\n <p style="font-size:11px;color:#888;font-family:var(--kp-mono)">Generating QR…</p>\n </div>\n <button class="action-btn secondary" id="kwespay-wc-copy" style="width:auto;padding:8px 20px;font-size:12px">Copy URI</button>\n <p style="font-size:11px;color:var(--kp-muted);font-family:var(--kp-mono);text-align:center">Waiting for wallet connection…</p>\n </div>\n ',_wcMobileHTML(){const e=this.walletService.getMobileWallets().map((e,t)=>`\n <div class="list-item kp-wallet-option" data-index="${t}" style="cursor:pointer">\n <div class="item-icon">\n <img src="${e.icon}" alt="${e.name}" style="width:22px;height:22px;object-fit:contain;border-radius:6px" onerror="this.style.display='none'">\n </div>\n <div class="item-info">\n <div class="item-name-row"><p class="item-name">${e.name}</p></div>\n <p class="item-desc">Tap to open and approve</p>\n </div>\n <span class="material-symbols-outlined item-chevron">open_in_new</span>\n </div>\n `).join("");return`\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-wc-back">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">Connect Wallet</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:16px">\n <div class="kp-mobile-connect-status" id="kwespay-wc-status-card">\n <div class="kp-mobile-status-icon">\n <div class="spinner-ring" style="width:20px;height:20px;border-width:2px"></div>\n </div>\n <div class="kp-mobile-status-text">\n <p class="kp-mobile-status-title">Preparing connection</p>\n <p class="kp-mobile-status-desc" id="kwespay-wc-status">This only takes a moment…</p>\n </div>\n </div>\n <p class="section-hint" style="margin-top:16px">Choose your wallet app to connect.</p>\n <div class="item-list" id="kwespay-mobile-wallet-list">${e}</div>\n <p style="font-size:10px;color:var(--kp-muted);font-family:var(--kp-mono);text-align:center;margin-top:16px;line-height:1.6">\n After approving in your wallet, return here to complete payment.\n </p>\n </div>\n `},_renderWCMobileStep(){const e=document.getElementById("kwespay-mobile-wallet-list");e&&e.querySelectorAll(".kp-wallet-option").forEach(e=>{const t=parseInt(e.getAttribute("data-index"),10),n=this.walletService.getMobileWallets()[t];e.addEventListener("click",()=>{if(!this.state.wcUri){const e=document.getElementById("kwespay-wc-status");return void(e&&(e.textContent="Still connecting — please wait…"))}const e=n.universalLink(this.state.wcUri);this.walletService.isIOS()?window.location.href=e:window.open(e,"_blank","noreferrer noopener")})})},_onWCUri(e){if(this.state.wcUri=e,_x()){const e=document.getElementById("kwespay-wc-status"),t=document.querySelector(".kp-mobile-status-title"),n=document.querySelector(".kp-mobile-status-icon");e&&(e.textContent="Ready. Tap a wallet below to connect."),t&&(t.textContent="Connection ready"),n&&(n.innerHTML='<span class="material-symbols-outlined" style="font-size:18px;color:var(--kp-accent)">check_circle</span>')}else this._renderQRCode(e)},_renderQRCode(e){const t=document.getElementById("kwespay-qr-canvas");if(t){if("undefined"!=typeof QRCode)return t.innerHTML="",void new QRCode(t,{text:e,width:200,height:200,colorDark:"#000000",colorLight:"#ffffff",correctLevel:QRCode.CorrectLevel.M});if(void 0!==window.qrcode){const n=window.qrcode(0,"M");return n.addData(e),n.make(),void(t.innerHTML=n.createImgTag(3))}t.innerHTML=`\n <div style="display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px">\n <p style="font-size:10px;color:#888;font-family:monospace;word-break:break-all;text-align:center;max-width:180px">${e.slice(0,80)}…</p>\n <p style="font-size:10px;color:#888;font-family:monospace">Use Copy URI button</p>\n </div>\n `}},_onWCConnected(){const e=this.walletService._connectionResult();this._removeCustomStep("kwespay-step-wc"),this._onWalletConnected(e)},_onWCDisconnected(){this._removeCustomStep("kwespay-step-wc"),this._goToStep(2)},async _onWalletConnected(e){const t=document.getElementById("kwespay-connectedWalletAddress");t&&(t.textContent=e.shortAddress);const n=document.getElementById("kwespay-summaryNetwork");n&&(n.textContent=this.state.selectedNetworkName);const r=document.getElementById("kwespay-summaryToken");r&&(r.textContent=this.state.selectedToken);const i=document.getElementById("kwespay-reviewCryptoLine"),s=document.getElementById("kwespay-quoteTimer"),o=document.getElementById("kwespay-proceedToPayment");i&&(i.textContent="loading…",i.classList.add("loading")),s&&(s.style.display="none"),o&&(o.disabled=!0),this._goToStep(3);try{await this._loadReviewStep()}catch(e){console.error("[KwesPayWidget] Quote load failed after wallet connect:",e.message),i&&(i.textContent="Could not load rate — please try again.",i.classList.remove("loading"))}Tx("walletConnected",{address:e.address})}};function Lx(e,t){const n=BigInt(10**t),r=e/n,i=e%n;if(0n===i)return`${r}`;const s=i.toString().padStart(t,"0");if(r>0n){const e=s.slice(0,4).replace(/0+$/,"");return e?`${r}.${e}`:`${r}`}let o=-1;for(let e=0;e<s.length;e++)if("0"!==s[e]){o=e;break}if(-1===o)return`${r}`;const a=s.slice(o,o+4).replace(/0+$/,"");return`0.${s.slice(0,o)+a}`}const Dx={async _loadReviewStep(){this._clearQuoteTimer();const e=document.getElementById("kwespay-reviewCryptoLine"),t=document.getElementById("kwespay-quoteTimer"),n=document.getElementById("kwespay-feePaymentAmount"),r=document.getElementById("kwespay-feePlatformFee"),i=document.getElementById("kwespay-feeVendorAmount"),s=document.getElementById("kwespay-proceedToPayment");e&&(e.textContent="loading…",e.classList.add("loading")),t&&(t.style.display="none"),s&&(s.disabled=!0);try{const t=await this.paymentService.getQuote({vendorId:this.config.vendorId,cryptoCurrency:this.state.selectedToken,fiatAmount:this.config.amount,fiatCurrency:this.config.currency,network:this.state.selectedNetwork,payerWalletAddress:this.walletService.getAddress()});this.state.currentPayload=t;const o=this.state.selectedTokenConfig?.decimals??6,a=BigInt(t.amountBaseUnits),c=25*Number(a)/1e4,l=BigInt(Math.max(1,Math.round(c))),d=a-l,h=this.state.selectedToken,u=e=>`${Lx(e,o)} ${h}`;e&&(e.textContent=u(a),e.classList.remove("loading")),n&&(n.textContent=u(a)),r&&(r.textContent=u(l)),i&&(i.textContent=u(d<0n?0n:d)),s&&(s.disabled=!1),this._startQuoteTimer(t.expiresAt)}catch(t){console.error("[KwesPayWidget] Quote fetch failed:",t.message),e&&(e.textContent="Could not load rate — please try again.",e.classList.remove("loading")),s&&(s.disabled=!0)}},_startQuoteTimer(e){const t=document.getElementById("kwespay-quoteTimer"),n=document.getElementById("kwespay-quoteTimerText");if(!t||!n)return;t.style.display="flex";const r=()=>{const r=Math.max(0,new Date(e).getTime()-Date.now()),i=Math.ceil(r/1e3),s=Math.floor(i/60),o=i%60;if(n.textContent=`Price locks in ${s}:${String(o).padStart(2,"0")}`,t.className="kp-quote-timer"+(i<=30?" urgent":"")+(i<=0?" expired":""),i<=0){n.textContent="Refreshing your rate…";const e=document.getElementById("kwespay-proceedToPayment");e&&(e.disabled=!0),this._clearQuoteTimer(),this._loadReviewStep()}};r(),this.state.quoteTimerInterval=setInterval(r,1e3)},_clearQuoteTimer(){this.state.quoteTimerInterval&&(clearInterval(this.state.quoteTimerInterval),this.state.quoteTimerInterval=null)}},jx={async _handlePaymentProcessing(){if(this.state.currentPayload)try{this._clearQuoteTimer(),this._goToStep(4);const e=(e,t)=>{const n=document.getElementById("kwespay-processingTitle"),r=document.getElementById("kwespay-processingText");n&&(n.textContent=e),r&&(r.textContent=t)},t="walletconnect"===this.walletService.connectionType,n=this.walletService.isMobile(),r=t&&n,s=this.walletService.getProvider(),o=this.state.selectedChainId;if(!s)throw new Error("No wallet provider");if(!await this.walletService.isSessionAlive()){console.error("[KwesPay] Session liveness check failed — session appears stale"),await this.walletService.disconnect();const e=new Error("Your wallet session expired. Please reconnect your wallet.");throw e.code="SESSION_EXPIRED",e}if(n&&document.getElementById("kwespay-mobileTransactionInstruction")?.style.setProperty("display","flex"),r)await this._assertMobileChain(s,o);else{const t=await s.request({method:"eth_chainId"}),n=parseInt(t,16);console.log("[KwesPay] Desktop chain check —",{currentChainId:n,targetChainId:o}),n!==o&&(e("Switching network…","Approve the network change in your wallet."),await this._switchNetworkSafe(o,this.state.selectedNetworkName,this.state.selectedRpcUrl,this.state.selectedToken,this.state.selectedTokenConfig.decimals),console.log("[KwesPay] Network switched"))}r?(e("Opening your wallet…","Approve the payment in your wallet."),this.walletService._openWalletForApproval(),await new Promise(e=>setTimeout(e,700))):e("Waiting for approval…","Confirm the transaction in your wallet.");const a=await this.paymentService.createPayment({payload:this.state.currentPayload,walletProvider:s,onStatusUpdate:e});document.getElementById("kwespay-mobileTransactionInstruction")?.style.setProperty("display","none");const c=this.state.selectedTokenConfig?.decimals??6,l=`${Lx(BigInt(this.state.currentPayload.amountBaseUnits),c)} ${this.state.selectedToken}`;document.getElementById("kwespay-txHash").textContent=function(e,t=10,n=8){return e?`${e.slice(0,t)}...${e.slice(-n)}`:""}(a.hash),document.getElementById("kwespay-txFiatAmount").textContent=`${this.config.amount} ${this.config.currency}`,document.getElementById("kwespay-txCryptoAmount").textContent=l,document.getElementById("kwespay-txNetwork").textContent=this.state.selectedNetworkName,document.getElementById("kwespay-explorerLink").href=i[this.state.selectedNetwork].explorer+a.hash,this._goToStep(5),Tx("paymentSuccess",{transactionReference:a.transactionReference,paymentIdBytes32:a.paymentIdBytes32,transactionHash:a.hash,fiatAmount:this.config.amount,currency:this.config.currency,token:this.state.selectedToken,network:this.state.selectedNetwork})}catch(e){console.error("[KwesPay] Payment error —",e.code??"UNKNOWN",":",e.message),document.getElementById("kwespay-mobileTransactionInstruction")?.style.setProperty("display","none");const t=Ox(e);let n="Payment Failed",r=function(e,t={}){const n=Ox(e);switch(console.error("[KwesPay] Payment error breakdown:",{errorType:n,message:e?.message,code:e?.code,data:e?.data,reason:e?.reason,stack:e?.stack,raw:e,context:t}),e?.data&&console.error("[KwesPay] Contract revert data:",e.data),e?.transaction&&console.error("[KwesPay] Failed tx details:",e.transaction),e?.receipt&&console.error("[KwesPay] Tx receipt:",e.receipt),n){case"USER_REJECTED":return"You cancelled the transaction in your wallet.";case"INSUFFICIENT_BALANCE":return`Not enough ${t.token||"funds"} to complete this payment.`;case"CONNECTION_REJECTED":return"Wallet connection was cancelled.";case"TIMEOUT":return"Connection timed out. Please try again.";default:return e?.reason||e?.message||"Something went wrong while processing your payment."}}(e,{token:this.state.selectedToken});"SESSION_EXPIRED"===e.code?(n="Session Expired",r=e.message):"WRONG_NETWORK"===e.code?(n="Wrong Network",r=e.message):"USER_REJECTED"===t?(n="Transaction Cancelled",r="You rejected the transaction in your wallet."):"INSUFFICIENT_BALANCE"===t&&(n="Insufficient Balance"),this._showError(n,r),Tx("paymentError",{error:r,errorType:t})}else this._showError("Payment Error","Something went wrong. Please go back and try again.")},async _assertMobileChain(e,t){for(let r=1;r<=3;r++){let i=null;try{const t=await e.request({method:"eth_chainId"});i=parseInt(t,16)}catch(n){console.error(`[KwesPay] eth_chainId RPC failed (attempt ${r}/3):`,n.message)}if(console.log(`[KwesPay] Chain check attempt ${r}/3 —`,{currentChainId:i,targetChainId:t}),i===t)return void console.log("[KwesPay] Chain confirmed ✅",i);r<3&&await new Promise(e=>setTimeout(e,1e3))}const n=new Error(`Please switch to ${this.state.selectedNetworkName} in your wallet and try again.`);throw n.code="WRONG_NETWORK",n},async _switchNetworkSafe(e,t,n,r,i){const s=this.walletService.switchNetwork,o=this.walletService.getProvider();if(!o)throw new Error("[WalletService] No provider connected");const a=e=>{if(null==e)return null;try{const t="string"==typeof e?e.startsWith("0x")?parseInt(e,16):parseInt(e,10):Number(e);return isNaN(t)?null:"0x"+t.toString(16)}catch{return null}},c=a(e);try{const e=a(await o.request({method:"eth_chainId"}));if(e&&e===c)return}catch(e){console.warn("[KwesPay] Could not read chainId before switch:",e.message)}try{await s(e,t,n,r,i)}catch(e){if(4001===e.code)throw e;console.warn("[KwesPay] switchNetwork threw (verifying anyway):",e.message)}const l=Date.now();for(;Date.now()-l<15e3;){await new Promise(e=>setTimeout(e,500));try{const e=a(await o.request({method:"eth_chainId"}));if(e&&e===c)return void console.log(`[KwesPay] Network switch confirmed after ${Date.now()-l}ms ✅`)}catch(e){console.warn("[KwesPay] Poll eth_chainId error:",e.message)}}throw new Error(`Could not confirm network switch to ${t} after 15s. Please switch manually in your wallet and try again.`)}};class zx{constructor(e){if(!e.apiKey)throw new Error("[KwesPayWidget] apiKey is required");if(!e.vendorId)throw new Error("[KwesPayWidget] vendorId is required");if(!e.amount||parseFloat(e.amount)<=0)throw new Error("[KwesPayWidget] Valid amount is required");var i;if(this.config={apiKey:e.apiKey,vendorId:e.vendorId,amount:parseFloat(e.amount),currency:e.currency||r.currency,graphqlEndpoint:r.graphqlEndpoint,acceptedTokens:(i=e.acceptedTokens,i?"stablecoins"===i?n:Array.isArray(i)&&i.length?i.map(e=>e.toUpperCase()):null:null)},!Object.values(t).includes(this.config.currency))throw new Error(`[KwesPayWidget] Unsupported currency: ${this.config.currency}`);this.walletService=new Px,this.paymentService=new Nx(this.config.apiKey,this.config.graphqlEndpoint),this.state={isOpen:!1,currentStep:0,selectedNetwork:null,selectedNetworkName:"",selectedChainId:null,selectedRpcUrl:null,selectedContractAddress:null,selectedToken:null,selectedTokenConfig:null,vendorInfo:null,keyAllowedNetworks:null,keyAllowedTokens:null,currentPayload:null,quoteTimerInterval:null,wcUri:null},this._init()}async open(){const e=document.getElementById("kwespay-widget-overlay"),t=document.getElementById("kwespay-widget-container");e&&t&&(t.classList.remove("closing"),e.classList.add("open"),document.body.classList.add("kwespay-open"),this.state.isOpen=!0,await this._validateAPIKey(),Tx("widgetOpened",{}))}close(){const e=document.getElementById("kwespay-widget-overlay"),t=document.getElementById("kwespay-widget-container");if(!e||!t)return;this._clearQuoteTimer();const n=5===this.state.currentStep;window.innerWidth<=480?(t.classList.add("closing"),setTimeout(()=>{t.classList.remove("closing"),e.classList.remove("open"),document.body.classList.remove("kwespay-open"),this.state.isOpen=!1,Tx("widgetClosed",{completedPayment:n})},300)):(e.classList.remove("open"),document.body.classList.remove("kwespay-open"),this.state.isOpen=!1,Tx("widgetClosed",{completedPayment:n}))}isOpen(){return this.state.isOpen}updateAmount(e,n){const r=parseFloat(e);isNaN(r)||r<=0||(this.config.amount=r,n&&Object.values(t).includes(n)&&(this.config.currency=n),document.querySelectorAll('[id*="paymentAmount"], [id*="summaryFiatAmount"], [id*="txFiatAmount"], [id*="reviewFiatAmount"]').forEach(e=>{e.textContent=`${this.config.amount} ${this.config.currency}`}),Tx("amountUpdated",{amount:this.config.amount,currency:this.config.currency}))}getState(){return{...this.state,config:{...this.config}}}destroy(){this._clearQuoteTimer(),document.body.classList.remove("kwespay-open"),this.walletService?.disconnect(),document.getElementById("kwespay-widget-overlay")?.remove(),document.getElementById("kwespay-widget-styles")?.remove(),this.state=null,this.config=null,this.walletService=null,this.paymentService=null,Tx("widgetDestroyed",{})}}Object.assign(zx.prototype,$x,Rx,Bx,Mx,Ux,Dx,jx);const Hx={isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase()},Vx={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"},Fx={caipNetworkIdToNumber:e=>e?Number(e.split(":")[1]):void 0,parseEvmChainId(e){return"string"==typeof e?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace:(e,t)=>e?.filter(e=>e.chainNamespace===t)||[],getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const n=e.find(e=>e.caipNetworkId===t);if(n)return n.name;const[r]=t.split(":");return Vx.CHAIN_NAME_MAP?.[r]||void 0}},qx=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var Wx=1e6,Zx=1e6,Kx="[big.js] ",Gx=Kx+"Invalid ",Yx=Gx+"decimal places",Jx=Gx+"rounding mode",Qx=Kx+"Division by zero",Xx={},eA=void 0,tA=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function nA(e,t,n,r){var i=e.c;if(n===eA&&(n=e.constructor.RM),0!==n&&1!==n&&2!==n&&3!==n)throw Error(Jx);if(t<1)r=3===n&&(r||!!i[0])||0===t&&(1===n&&i[0]>=5||2===n&&(i[0]>5||5===i[0]&&(r||i[1]!==eA))),i.length=1,r?(e.e=e.e-t+1,i[0]=1):i[0]=e.e=0;else if(t<i.length){if(r=1===n&&i[t]>=5||2===n&&(i[t]>5||5===i[t]&&(r||i[t+1]!==eA||1&i[t-1]))||3===n&&(r||!!i[0]),i.length=t,r)for(;++i[--t]>9;)if(i[t]=0,0===t){++e.e,i.unshift(1);break}for(t=i.length;!i[--t];)i.pop()}return e}function rA(e,t,n){var r=e.e,i=e.c.join(""),s=i.length;if(t)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>s)for(r-=s;r--;)i+="0";else r<s&&(i=i.slice(0,r)+"."+i.slice(r));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return e.s<0&&n?"-"+i:i}Xx.abs=function(){var e=new this.constructor(this);return e.s=1,e},Xx.cmp=function(e){var t,n=this,r=n.c,i=(e=new n.constructor(e)).c,s=n.s,o=e.s,a=n.e,c=e.e;if(!r[0]||!i[0])return r[0]?s:i[0]?-o:0;if(s!=o)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,s=-1;++s<o;)if(r[s]!=i[s])return r[s]>i[s]^t?1:-1;return a==c?0:a>c^t?1:-1},Xx.div=function(e){var t=this,n=t.constructor,r=t.c,i=(e=new n(e)).c,s=t.s==e.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>Wx)throw Error(Yx);if(!i[0])throw Error(Qx);if(!r[0])return e.s=s,e.c=[e.e=0],e;var a,c,l,d,h,u=i.slice(),p=a=i.length,f=r.length,g=r.slice(0,a),m=g.length,y=e,w=y.c=[],b=0,v=o+(y.e=t.e-e.e)+1;for(y.s=s,s=v<0?0:v,u.unshift(0);m++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(m=g.length))d=a>m?1:-1;else for(h=-1,d=0;++h<a;)if(i[h]!=g[h]){d=i[h]>g[h]?1:-1;break}if(!(d<0))break;for(c=m==a?i:u;m;){if(g[--m]<c[m]){for(h=m;h&&!g[--h];)g[h]=9;--g[h],g[m]+=10}g[m]-=c[m]}for(;!g[0];)g.shift()}w[b++]=d?l:++l,g[0]&&d?g[m]=r[p]||0:g=[r[p]]}while((p++<f||g[0]!==eA)&&s--);return w[0]||1==b||(w.shift(),y.e--,v--),b>v&&nA(y,v,n.RM,g[0]!==eA),y},Xx.eq=function(e){return 0===this.cmp(e)},Xx.gt=function(e){return this.cmp(e)>0},Xx.gte=function(e){return this.cmp(e)>-1},Xx.lt=function(e){return this.cmp(e)<0},Xx.lte=function(e){return this.cmp(e)<1},Xx.minus=Xx.sub=function(e){var t,n,r,i,s=this,o=s.constructor,a=s.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,s.plus(e);var l=s.c.slice(),d=s.e,h=e.c,u=e.e;if(!l[0]||!h[0])return h[0]?e.s=-c:l[0]?e=new o(s):e.s=1,e;if(a=d-u){for((i=a<0)?(a=-a,r=l):(u=d,r=h),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((i=l.length<h.length)?l:h).length,a=c=0;c<n;c++)if(l[c]!=h[c]){i=l[c]<h[c];break}if(i&&(r=l,l=h,h=r,e.s=-e.s),(c=(n=h.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;n>a;){if(l[--n]<h[n]){for(t=n;t&&!l[--t];)l[t]=9;--l[t],l[n]+=10}l[n]-=h[n]}for(;0===l[--c];)l.pop();for(;0===l[0];)l.shift(),--u;return l[0]||(e.s=1,l=[u=0]),e.c=l,e.e=u,e},Xx.mod=function(e){var t,n=this,r=n.constructor,i=n.s,s=(e=new r(e)).s;if(!e.c[0])throw Error(Qx);return n.s=e.s=1,t=1==e.cmp(n),n.s=i,e.s=s,t?new r(n):(i=r.DP,s=r.RM,r.DP=r.RM=0,n=n.div(e),r.DP=i,r.RM=s,this.minus(n.times(e)))},Xx.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},Xx.plus=Xx.add=function(e){var t,n,r,i=this,s=i.constructor;if(e=new s(e),i.s!=e.s)return e.s=-e.s,i.minus(e);var o=i.e,a=i.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new s(i):e.s=i.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,r=l):(t=-t,r=a),r.reverse();t--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),t=l.length,n=0;t;a[t]%=10)n=(a[--t]=a[t]+l[t]+n)/10|0;for(n&&(a.unshift(n),++c),t=a.length;0===a[--t];)a.pop();return e.c=a,e.e=c,e},Xx.pow=function(e){var t=this,n=new t.constructor("1"),r=n,i=e<0;if(e!==~~e||e<-1e6||e>Zx)throw Error(Gx+"exponent");for(i&&(e=-e);1&e&&(r=r.times(t)),e>>=1;)t=t.times(t);return i?n.div(r):r},Xx.prec=function(e,t){if(e!==~~e||e<1||e>Wx)throw Error(Gx+"precision");return nA(new this.constructor(this),e,t)},Xx.round=function(e,t){if(e===eA)e=0;else if(e!==~~e||e<-Wx||e>Wx)throw Error(Yx);return nA(new this.constructor(this),e+this.e+1,t)},Xx.sqrt=function(){var e,t,n,r=this,i=r.constructor,s=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(s<0)throw Error(Kx+"No square root");0===(s=Math.sqrt(+rA(r,!0,!0)))||s===1/0?((t=r.c.join("")).length+o&1||(t+="0"),o=((o+1)/2|0)-(o<0||1&o),e=new i(((s=Math.sqrt(t))==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):e=new i(s+""),o=e.e+(i.DP+=4);do{n=e,e=a.times(n.plus(r.div(n)))}while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return nA(e,(i.DP-=4)+e.e+1,i.RM)},Xx.times=Xx.mul=function(e){var t,n=this,r=n.constructor,i=n.c,s=(e=new r(e)).c,o=i.length,a=s.length,c=n.e,l=e.e;if(e.s=n.s==e.s?1:-1,!i[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=i,i=s,s=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+s[c]*i[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},Xx.toExponential=function(e,t){var n=this,r=n.c[0];if(e!==eA){if(e!==~~e||e<0||e>Wx)throw Error(Yx);for(n=nA(new n.constructor(n),++e,t);n.c.length<e;)n.c.push(0)}return rA(n,!0,!!r)},Xx.toFixed=function(e,t){var n=this,r=n.c[0];if(e!==eA){if(e!==~~e||e<0||e>Wx)throw Error(Yx);for(e=e+(n=nA(new n.constructor(n),e+n.e+1,t)).e+1;n.c.length<e;)n.c.push(0)}return rA(n,!1,!!r)},Xx[Symbol.for("nodejs.util.inspect.custom")]=Xx.toJSON=Xx.toString=function(){var e=this,t=e.constructor;return rA(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},Xx.toNumber=function(){var e=+rA(this,!0,!0);if(!0===this.constructor.strict&&!this.eq(e.toString()))throw Error(Kx+"Imprecise conversion");return e},Xx.toPrecision=function(e,t){var n=this,r=n.constructor,i=n.c[0];if(e!==eA){if(e!==~~e||e<1||e>Wx)throw Error(Gx+"precision");for(n=nA(new r(n),e,t);n.c.length<e;)n.c.push(0)}return rA(n,e<=n.e||n.e<=r.NE||n.e>=r.PE,!!i)},Xx.valueOf=function(){var e=this,t=e.constructor;if(!0===t.strict)throw Error(Kx+"valueOf disallowed");return rA(e,e.e<=t.NE||e.e>=t.PE,!0)};var iA=function e(){function t(n){var r=this;if(!(r instanceof t))return n===eA?e():new t(n);if(n instanceof t)r.s=n.s,r.e=n.e,r.c=n.c.slice();else{if("string"!=typeof n){if(!0===t.strict&&"bigint"!=typeof n)throw TypeError(Gx+"value");n=0===n&&1/n<0?"-0":String(n)}!function(e,t){var n,r,i;if(!tA.test(t))throw Error(Gx+"number");e.s="-"==t.charAt(0)?(t=t.slice(1),-1):1,(n=t.indexOf("."))>-1&&(t=t.replace(".",""));(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length);for(i=t.length,r=0;r<i&&"0"==t.charAt(r);)++r;if(r==i)e.c=[e.e=0];else{for(;i>0&&"0"==t.charAt(--i););for(e.e=n-r-1,e.c=[],n=0;r<=i;)e.c[n++]=+t.charAt(r++)}}(r,n)}r.constructor=t}return t.prototype=Xx,t.DP=20,t.RM=1,t.NE=-7,t.PE=21,t.strict=false,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}();const sA={bigNumber(e,t={safe:!1}){try{return new iA(e?e:0)}catch(e){if(t.safe)return new iA(0);throw e}},formatNumber(e,t){const{decimals:n,round:r=8,safe:i=!0}=t;return sA.bigNumber(e,{safe:i}).div(new iA(10).pow(n)).round(r)},multiply(e,t){if(void 0===e||void 0===t)return new iA(0);const n=new iA(e),r=new iA(t);return n.times(r)},toFixed:(e,t=2)=>void 0===e||""===e?new iA(0).toFixed(t):new iA(e).toFixed(t),formatNumberToLocalString:(e,t=2)=>void 0===e||""===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}),parseLocalStringToNumber(e){if(void 0===e||""===e)return 0;const t=e.replace(/,/gu,"");return new iA(t).toNumber()}},oA=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],aA=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],cA=e=>Vx.USDT_CONTRACT_ADDRESSES.includes(e)?aA:oA,lA={ConnectorExplorerIds:{[Vx.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Vx.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Vx.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Vx.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[Vx.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[Vx.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Vx.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Vx.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Vx.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Vx.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Vx.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Vx.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Vx.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Vx.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Vx.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Vx.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Vx.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Vx.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Vx.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"}},dA={validateCaipAddress(e){if(3!==e.split(":")?.length)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(3!==t.length)throw new Error(`Invalid CAIP-10 address: ${e}`);const[n,r,i]=t;if(!n||!r||!i)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:n,chainId:r,address:i}},parseCaipNetworkId(e){const t=e.split(":");if(2!==t.length)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[n,r]=t;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:n,chainId:r}}},hA={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if("object"==typeof e&&null!==e){const t=e,n="string"==typeof t.message,r="number"==typeof t.code;return n&&r}return!1}catch{return!1}},isUserRejectedMessage:e=>e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled"),isUserRejectedRequestError(e){if(hA.isRpcProviderError(e)){const t=e.code===hA.RPC_ERROR_CODE.USER_REJECTED_REQUEST,n=e.code===hA.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||n||hA.isUserRejectedMessage(e.message)}return e instanceof Error&&hA.isUserRejectedMessage(e.message)}};let uA=class extends Error{constructor(e,t){super(t.message,{cause:e}),this.name=hA.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=t.code}},pA=class extends uA{constructor(e){super(e,{code:hA.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=hA.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}};const fA="@appkit/active_caip_network_id",gA="@appkit/connected_social",mA="@appkit-wallet/SOCIAL_USERNAME",yA="@appkit/recent_wallets",wA="@appkit/recent_wallet",bA="WALLETCONNECT_DEEPLINK_CHOICE",vA="@appkit/active_namespace",EA="@appkit/connected_namespaces",xA="@appkit/connection_status",AA="@appkit/siwx-auth-token",kA="@appkit/siwx-nonce-token",IA="@appkit/social_provider",CA="@appkit/native_balance_cache",SA="@appkit/portfolio_cache",PA="@appkit/ens_cache",NA="@appkit/identity_cache",_A="@appkit/preferred_account_types",TA="@appkit/connections",OA="@appkit/disconnected_connector_ids",$A="@appkit/history_transactions_cache",RA="@appkit/token_price_cache",BA="@appkit/latest_version",MA="@appkit/ton_wallets_cache";function UA(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const LA={setItem(e,t){DA()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(DA())return localStorage.getItem(e)||void 0},removeItem(e){DA()&&localStorage.removeItem(e)},clear(){DA()&&localStorage.clear()}};function DA(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}function jA(e,t){const n=e?.["--apkt-accent"]??e?.["--w3m-accent"];return"light"===t?{"--w3m-accent":n||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":n||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const zA=Symbol(),HA=Object.getPrototypeOf,VA=new WeakMap,FA=e=>(e=>e&&(VA.has(e)?VA.get(e):HA(e)===Object.prototype||HA(e)===Array.prototype))(e)&&e[zA]||null,qA=(e,t=!0)=>{VA.set(e,t)},WA=e=>"object"==typeof e&&null!==e,ZA=(e,t)=>{const n=YA.get(e);if((null==n?void 0:n[0])===t)return n[1];const r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return qA(r,!0),YA.set(e,[t,r]),Reflect.ownKeys(e).forEach(t=>{if(Object.getOwnPropertyDescriptor(r,t))return;const n=Reflect.get(e,t),{enumerable:i}=Reflect.getOwnPropertyDescriptor(e,t),s={value:n,enumerable:i,configurable:!0};if(GA.has(n))qA(n,!1);else if(KA.has(n)){const[e,t]=KA.get(n);s.value=ZA(e,t())}Object.defineProperty(r,t,s)}),Object.preventExtensions(r)},KA=new WeakMap,GA=new WeakSet,YA=new WeakMap,JA=[1],QA=new WeakMap;let XA=Object.is,ek=(e,t)=>new Proxy(e,t),tk=e=>WA(e)&&!GA.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),nk=ZA,rk=(e,t,n,r)=>({deleteProperty(e,t){const i=Reflect.get(e,t);n(t);const s=Reflect.deleteProperty(e,t);return s&&r(["delete",[t],i]),s},set(i,s,o,a){const c=!e()&&Reflect.has(i,s),l=Reflect.get(i,s,a);if(c&&(XA(l,o)||QA.has(o)&&XA(l,QA.get(o))))return!0;n(s),WA(o)&&(o=FA(o)||o);const d=!KA.has(o)&&tk(o)?ik(o):o;return t(s,d),Reflect.set(i,s,d,a),r(["set",[s],o,l]),!0}});function ik(e={}){if(!WA(e))throw new Error("object required");const t=QA.get(e);if(t)return t;let n=JA[0];const r=new Set,i=(e,t=++JA[0])=>{n!==t&&(s=n=t,r.forEach(n=>n(e,t)))};let s=n;const o=e=>(t,n)=>{const r=[...t];r[1]=[e,...r[1]],i(r,n)},a=new Map;let c=!0;const l=rk(()=>c,(e,t)=>{const n=!GA.has(t)&&KA.get(t);if(n){if(a.has(e))throw new Error("prop listener already exists");if(r.size){const t=n[2](o(e));a.set(e,[n,t])}else a.set(e,[n])}},e=>{var t;const n=a.get(e);n&&(a.delete(e),null==(t=n[1])||t.call(n))},i),d=ek(e,l);QA.set(e,d);const h=[e,(e=JA[0])=>(s!==e&&(s=e,a.forEach(([t])=>{const r=t[1](e);r>n&&(n=r)})),n),e=>{r.add(e),1===r.size&&a.forEach(([e,t],n)=>{if(t)throw new Error("remove already exists");const r=e[2](o(n));a.set(n,[e,r])});return()=>{r.delete(e),0===r.size&&a.forEach(([e,t],n)=>{t&&(t(),a.set(n,[e]))})}}];return KA.set(d,h),Reflect.ownKeys(e).forEach(t=>{const n=Object.getOwnPropertyDescriptor(e,t);"value"in n&&n.writable&&(d[t]=e[t])}),c=!1,d}function sk(e,t,n){const r=KA.get(e);let i;r||console.warn("Please use proxy object");const s=[],o=r[2];let a=!1;const c=o(e=>{s.push(e),i||(i=Promise.resolve().then(()=>{i=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,c()}}function ok(e){const t=KA.get(e);t||console.warn("Please use proxy object");const[n,r]=t;return nk(n,r())}function ak(e){return GA.add(e),e}function ck(e,t,n,r){let i=e[t];return sk(e,()=>{const r=e[t];Object.is(i,r)||n(i=r)})}const{proxyStateMap:lk,snapCache:dk}={proxyStateMap:KA,refSet:GA,snapCache:YA,versionHolder:JA,proxyCache:QA},hk=e=>lk.has(e);const uk=("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",pk=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],fk={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:uk,SECURE_SITE_DASHBOARD:`${uk}/dashboard`,SECURE_SITE_FAVICON:`${uk}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD₮0"]},BALANCE_SUPPORTED_CHAINS:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[Vx.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[lA.ConnectorExplorerIds[Vx.CONNECTOR_ID.COINBASE],lA.ConnectorExplorerIds[Vx.CONNECTOR_ID.COINBASE_SDK],lA.ConnectorExplorerIds[Vx.CONNECTOR_ID.BASE_ACCOUNT],lA.ConnectorExplorerIds[Vx.SOLFLARE_CONNECTOR_NAME],lA.ConnectorExplorerIds[Vx.PHANTOM_CONNECTOR_NAME],lA.ConnectorExplorerIds[Vx.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},gk={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=gk.getActiveNamespace(),t=gk.getActiveCaipNetworkId(),n=t?t.split(":")[1]:void 0;return{namespace:e,caipNetworkId:t,chainId:n?isNaN(Number(n))?n:Number(n):void 0}},setWalletConnectDeepLink({name:e,href:t}){try{LA.setItem(bA,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=LA.getItem(bA);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{LA.removeItem(bA)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{LA.setItem(vA,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{LA.setItem(fA,e),gk.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return LA.getItem(fA)}catch{return void console.info("Unable to get active caip network id")}},deleteActiveCaipNetworkId(){try{LA.removeItem(fA)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=UA(e);LA.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=gk.getRecentWallets(),n=t.find(t=>t.id===e.id);n||(t.unshift(e),t.length>2&&t.pop(),LA.setItem(yA,JSON.stringify(t)),LA.setItem(wA,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=LA.getItem(yA);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=LA.getItem(wA);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{LA.removeItem(wA)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const n=UA(e);LA.setItem(n,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return LA.getItem(vA)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=UA(e);return LA.getItem(t)}catch(t){console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{LA.setItem(gA,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return LA.getItem(gA)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{LA.removeItem(gA)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return LA.getItem(mA)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){const e=LA.getItem(fA),t=e?.split(":")?.[1];return t},setConnectionStatus(e){try{LA.setItem(xA,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return LA.getItem(xA)}catch{return}},getConnectedNamespaces(){try{const e=LA.getItem(EA);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));LA.setItem(EA,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=gk.getConnectedNamespaces();t.includes(e)||(t.push(e),gk.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=gk.getConnectedNamespaces(),n=t.indexOf(e);n>-1&&(t.splice(n,1),gk.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return LA.getItem(IA)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{LA.setItem(IA,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{LA.removeItem(IA)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=LA.getItem(SA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=gk.getBalanceCache();LA.setItem(SA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const t=gk.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;gk.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=gk.getBalanceCache();t[e.caipAddress]=e,LA.setItem(SA,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=LA.getItem(CA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=gk.getBalanceCache();LA.setItem(CA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const t=gk.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",e),gk.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=gk.getNativeBalanceCache();t[e.caipAddress]=e,LA.setItem(CA,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=LA.getItem(PA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const t=gk.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;gk.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=gk.getEnsCache();t[e.address]=e,LA.setItem(PA,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=gk.getEnsCache();LA.setItem(PA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=LA.getItem(NA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const t=gk.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;gk.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=gk.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},LA.setItem(NA,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=gk.getIdentityCache();LA.setItem(NA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{const e=LA.getItem(MA),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;gk.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{const t=gk.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=(new Date).getTime(),t.wallets=e,LA.setItem(MA,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{LA.removeItem(MA)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{LA.removeItem(SA),LA.removeItem(CA),LA.removeItem(PA),LA.removeItem(NA),LA.removeItem($A)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{LA.setItem(_A,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=LA.getItem(_A);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const n=gk.getConnections(),r=n[t]??[],i=new Map;for(const e of r)i.set(e.connectorId,{...e});for(const t of e){const e=i.get(t.connectorId),n=t.connectorId===Vx.CONNECTOR_ID.AUTH;if(e&&!n){const n=new Set(e.accounts.map(e=>e.address.toLowerCase())),r=t.accounts.filter(e=>!n.has(e.address.toLowerCase()));e.accounts.push(...r)}else i.set(t.connectorId,{...t})}const s={...n,[t]:Array.from(i.values())};LA.setItem(TA,JSON.stringify(s))}catch(e){console.error("Unable to sync connections to storage",e)}},getConnections(){try{const e=LA.getItem(TA);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:n}){try{const r=gk.getConnections(),i=r[n]??[],s=new Map(i.map(e=>[e.connectorId,e])),o=s.get(e);if(o){0===o.accounts.filter(e=>e.address.toLowerCase()!==t.toLowerCase()).length?s.delete(e):s.set(e,{...o,accounts:o.accounts.filter(e=>e.address.toLowerCase()!==t.toLowerCase())})}LA.setItem(TA,JSON.stringify({...r,[n]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const e=LA.getItem(OA);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const n=gk.getDisconnectedConnectorIds(),r=n[t]??[];r.push(e),LA.setItem(OA,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{const n=gk.getDisconnectedConnectorIds();let r=n[t]??[];r=r.filter(t=>t.toLowerCase()!==e.toLowerCase()),LA.setItem(OA,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{const n=gk.getDisconnectedConnectorIds();return(n[t]??[]).some(t=>t.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{const e=LA.getItem($A);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{const n=gk.getTransactionsCache(),r=n[e]?.[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;gk.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:n,transactions:r}){try{const i=gk.getTransactionsCache();i[e]={...i[e],[t]:{timestamp:n,transactions:r}},LA.setItem($A,JSON.stringify(i))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:n,transactions:r})}},removeTransactionsCache({address:e,chainId:t}){try{const n=gk.getTransactionsCache(),r=n?.[e]||{},{[t]:i,...s}=r;LA.setItem($A,JSON.stringify({...n,[e]:s}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=LA.getItem(RA);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const t=gk.getTokenPriceCache()[e.join(",")];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tokenPrice))return t.tokenPrice;gk.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=gk.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},LA.setItem(RA,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=gk.getTokenPriceCache();LA.setItem(RA,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{const e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const e=LA.getItem(BA);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=gk.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,LA.setItem(BA,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},mk={getWindow(){if("undefined"!=typeof window)return window},isMobile(){return!!this.isClient()&&Boolean(window?.matchMedia&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent))},checkCaipNetwork:(e,t="")=>e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase()),isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return mk.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){if(!this.isClient())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("safari")},isClient:()=>"undefined"!=typeof window,isPairingExpired:e=>!e||e-Date.now()<=fk.TEN_SEC_MS,isAllowedRetry:(e,t=fk.ONE_SEC_MS)=>Date.now()-e>=t,copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch(e){return!1}},isSafeApp(){if(mk.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const n=new URL(e),r=new URL(t);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry:()=>Date.now()+fk.FOUR_MINUTES_MS,getNetworkId:e=>e?.split(":")[1],getPlainAddress:e=>e?.split(":")[2],wait:async e=>new Promise(t=>{setTimeout(t,e)}),debounce(e,t=500){let n;return(...r)=>{n&&clearTimeout(n),n=setTimeout(function(){e(...r)},t)}},isHttpUrl:e=>e.startsWith("http://")||e.startsWith("https://"),formatNativeUrl(e,t,n=null){if(mk.isHttpUrl(e))return this.formatUniversalUrl(e,t);let r=e,i=n;r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const s=encodeURIComponent(t);return{redirect:`${r}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:r}},formatUniversalUrl(e,t){if(!mk.isHttpUrl(e))return this.formatNativeUrl(e,t);let n=e;n.endsWith("/")||(n=`${n}/`);return{redirect:`${n}wc?uri=${encodeURIComponent(t)}`,href:n}},getOpenTargetForPlatform(e){return"popupWindow"===e?e:this.isTelegram()?gk.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,n){window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},returnOpenHref(e,t,n){return window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},isTelegram:()=>"undefined"!=typeof window&&(Boolean(window.TelegramWebviewProxy)||Boolean(window.Telegram)||Boolean(window.TelegramWebviewProxyProto)),isPWA(){if("undefined"==typeof window)return!1;const e=!(!window?.matchMedia||"function"!=typeof window.matchMedia)&&window.matchMedia("(display-mode: standalone)")?.matches,t=window?.navigator?.standalone;return Boolean(e||t)},async preloadImage(e){const t=new Promise((t,n)=>{const r=new Image;r.onload=t,r.onerror=n,r.crossOrigin="anonymous",r.src=e});return Promise.race([t,mk.wait(2e3)])},parseBalance(e,t){let n="0.000";if("string"==typeof e){const t=Number(e);if(!isNaN(t)){const e=(Math.floor(1e3*t)/1e3).toFixed(3);e&&(n=e)}}const[r,i]=n.split("."),s=r||"0",o=i||"000";return{formattedText:`${s}.${o}${t?` ${t}`:""}`,value:s,decimals:o,symbol:t}},getApiUrl:()=>Vx.W3M_API_URL,getBlockchainApiUrl:()=>Vx.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>Vx.PULSE_API_URL,getUUID:()=>crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),parseError:e=>"string"==typeof e?e:"string"==typeof e?.issues?.[0]?.message?e.issues[0].message:e instanceof Error?e.message:"Unknown error",sortRequestedNetworks(e,t=[]){const n={};return t&&e&&(e.forEach((e,t)=>{n[e]=t}),t.sort((e,t)=>{const r=n[e.id],i=n[t.id];return void 0!==r&&void 0!==i?r-i:void 0!==r?-1:void 0!==i?1:0})),t},calculateBalance(e){let t=0;for(const n of e)t+=n.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[n,r]=t.split(".");return{dollars:n,pennies:r}},isAddress(e,t="eip155"){switch(t){case"eip155":return!!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!(!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!/^(?:0x)?[0-9A-F]{40}$/iu.test(e));case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);case"bip122":{const t=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),n=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),r=/^bc1[a-z0-9]{39,87}$/u.test(e),i=/^bc1p[a-z0-9]{58}$/u.test(e);return t||n||r||i}default:return!1}},uniqueBy(e,t){const n=new Set;return e.filter(e=>{const r=e[t];return!n.has(r)&&(n.add(r),!0)})},generateSdkVersion:(e,t,n)=>`${t}-${0===e.length?fk.ADAPTER_TYPES.UNIVERSAL:e.map(e=>e.adapterType).join(",")}-${n}`,createAccount:(e,t,n,r,i)=>({namespace:e,address:t,type:n,publicKey:r,path:i}),isCaipAddress(e){if("string"!=typeof e)return!1;const t=e.split(":"),n=t[0];return 3===t.filter(Boolean).length&&n in Vx.CHAIN_NAME_MAP},getAccount:e=>e?"string"==typeof e?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,n="state=";if("auth.magic.link"===new URL(e).host){const r="provider_authorization_url=",i=e.substring(e.indexOf(r)+r.length),s=this.injectIntoUrl(decodeURIComponent(i),n,t);return e.replace(i,encodeURIComponent(s))}return this.injectIntoUrl(e,n,t)},injectIntoUrl(e,t,n){const r=e.indexOf(t);if(-1===r)throw new Error(`${t} parameter not found in the URL: ${e}`);const i=e.indexOf("&",r),s=t.length,o=-1!==i?i:e.length;return e.substring(0,r+s)+(e.substring(r+s,o)+n)+e.substring(i)},isNumber:e=>("number"==typeof e||"string"==typeof e)&&!isNaN(Number(e))};"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const yk="@appkit-wallet/",wk="SMART_ACCOUNT_ENABLED_NETWORKS",bk={EOA:"eoa",SMART_ACCOUNT:"smartAccount"},vk={set(e,t){Ek.isClient&&localStorage.setItem(`${yk}${e}`,t)},get:e=>Ek.isClient?localStorage.getItem(`${yk}${e}`):null,delete(e,t){Ek.isClient&&(t?localStorage.removeItem(e):localStorage.removeItem(`${yk}${e}`))}},Ek={isClient:"undefined"!=typeof window};let xk=class e extends Error{constructor(t,n={}){const r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath;super([t||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...r?[`Details: ${r}`]:[],"Version: abitype@1.2.3"].join("\n")),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,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),n.cause&&(this.cause=n.cause),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.shortMessage=t}};function Ak(e,t){const n=e.exec(t);return n?.groups}const kk=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Ik=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Ck=/^\(.+?\).*?$/,Sk=/^tuple(?<array>(\[(\d*)\])*)$/;function Pk(e){let t=e.type;if(Sk.test(e.type)&&"components"in e){t="(";const n=e.components.length;for(let r=0;r<n;r++){t+=Pk(e.components[r]),r<n-1&&(t+=", ")}const r=Ak(Sk,e.type);return t+=`)${r?.array||""}`,Pk({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function Nk(e){let t="";const n=e.length;for(let r=0;r<n;r++){t+=Pk(e[r]),r!==n-1&&(t+=", ")}return t}function _k(e){return"function"===e.type?`function ${e.name}(${Nk(e.inputs)})${e.stateMutability&&"nonpayable"!==e.stateMutability?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Nk(e.outputs)})`:""}`:"event"===e.type?`event ${e.name}(${Nk(e.inputs)})`:"error"===e.type?`error ${e.name}(${Nk(e.inputs)})`:"constructor"===e.type?`constructor(${Nk(e.inputs)})${"payable"===e.stateMutability?" payable":""}`:"fallback"===e.type?"fallback() external"+("payable"===e.stateMutability?" payable":""):"receive() external payable"}const Tk=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;const Ok=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;const $k=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;const Rk=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Bk(e){return Rk.test(e)}function Mk(e){return Ak(Rk,e)}const Uk=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;const Lk=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;const Dk=/^receive\(\) external payable$/;const jk=new Set(["memory","indexed","storage","calldata"]),zk=new Set(["indexed"]),Hk=new Set(["calldata","memory","storage"]);class Vk extends xk{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}let Fk=class extends xk{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},qk=class extends xk{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};class Wk extends xk{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}let Zk=class extends xk{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},Kk=class extends xk{constructor({param:e,name:t}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${t}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},Gk=class extends xk{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},Yk=class extends xk{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},Jk=class extends xk{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}},Qk=class extends xk{constructor({signature:e,type:t}){super(`Invalid ${t} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},Xk=class extends xk{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},eI=class extends xk{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}},tI=class extends xk{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}},nI=class extends xk{constructor({current:e,depth:t}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${t>0?"opening":"closing"} parentheses.`],details:`Depth "${t}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};const rI=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function iI(e,t={}){if(function(e){return $k.test(e)}(e))return function(e,t={}){const n=function(e){return Ak($k,e)}(e);if(!n)throw new Qk({signature:e,type:"function"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{modifiers:Hk,structs:t,type:"function"}));const o=[];if(n.returns){const e=lI(n.returns),r=e.length;for(let n=0;n<r;n++)o.push(cI(e[n],{modifiers:Hk,structs:t,type:"function"}))}return{name:n.name,type:"function",stateMutability:n.stateMutability??"nonpayable",inputs:i,outputs:o}}(e,t);if(function(e){return Ok.test(e)}(e))return function(e,t={}){const n=function(e){return Ak(Ok,e)}(e);if(!n)throw new Qk({signature:e,type:"event"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{modifiers:zk,structs:t,type:"event"}));return{name:n.name,type:"event",inputs:i}}(e,t);if(function(e){return Tk.test(e)}(e))return function(e,t={}){const n=function(e){return Ak(Tk,e)}(e);if(!n)throw new Qk({signature:e,type:"error"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{structs:t,type:"error"}));return{name:n.name,type:"error",inputs:i}}(e,t);if(function(e){return Uk.test(e)}(e))return function(e,t={}){const n=function(e){return Ak(Uk,e)}(e);if(!n)throw new Qk({signature:e,type:"constructor"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:n.stateMutability??"nonpayable",inputs:i}}(e,t);if(function(e){return Lk.test(e)}(e))return function(e){const t=function(e){return Ak(Lk,e)}(e);if(!t)throw new Qk({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}(e);if(function(e){return Dk.test(e)}(e))return{type:"receive",stateMutability:"payable"};throw new Xk({signature:e})}const sI=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,oI=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,aI=/^u?int$/;function cI(e,t){const n=function(e,t,n){let r="";if(n)for(const e of Object.entries(n)){if(!e)continue;let t="";for(const n of e[1])t+=`[${n.type}${n.name?`:${n.name}`:""}]`;r+=`(${e[0]}{${t}})`}return t?`${t}:${e}${r}`:`${e}${r}`}(e,t?.type,t?.structs);if(rI.has(n))return rI.get(n);const r=Ck.test(e),i=Ak(r?oI:sI,e);if(!i)throw new Zk({param:e});if(i.name&&function(e){return"address"===e||"bool"===e||"function"===e||"string"===e||"tuple"===e||kk.test(e)||Ik.test(e)||hI.test(e)}(i.name))throw new Kk({param:e,name:i.name});const s=i.name?{name:i.name}:{},o="indexed"===i.modifier?{indexed:!0}:{},a=t?.structs??{};let c,l={};if(r){c="tuple";const e=lI(i.type),t=[],n=e.length;for(let r=0;r<n;r++)t.push(cI(e[r],{structs:a}));l={components:t}}else if(i.type in a)c="tuple",l={components:a[i.type]};else if(aI.test(i.type))c=`${i.type}256`;else if("address payable"===i.type)c="address";else if(c=i.type,"struct"!==t?.type&&!dI(c))throw new qk({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new Gk({param:e,type:t?.type,modifier:i.modifier});if(Hk.has(i.modifier)&&!function(e,t){return t||"bytes"===e||"string"===e||"tuple"===e}(c,!!i.array))throw new Yk({param:e,type:t?.type,modifier:i.modifier})}const d={type:`${c}${i.array??""}`,...s,...o,...l};return rI.set(n,d),d}function lI(e,t=[],n="",r=0){const i=e.trim().length;for(let s=0;s<i;s++){const i=e[s],o=e.slice(s+1);switch(i){case",":return 0===r?lI(o,[...t,n.trim()]):lI(o,t,`${n}${i}`,r);case"(":return lI(o,t,`${n}${i}`,r+1);case")":return lI(o,t,`${n}${i}`,r-1);default:return lI(o,t,`${n}${i}`,r)}}if(""===n)return t;if(0!==r)throw new nI({current:n,depth:r});return t.push(n.trim()),t}function dI(e){return"address"===e||"bool"===e||"function"===e||"string"===e||kk.test(e)||Ik.test(e)}const hI=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function uI(e){const t={},n=e.length;for(let r=0;r<n;r++){const n=e[r];if(!Bk(n))continue;const i=Mk(n);if(!i)throw new Qk({signature:n,type:"struct"});const s=i.properties.split(";"),o=[],a=s.length;for(let e=0;e<a;e++){const t=s[e].trim();if(!t)continue;const n=cI(t,{type:"struct"});o.push(n)}if(!o.length)throw new eI({signature:n});t[i.name]=o}const r={},i=Object.entries(t),s=i.length;for(let e=0;e<s;e++){const[n,s]=i[e];r[n]=fI(s,t)}return r}const pI=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function fI(e=[],t={},n=new Set){const r=[],i=e.length;for(let s=0;s<i;s++){const i=e[s];if(Ck.test(i.type))r.push(i);else{const e=Ak(pI,i.type);if(!e?.type)throw new Jk({abiParameter:i});const{array:s,type:o}=e;if(o in t){if(n.has(o))throw new tI({type:o});r.push({...i,type:`tuple${s??""}`,components:fI(t[o],t,new Set([...n,o]))})}else{if(!dI(o))throw new Fk({type:o});r.push(i)}}}return r}function gI(e){const t=uI(e),n=[],r=e.length;for(let i=0;i<r;i++){const r=e[i];Bk(r)||n.push(iI(r,t))}return n}function mI(e){let t;if("string"==typeof e)t=iI(e);else{const n=uI(e),r=e.length;for(let i=0;i<r;i++){const r=e[i];if(!Bk(r)){t=iI(r,n);break}}}if(!t)throw new Vk({signature:e});return t}function yI(e){const t=[];if("string"==typeof e){const n=lI(e),r=n.length;for(let e=0;e<r;e++)t.push(cI(n[e],{modifiers:jk}))}else{const n=uI(e),r=e.length;for(let i=0;i<r;i++){const r=e[i];if(Bk(r))continue;const s=lI(r),o=s.length;for(let e=0;e<o;e++)t.push(cI(s[e],{modifiers:jk,structs:n}))}}if(0===t.length)throw new Wk({params:e});return t}function wI(e,t,n){const r=e[t.name];if("function"==typeof r)return r;const i=e[n];return"function"==typeof i?i:n=>t(e,n)}function bI(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new JI(e.type);return`${e.name}(${vI(e.inputs,{includeName:t})})`}function vI(e,{includeName:t=!1}={}){return e?e.map(e=>function(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${vI(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}(e,{includeName:t})).join(t?", ":","):""}function EI(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function xI(e){return EI(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const AI="2.47.10";let kI=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,II=`viem@${AI}`,CI=class e extends Error{constructor(t,n={}){const r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,s=kI?.({...n,docsPath:i});super([t||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...II?[`Version: ${II}`]:[]].join("\n"),n.cause?{cause:n.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=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=AI}walk(e){return SI(this,e)}};function SI(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?SI(e.cause,t):t?null:e}class PI extends CI{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join("\n"),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class NI extends CI{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join("\n"),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class _I extends CI{constructor({data:e,params:t,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join("\n"),{metaMessages:[`Params: (${vI(t,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=t,this.size=n}}class TI extends CI{constructor({cause:e}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:e})}}let OI=class extends CI{constructor({expectedLength:e,givenLength:t,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${t}`].join("\n"),{name:"AbiEncodingArrayLengthMismatchError"})}},$I=class extends CI{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${xI(t)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}},RI=class extends CI{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${t}`].join("\n"),{name:"AbiEncodingLengthMismatchError"})}};class BI extends CI{constructor(e,{docsPath:t}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join("\n"),{docsPath:t,name:"AbiErrorInputsNotFoundError"})}}class MI extends CI{constructor(e,{docsPath:t}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join("\n"),{docsPath:t,name:"AbiErrorNotFoundError"})}}class UI extends CI{constructor(e,{docsPath:t,cause:n}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${e}.`].join("\n"),{docsPath:t,name:"AbiErrorSignatureNotFoundError",cause:n}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class LI extends CI{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class DI extends CI{constructor(e,{docsPath:t}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${e}.`].join("\n"),{docsPath:t,name:"AbiEventSignatureNotFoundError"})}}class jI extends CI{constructor(e,{docsPath:t}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join("\n"),{docsPath:t,name:"AbiEventNotFoundError"})}}let zI=class extends CI{constructor(e,{docsPath:t}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join("\n"),{docsPath:t,name:"AbiFunctionNotFoundError"})}};class HI extends CI{constructor(e,{docsPath:t}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join("\n"),{docsPath:t,name:"AbiFunctionOutputsNotFoundError"})}}class VI extends CI{constructor(e,{docsPath:t}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${e}.`].join("\n"),{docsPath:t,name:"AbiFunctionSignatureNotFoundError"})}}let FI=class extends CI{constructor(e,t){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${bI(e.abiItem)}\`, and`,`\`${t.type}\` in \`${bI(t.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}},qI=class extends CI{constructor({expectedSize:e,givenSize:t}){super(`Expected bytes${e}, got bytes${t}.`,{name:"BytesSizeMismatchError"})}};class WI extends CI{constructor({abiItem:e,data:t,params:n,size:r}){super([`Data size of ${r} bytes is too small for non-indexed event parameters.`].join("\n"),{metaMessages:[`Params: (${vI(n,{includeName:!0})})`,`Data: ${t} (${r} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=t,this.params=n,this.size=r}}class ZI extends CI{constructor({abiItem:e,param:t}){super([`Expected a topic for indexed event parameter${t.name?` "${t.name}"`:""} on event "${bI(e,{includeName:!0})}".`].join("\n"),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}let KI=class extends CI{constructor(e,{docsPath:t}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join("\n"),{docsPath:t,name:"InvalidAbiEncodingType"})}};class GI extends CI{constructor(e,{docsPath:t}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join("\n"),{docsPath:t,name:"InvalidAbiDecodingType"})}}let YI=class extends CI{constructor(e){super([`Value "${e}" is not a valid array.`].join("\n"),{name:"InvalidArrayError"})}},JI=class extends CI{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join("\n"),{name:"InvalidDefinitionTypeError"})}};class QI extends CI{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let XI=class extends CI{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},eC=class extends CI{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};class tC extends CI{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${t} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function nC(e,{dir:t,size:n=32}={}){return"string"==typeof e?rC(e,{dir:t,size:n}):iC(e,{dir:t,size:n})}function rC(e,{dir:t,size:n=32}={}){if(null===n)return e;const r=e.replace("0x","");if(r.length>2*n)throw new eC({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r["right"===t?"padEnd":"padStart"](2*n,"0")}`}function iC(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new eC({size:e.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s="right"===t;r[s?i:n-i-1]=e[s?i:e.length-i-1]}return r}let sC=class extends CI{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${8*r}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},oC=class extends CI{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class aC extends CI{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let cC=class extends CI{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function lC(e,{dir:t="left"}={}){let n="string"==typeof e?e.replace("0x",""):e,r=0;for(let e=0;e<n.length-1&&"0"===n["left"===t?e:n.length-e-1].toString();e++)r++;return n="left"===t?n.slice(r):n.slice(0,n.length-r),"string"==typeof e?(1===n.length&&"right"===t&&(n=`${n}0`),`0x${n.length%2==1?`0${n}`:n}`):n}function dC(e,{size:t}){if(xI(e)>t)throw new cC({givenSize:xI(e),maxSize:t})}function hC(e,t={}){const{signed:n}=t;t.size&&dC(e,{size:t.size});const r=BigInt(e);if(!n)return r;const i=(e.length-2)/2;return r<=(1n<<8n*BigInt(i)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*i,"f")}`)-1n}function uC(e,t={}){let n=e;if(t.size&&(dC(n,{size:t.size}),n=lC(n)),"0x00"===lC(n))return!1;if("0x01"===lC(n))return!0;throw new aC(n)}function pC(e,t={}){const n=hC(e,t),r=Number(n);if(!Number.isSafeInteger(r))throw new sC({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${n}n`});return r}const fC=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function gC(e,t={}){return"number"==typeof e||"bigint"==typeof e?wC(e,t):"string"==typeof e?vC(e,t):"boolean"==typeof e?mC(e,t):yC(e,t)}function mC(e,t={}){const n=`0x${Number(e)}`;return"number"==typeof t.size?(dC(n,{size:t.size}),nC(n,{size:t.size})):n}function yC(e,t={}){let n="";for(let t=0;t<e.length;t++)n+=fC[e[t]];const r=`0x${n}`;return"number"==typeof t.size?(dC(r,{size:t.size}),nC(r,{dir:"right",size:t.size})):r}function wC(e,t={}){const{signed:n,size:r}=t,i=BigInt(e);let s;r?s=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&i>s||i<o){const t="bigint"==typeof e?"n":"";throw new sC({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}const a=`0x${(n&&i<0?(1n<<BigInt(8*r))+BigInt(i):i).toString(16)}`;return r?nC(a,{size:r}):a}const bC=new TextEncoder;function vC(e,t={}){return yC(bC.encode(e),t)}const EC=new TextEncoder;function xC(e,t={}){return"number"==typeof e||"bigint"==typeof e?SC(e,t):"boolean"==typeof e?AC(e,t):EI(e)?CC(e,t):PC(e,t)}function AC(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(dC(n,{size:t.size}),nC(n,{size:t.size})):n}const kC={zero:48,nine:57,A:65,F:70,a:97,f:102};function IC(e){return e>=kC.zero&&e<=kC.nine?e-kC.zero:e>=kC.A&&e<=kC.F?e-(kC.A-10):e>=kC.a&&e<=kC.f?e-(kC.a-10):void 0}function CC(e,t={}){let n=e;t.size&&(dC(n,{size:t.size}),n=nC(n,{dir:"right",size:t.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let e=0,t=0;e<i;e++){const n=IC(r.charCodeAt(t++)),i=IC(r.charCodeAt(t++));if(void 0===n||void 0===i)throw new CI(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);s[e]=16*n+i}return s}function SC(e,t){return CC(wC(e,t))}function PC(e,t={}){const n=EC.encode(e);return"number"==typeof t.size?(dC(n,{size:t.size}),nC(n,{dir:"right",size:t.size})):n}const NC=BigInt(2**32-1),_C=BigInt(32);function TC(e,t=!1){return t?{h:Number(e&NC),l:Number(e>>_C&NC)}:{h:0|Number(e>>_C&NC),l:0|Number(e&NC)}}const OC="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function $C(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function RC(e,...t){if(!
|
|
40
|
+
const ul=hl;function pl(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return(e=>{const t=e.replace(/([\[:])?(\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,'$1"$2n"$3');return JSON.parse(t,(e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t)})(e)}catch(t){return e}}function fl(e){return"string"==typeof e?e:(t=e,JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString()+"n":t)||"");var t}function gl(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ml(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const yl="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,wl=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bl(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),gl(e),e}let vl=class{clone(){return this._cloneInto()}};function El(e=32){if(yl&&"function"==typeof yl.getRandomValues)return yl.getRandomValues(new Uint8Array(e));if(yl&&"function"==typeof yl.randomBytes)return yl.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}let xl=class extends vl{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=wl(this.buffer)}update(e){ml(this);const{view:t,buffer:n,blockLen:r}=this,i=(e=bl(e)).length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=wl(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ml(this),function(e,t){gl(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;(function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)})(n,r-8,BigInt(8*this.length),i),this.process(n,0);const o=wl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return e.length=r,e.pos=o,e.finished=i,e.destroyed=s,r%t&&e.buffer.set(n),e}};const Al=BigInt(2**32-1),kl=BigInt(32);function Il(e,t=!1){return t?{h:Number(e&Al),l:Number(e>>kl&Al)}:{h:0|Number(e>>kl&Al),l:0|Number(e&Al)}}const Cl={fromBig:Il,split:function(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=Il(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]},toBig:(e,t)=>BigInt(e>>>0)<<kl|BigInt(t>>>0),shrSH:(e,t,n)=>e>>>n,shrSL:(e,t,n)=>e<<32-n|t>>>n,rotrSH:(e,t,n)=>e>>>n|t<<32-n,rotrSL:(e,t,n)=>e<<32-n|t>>>n,rotrBH:(e,t,n)=>e<<64-n|t>>>n-32,rotrBL:(e,t,n)=>e>>>n-32|t<<64-n,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,n)=>e<<n|t>>>32-n,rotlSL:(e,t,n)=>t<<n|e>>>32-n,rotlBH:(e,t,n)=>t<<n-32|e>>>64-n,rotlBL:(e,t,n)=>e<<n-32|t>>>64-n,add:function(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/2**32|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,add5H:(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,add5L:(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0)},[Sl,Pl]=Cl.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(e=>BigInt(e))),Nl=new Uint32Array(80),_l=new Uint32Array(80);let Tl=class extends xl{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:n,Bl:r,Ch:i,Cl:s,Dh:o,Dl:a,Eh:c,El:l,Fh:d,Fl:h,Gh:u,Gl:p,Hh:f,Hl:g}=this;return[e,t,n,r,i,s,o,a,c,l,d,h,u,p,f,g]}set(e,t,n,r,i,s,o,a,c,l,d,h,u,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|d,this.Fl=0|h,this.Gh=0|u,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)Nl[n]=e.getUint32(t),_l[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Nl[e-15],n=0|_l[e-15],r=Cl.rotrSH(t,n,1)^Cl.rotrSH(t,n,8)^Cl.shrSH(t,n,7),i=Cl.rotrSL(t,n,1)^Cl.rotrSL(t,n,8)^Cl.shrSL(t,n,7),s=0|Nl[e-2],o=0|_l[e-2],a=Cl.rotrSH(s,o,19)^Cl.rotrBH(s,o,61)^Cl.shrSH(s,o,6),c=Cl.rotrSL(s,o,19)^Cl.rotrBL(s,o,61)^Cl.shrSL(s,o,6),l=Cl.add4L(i,c,_l[e-7],_l[e-16]),d=Cl.add4H(l,r,a,Nl[e-7],Nl[e-16]);Nl[e]=0|d,_l[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:o,Cl:a,Dh:c,Dl:l,Eh:d,El:h,Fh:u,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Cl.rotrSH(d,h,14)^Cl.rotrSH(d,h,18)^Cl.rotrBH(d,h,41),w=Cl.rotrSL(d,h,14)^Cl.rotrSL(d,h,18)^Cl.rotrBL(d,h,41),b=d&u^~d&f,v=h&p^~h&g,E=Cl.add5L(y,w,v,Pl[e],_l[e]),x=Cl.add5H(E,m,t,b,Sl[e],Nl[e]),A=0|E,k=Cl.rotrSH(n,r,28)^Cl.rotrBH(n,r,34)^Cl.rotrBH(n,r,39),I=Cl.rotrSL(n,r,28)^Cl.rotrBL(n,r,34)^Cl.rotrBL(n,r,39),C=n&i^n&o^i&o,S=r&s^r&a^s&a;m=0|f,y=0|g,f=0|u,g=0|p,u=0|d,p=0|h,({h:d,l:h}=Cl.add(0|c,0|l,0|x,0|A)),c=0|o,l=0|a,o=0|i,a=0|s,i=0|n,s=0|r;const P=Cl.add3L(A,I,S);n=Cl.add3H(P,x,k,C),r=0|P}({h:n,l:r}=Cl.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=Cl.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=Cl.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=Cl.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:d,l:h}=Cl.add(0|this.Eh,0|this.El,0|d,0|h)),({h:u,l:p}=Cl.add(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=Cl.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Cl.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,i,s,o,a,c,l,d,h,u,p,f,g,m,y)}roundClean(){Nl.fill(0),_l.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 Ol=function(e){const t=t=>e().update(bl(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new Tl),$l=BigInt(0),Rl=BigInt(1),Bl=BigInt(2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ml(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Ul(e){if(!Ml(e))throw new Error("Uint8Array expected")}function Ll(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const Dl=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function jl(e){Ul(e);let t="";for(let n=0;n<e.length;n++)t+=Dl[e[n]];return t}function zl(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?$l:BigInt("0x"+e)}const Hl=48,Vl=57,Fl=65,ql=70,Wl=97,Zl=102;function Kl(e){return e>=Hl&&e<=Vl?e-Hl:e>=Fl&&e<=ql?e-(Fl-10):e>=Wl&&e<=Zl?e-(Wl-10):void 0}function Gl(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=Kl(e.charCodeAt(i)),s=Kl(e.charCodeAt(i+1));if(void 0===n||void 0===s){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+s}return r}function Yl(e){return Ul(e),zl(jl(Uint8Array.from(e).reverse()))}function Jl(e,t){return Gl(e.toString(16).padStart(2*t,"0"))}function Ql(e,t){return Jl(e,t).reverse()}function Xl(e,t,n){let r;if("string"==typeof t)try{r=Gl(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Ml(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function ed(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Ul(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}const td=e=>"bigint"==typeof e&&$l<=e;function nd(e,t,n,r){if(!function(e,t,n){return td(e)&&td(t)&&td(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const rd=e=>(Bl<<BigInt(e-1))-Rl,id={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Ml(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function sd(e,t,n={}){const r=(t,n,r)=>{const i=id[n];if("function"!=typeof i)throw new Error("invalid validator function");const s=e[t];if(!(r&&void 0===s||i(s,e)))throw new Error("param "+String(t)+" is invalid. Expected "+n+", got "+s)};for(const[e,n]of Object.entries(t))r(e,n,!1);for(const[e,t]of Object.entries(n))r(e,t,!0);return e}function od(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}const ad=BigInt(0),cd=BigInt(1),ld=BigInt(2),dd=BigInt(3),hd=BigInt(4),ud=BigInt(5),pd=BigInt(8);function fd(e,t){const n=e%t;return n>=ad?n:t+n}function gd(e,t,n){if(t<ad)throw new Error("invalid exponent, negatives unsupported");if(n<=ad)throw new Error("invalid modulus");if(n===cd)return ad;let r=cd;for(;t>ad;)t&cd&&(r=r*e%n),e=e*e%n,t>>=cd;return r}function md(e,t,n){let r=e;for(;t-- >ad;)r*=r,r%=n;return r}function yd(e,t){if(e===ad)throw new Error("invert: expected non-zero number");if(t<=ad)throw new Error("invert: expected positive modulus, got "+t);let n=fd(e,t),r=t,i=ad,s=cd;for(;n!==ad;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==cd)throw new Error("invert: does not exist");return fd(i,t)}function wd(e){if(e%hd===dd){const t=(e+cd)/hd;return function(e,n){const r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}}if(e%pd===ud){const t=(e-ud)/pd;return function(e,n){const r=e.mul(n,ld),i=e.pow(r,t),s=e.mul(n,i),o=e.mul(e.mul(s,ld),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),n))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-cd)/ld;let n,r,i;for(n=e-cd,r=0;n%ld===ad;n/=ld,r++);for(i=ld;i<e&&gd(i,t,e)!==e-cd;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===r){const t=(e+cd)/hd;return function(e,n){const r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}}const s=(n+cd)/ld;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=r,c=e.pow(e.mul(e.ONE,i),n),l=e.pow(o,s),d=e.pow(o,n);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let n=e.sqr(d);t<a&&!e.eql(n,e.ONE);t++)n=e.sqr(n);const n=e.pow(c,cd<<BigInt(a-t-1));c=e.sqr(n),l=e.mul(l,n),d=e.mul(d,c),a=t}return l}}(e)}const bd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vd(e,t){const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Ed(e,t,n=!1,r={}){if(e<=ad)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:i,nByteLength:s}=vd(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:n,BITS:i,BYTES:s,MASK:rd(i),ZERO:ad,ONE:cd,create:t=>fd(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return ad<=t&&t<e},is0:e=>e===ad,isOdd:e=>(e&cd)===cd,neg:t=>fd(-t,e),eql:(e,t)=>e===t,sqr:t=>fd(t*t,e),add:(t,n)=>fd(t+n,e),sub:(t,n)=>fd(t-n,e),mul:(t,n)=>fd(t*n,e),pow:(e,t)=>function(e,t,n){if(n<ad)throw new Error("invalid exponent, negatives unsupported");if(n===ad)return e.ONE;if(n===cd)return t;let r=e.ONE,i=t;for(;n>ad;)n&cd&&(r=e.mul(r,i)),i=e.sqr(i),n>>=cd;return r}(a,e,t),div:(t,n)=>fd(t*yd(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>yd(t,e),sqrt:r.sqrt||(t=>(o||(o=wd(e)),o(a,t))),invertBatch:e=>function(e,t){const n=new Array(t.length),r=t.reduce((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r)),e.ONE),i=e.inv(r);return t.reduceRight((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r)),i),n}(a,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?Ql(e,s):Jl(e,s),fromBytes:e=>{if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);return n?Yl(e):function(e){return zl(jl(e))}(e)}});return Object.freeze(a)}const xd=BigInt(0),Ad=BigInt(1);function kd(e,t){const n=t.negate();return e?n:t}function Id(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Cd(e,t){Id(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Sd=new WeakMap,Pd=new WeakMap;function Nd(e){return Pd.get(e)||1}function _d(e,t,n,r){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,s=function(e){let t;for(t=0;e>$l;e>>=Rl,t+=1);return t}(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i);let l=i;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(i);for(let t=0;t<r.length;t++){const i=r[t],s=Number(i>>BigInt(e)&BigInt(a));c[s]=c[s].add(n[t])}let t=i;for(let e=c.length-1,n=i;e>0;e--)n=n.add(c[e]),t=t.add(n);if(l=l.add(t),0!==e)for(let e=0;e<o;e++)l=l.double()}return l}function Td(e){return function(e){const t=bd.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});sd(e,t)}(e.Fp),sd(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vd(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const Od=BigInt(0),$d=BigInt(1),Rd=BigInt(2),Bd=BigInt(8),Md={zip215:!0};function Ud(e){const t=function(e){const t=Td(e);return sd(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=t,l=Rd<<BigInt(8*a)-$d,d=n.create,h=Ed(t.n,t.nBitLength),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(e*n.inv(t))}}catch{return{isValid:!1,value:Od}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,n)=>{if(Ll("phflag",n),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){nd("coordinate "+e,t,Od,l)}function m(e){if(!(e instanceof b))throw new Error("ExtendedPoint expected")}const y=od((e,t)=>{const{ex:r,ey:i,ez:s}=e,o=e.is0();null==t&&(t=o?Bd:n.inv(s));const a=d(r*t),c=d(i*t),l=d(s*t);if(o)return{x:Od,y:$d};if(l!==$d)throw new Error("invZ was invalid");return{x:a,y:c}}),w=od(e=>{const{a:n,d:r}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:i,ey:s,ez:o,et:a}=e,c=d(i*i),l=d(s*s),h=d(o*o),u=d(h*h),p=d(c*n);if(d(h*d(p+l))!==d(u+d(r*d(c*l))))throw new Error("bad point: equation left != right (1)");if(d(i*s)!==d(o*a))throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(e,t,n,r){this.ex=e,this.ey=t,this.ez=n,this.et=r,g("x",e),g("y",t),g("z",n),g("t",r),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof b)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return g("x",t),g("y",n),new b(t,n,$d,d(t*n))}static normalizeZ(e){const t=n.invertBatch(e.map(e=>e.ez));return e.map((e,n)=>e.toAffine(t[n])).map(b.fromAffine)}static msm(e,t){return _d(b,h,e,t)}_setWindowSize(e){x.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){m(e);const{ex:t,ey:n,ez:r}=this,{ex:i,ey:s,ez:o}=e,a=d(t*o),c=d(i*r),l=d(n*o),h=d(s*r);return a===c&&l===h}is0(){return this.equals(b.ZERO)}negate(){return new b(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){const{a:e}=t,{ex:n,ey:r,ez:i}=this,s=d(n*n),o=d(r*r),a=d(Rd*d(i*i)),c=d(e*s),l=n+r,h=d(d(l*l)-s-o),u=c+o,p=u-a,f=c-o,g=d(h*p),m=d(u*f),y=d(h*f),w=d(p*u);return new b(g,m,w,y)}add(e){m(e);const{a:n,d:r}=t,{ex:i,ey:s,ez:o,et:a}=this,{ex:c,ey:l,ez:h,et:u}=e;if(n===BigInt(-1)){const e=d((s-i)*(l+c)),t=d((s+i)*(l-c)),n=d(t-e);if(n===Od)return this.double();const r=d(o*Rd*u),p=d(a*Rd*h),f=p+r,g=t+e,m=p-r,y=d(f*n),w=d(g*m),v=d(f*m),E=d(n*g);return new b(y,w,E,v)}const p=d(i*c),f=d(s*l),g=d(a*r*u),y=d(o*h),w=d((i+s)*(c+l)-p-f),v=y-g,E=y+g,x=d(f-n*p),A=d(w*v),k=d(E*x),I=d(w*x),C=d(v*E);return new b(A,k,C,I)}subtract(e){return this.add(e.negate())}wNAF(e){return x.wNAFCached(this,e,b.normalizeZ)}multiply(e){const t=e;nd("scalar",t,$d,r);const{p:n,f:i}=this.wNAF(t);return b.normalizeZ([n,i])[0]}multiplyUnsafe(e,t=b.ZERO){const n=e;return nd("scalar",n,Od,r),n===Od?E:this.is0()||n===$d?this:x.wNAFCachedUnsafe(this,n,b.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return x.unsafeLadder(this,r).is0()}toAffine(e){return y(this,e)}clearCofactor(){const{h:e}=t;return e===$d?this:this.multiplyUnsafe(e)}static fromHex(e,r=!1){const{d:i,a:s}=t,o=n.BYTES;e=Xl("pointHex",e,o),Ll("zip215",r);const a=e.slice(),c=e[o-1];a[o-1]=-129&c;const h=Yl(a),p=r?l:n.ORDER;nd("pointHex.y",h,Od,p);const f=d(h*h),g=d(f-$d),m=d(i*f-s);let{isValid:y,value:w}=u(g,m);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const v=(w&$d)===$d,E=!!(128&c);if(!r&&w===Od&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(w=d(-w)),b.fromAffine({x:w,y:h})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Ql(t,n.BYTES);return r[r.length-1]|=e&$d?128:0,r}toHex(){return jl(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,$d,d(t.Gx*t.Gy)),b.ZERO=new b(Od,$d,$d,Od);const{BASE:v,ZERO:E}=b,x=function(e,t){return{constTimeNegate:kd,hasPrecomputes:e=>1!==Nd(e),unsafeLadder(t,n,r=e.ZERO){let i=t;for(;n>xd;)n&Ad&&(r=r.add(i)),i=i.double(),n>>=Ad;return r},precomputeWindow(e,n){const{windows:r,windowSize:i}=Cd(n,t),s=[];let o=e,a=o;for(let e=0;e<r;e++){a=o,s.push(a);for(let e=1;e<i;e++)a=a.add(o),s.push(a);o=a.double()}return s},wNAF(n,r,i){const{windows:s,windowSize:o}=Cd(n,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**n-1),d=2**n,h=BigInt(n);for(let e=0;e<s;e++){const t=e*o;let n=Number(i&l);i>>=h,n>o&&(n-=d,i+=Ad);const s=t,u=t+Math.abs(n)-1,p=e%2!=0,f=n<0;0===n?c=c.add(kd(p,r[s])):a=a.add(kd(f,r[u]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=e.ZERO){const{windows:o,windowSize:a}=Cd(n,t),c=BigInt(2**n-1),l=2**n,d=BigInt(n);for(let e=0;e<o;e++){const t=e*a;if(i===xd)break;let n=Number(i&c);if(i>>=d,n>a&&(n-=l,i+=Ad),0===n)continue;let o=r[t+Math.abs(n)-1];n<0&&(o=o.negate()),s=s.add(o)}return s},getPrecomputes(e,t,n){let r=Sd.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&Sd.set(t,n(r))),r},wNAFCached(e,t,n){const r=Nd(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)},wNAFCachedUnsafe(e,t,n,r){const i=Nd(e);return 1===i?this.unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)},setWindowSize(e,n){Id(n,t),Pd.set(e,n),Sd.delete(e)}}}(b,8*a);function A(e){return fd(e,r)}function k(e){return A(Yl(e))}function I(e){const t=n.BYTES;e=Xl("private key",e,t);const r=Xl("hashed private key",s(e),2*t),i=p(r.slice(0,t)),o=r.slice(t,2*t),a=k(i),c=v.multiply(a),l=c.toRawBytes();return{head:i,prefix:o,scalar:a,point:c,pointBytes:l}}function C(e=new Uint8Array,...t){const n=ed(...t);return k(s(f(n,Xl("context",e),!!i)))}const S=Md;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,s={}){e=Xl("message",e),i&&(e=i(e));const{prefix:o,scalar:a,pointBytes:c}=I(t),l=C(s.context,o,e),d=v.multiply(l).toRawBytes(),h=A(l+C(s.context,d,c,e)*a);return nd("signature.s",h,Od,r),Xl("result",ed(d,Ql(h,n.BYTES)),2*n.BYTES)},verify:function(e,t,r,s=S){const{context:o,zip215:a}=s,c=n.BYTES;e=Xl("signature",e,2*c),t=Xl("message",t),r=Xl("publicKey",r,c),void 0!==a&&Ll("zip215",a),i&&(t=i(t));const l=Yl(e.slice(c,2*c));let d,h,u;try{d=b.fromHex(r,a),h=b.fromHex(e.slice(0,c),a),u=v.multiplyUnsafe(l)}catch{return!1}if(!a&&d.isSmallOrder())return!1;const p=C(o,h.toRawBytes(),d.toRawBytes(),t);return h.add(d.multiplyUnsafe(p)).subtract(u).clearCofactor().equals(b.ZERO)},ExtendedPoint:b,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(n.BYTES),precompute:(e=8,t=b.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}BigInt(0),BigInt(1);const Ld=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Dd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const jd=BigInt(1),zd=BigInt(2);BigInt(3);const Hd=BigInt(5),Vd=BigInt(8);function Fd(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function qd(e,t){const n=Ld,r=fd(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Ld,o=e*e%s*e%s,a=md(o,zd,s)*o%s,c=md(a,jd,s)*e%s,l=md(c,Hd,s)*c%s,d=md(l,t,s)*l%s,h=md(d,n,s)*d%s,u=md(h,r,s)*h%s,p=md(u,i,s)*u%s,f=md(p,i,s)*u%s,g=md(f,t,s)*l%s;return{pow_p_5_8:md(g,zd,s)*e%s,b2:o}}(e*fd(r*r*t,n)).pow_p_5_8;let s=fd(e*r*i,n);const o=fd(t*s*s,n),a=s,c=fd(s*Dd,n),l=o===e,d=o===fd(-e,n),h=o===fd(-e*Dd,n);return l&&(s=a),(d||h)&&(s=c),((e,t)=>(fd(e,t)&cd)===cd)(s,n)&&(s=fd(-s,n)),{isValid:l||d,value:s}}const Wd=Ed(Ld,void 0,!0),Zd=Ud({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wd,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Vd,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ol,randomBytes:El,adjustScalarBytes:Fd,uvRatio:qd}),Kd=".",Gd="base64url",Yd="utf8",Jd="utf8",Qd="did",Xd="key",eh="base58btc";function th(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function nh(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?th(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function rh(e,t){t||(t=e.reduce((e,t)=>e+t.length,0));const n=nh(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return th(n)}var ih=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(255!==n[o])throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var r=0,i=0;e[t]===c;)r++,t++;for(var s=(e.length-t)*l+1>>>0,o=new Uint8Array(s);e[t];){var d=n[e.charCodeAt(t)];if(255===d)return;for(var h=0,u=s-1;(0!==d||h<i)&&-1!==u;u--,h++)d+=a*o[u]>>>0,o[u]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=h,t++}if(" "!==e[t]){for(var p=s-i;p!==s&&0===o[p];)p++;for(var f=new Uint8Array(r+(s-p)),g=r;p!==s;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var n=0,r=0,i=0,s=t.length;i!==s&&0===t[i];)i++,n++;for(var o=(s-i)*d+1>>>0,l=new Uint8Array(o);i!==s;){for(var h=t[i],u=0,p=o-1;(0!==h||u<r)&&-1!==p;p--,u++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");r=u,i++}for(var f=o-r;f!==o&&0===l[f];)f++;for(var g=c.repeat(n);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var n=h(e);if(n)return n;throw new Error(`Non-${t} character`)}}},sh=ih;const oh=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};let ah=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ch=class{constructor(e,t,n){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return dh(this,e)}},lh=class{constructor(e){this.decoders=e}or(e){return dh(this,e)}decode(e){const t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const dh=(e,t)=>new lh({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});let hh=class{constructor(e,t,n,r){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=r,this.encoder=new ah(e,t,n),this.decoder=new ch(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const uh=({name:e,prefix:t,encode:n,decode:r})=>new hh(e,t,n,r),ph=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=sh(n,t);return uh({prefix:e,name:t,encode:r,decode:e=>oh(i(e))})},fh=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>uh({prefix:t,name:e,encode:e=>((e,t,n)=>{const r="="===t[t.length-1],i=(1<<n)-1;let s="",o=0,a=0;for(let r=0;r<e.length;++r)for(a=a<<8|e[r],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s})(e,r,n),decode:t=>((e,t,n,r)=>{const i={};for(let e=0;e<t.length;++e)i[t[e]]=e;let s=e.length;for(;"="===e[s-1];)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let t=0;t<s;++t){const s=i[e[t]];if(void 0===s)throw new SyntaxError(`Non-${r} character`);c=c<<n|s,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,r,n,e)}),gh=uh({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var mh=Object.freeze({__proto__:null,identity:gh});const yh=fh({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wh=Object.freeze({__proto__:null,base2:yh});const bh=fh({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vh=Object.freeze({__proto__:null,base8:bh});const Eh=ph({prefix:"9",name:"base10",alphabet:"0123456789"});var xh=Object.freeze({__proto__:null,base10:Eh});const Ah=fh({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kh=fh({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ih=Object.freeze({__proto__:null,base16:Ah,base16upper:kh});const Ch=fh({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sh=fh({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ph=fh({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nh=fh({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_h=fh({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Th=fh({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oh=fh({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$h=fh({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rh=fh({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bh=Object.freeze({__proto__:null,base32:Ch,base32upper:Sh,base32pad:Ph,base32padupper:Nh,base32hex:_h,base32hexupper:Th,base32hexpad:Oh,base32hexpadupper:$h,base32z:Rh});const Mh=ph({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Uh=ph({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Lh=Object.freeze({__proto__:null,base36:Mh,base36upper:Uh});const Dh=ph({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jh=ph({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var zh=Object.freeze({__proto__:null,base58btc:Dh,base58flickr:jh});const Hh=fh({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Vh=fh({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fh=fh({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qh=fh({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wh=Object.freeze({__proto__:null,base64:Hh,base64pad:Vh,base64url:Fh,base64urlpad:qh});const Zh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Kh=Zh.reduce((e,t,n)=>(e[n]=t,e),[]),Gh=Zh.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);const Yh=uh({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+=Kh[t],"")},decode:function(e){const t=[];for(const n of e){const e=Gh[n.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${n}`);t.push(e)}return new Uint8Array(t)}});var Jh=Object.freeze({__proto__:null,base256emoji:Yh}),Qh=function e(t,n,r){n=n||[];for(var i=r=r||0;t>=tu;)n[r++]=255&t|Xh,t/=128;for(;t&eu;)n[r++]=255&t|Xh,t>>>=7;return n[r]=0|t,e.bytes=r-i+1,n},Xh=128,eu=-128,tu=Math.pow(2,31);var nu=function e(t,n){var r,i=0,s=(n=n||0,0),o=n,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");r=t[o++],i+=s<28?(r&iu)<<s:(r&iu)*Math.pow(2,s),s+=7}while(r>=ru);return e.bytes=o-n,i},ru=128,iu=127;var su=Math.pow(2,7),ou=Math.pow(2,14),au=Math.pow(2,21),cu=Math.pow(2,28),lu=Math.pow(2,35),du=Math.pow(2,42),hu=Math.pow(2,49),uu=Math.pow(2,56),pu=Math.pow(2,63),fu={encode:Qh,decode:nu,encodingLength:function(e){return e<su?1:e<ou?2:e<au?3:e<cu?4:e<lu?5:e<du?6:e<hu?7:e<uu?8:e<pu?9:10}},gu=fu;const mu=(e,t,n=0)=>(gu.encode(e,t,n),t),yu=e=>gu.encodingLength(e),wu=(e,t)=>{const n=t.byteLength,r=yu(e),i=r+yu(n),s=new Uint8Array(i+n);return mu(e,s,0),mu(n,s,r),s.set(t,i),new bu(e,n,t,s)};let bu=class{constructor(e,t,n,r){this.code=e,this.size=t,this.digest=n,this.bytes=r}};const vu=({name:e,code:t,encode:n})=>new Eu(e,t,n);let Eu=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?wu(this.code,t):t.then(e=>wu(this.code,e))}throw Error("Unknown type, must be binary type")}};const xu=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Au=vu({name:"sha2-256",code:18,encode:xu("SHA-256")}),ku=vu({name:"sha2-512",code:19,encode:xu("SHA-512")});Object.freeze({__proto__:null,sha256:Au,sha512:ku});const Iu=oh,Cu={code:0,name:"identity",encode:Iu,digest:e=>wu(0,Iu(e))};Object.freeze({__proto__:null,identity:Cu});new TextEncoder,new TextDecoder;const Su={...mh,...wh,...vh,...xh,...Ih,...Bh,...Lh,...zh,...Wh,...Jh};function Pu(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const Nu=Pu("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),_u=Pu("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{const t=nh((e=e.substring(1)).length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Tu={utf8:Nu,"utf-8":Nu,hex:Su.base16,latin1:_u,ascii:_u,binary:_u,...Su};function Ou(e,t="utf8"){const n=Tu[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?n.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}function $u(e,t="utf8"){const n=Tu[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?n.decoder.decode(`${n.prefix}${e}`):th(globalThis.Buffer.from(e,"utf-8"))}function Ru(e){return pl(Ou($u(e,Gd),Yd))}function Bu(e){return Ou($u(fl(e),Yd),Gd)}function Mu(e){const t="z"+Ou(rh([$u("K36",eh),e]),eh);return[Qd,Xd,t].join(":")}function Uu(e){return Ou(e,Gd)}function Lu(e){const t=e.split(Kd),n=Ru(t[0]),r=Ru(t[1]),i=function(e){return $u(e,Gd)}(t[2]);return{header:n,payload:r,signature:i,data:$u(t.slice(0,2).join(Kd),Jd)}}function Du(e=El(32)){const t=Zd.getPublicKey(e);return{secretKey:rh([e,t]),publicKey:t}}async function ju(e,t,n,r,i=U.fromMiliseconds(Date.now())){const s={alg:"EdDSA",typ:"JWT"},o={iss:Mu(r.publicKey),sub:e,aud:t,iat:i,exp:i+n},a=function(e){return $u([Bu(e.header),Bu(e.payload)].join(Kd),Jd)}({header:s,payload:o});return function(e){return[Bu(e.header),Bu(e.payload),Uu(e.signature)].join(Kd)}({header:s,payload:o,signature:Zd.sign(a,r.secretKey.slice(0,32))})}const zu={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"}};function Hu(e){return(4294967296+e).toString(16).substring(1)}var Vu={normalizeInput:function(e){let t;if(e instanceof Uint8Array)t=e;else{if("string"!=typeof e)throw new Error("Input must be an string, Buffer or Uint8Array");t=(new TextEncoder).encode(e)}return t},toHex:function(e){return Array.prototype.map.call(e,function(e){return(e<16?"0":"")+e.toString(16)}).join("")},debugPrint:function(e,t,n){let r="\n"+e+" = ";for(let i=0;i<t.length;i+=2){if(32===n)r+=Hu(t[i]).toUpperCase(),r+=" ",r+=Hu(t[i+1]).toUpperCase();else{if(64!==n)throw new Error("Invalid size "+n);r+=Hu(t[i+1]).toUpperCase(),r+=Hu(t[i]).toUpperCase()}i%6==4?r+="\n"+new Array(e.length+4).join(" "):i<t.length-2&&(r+=" ")}console.log(r)},testSpeed:function(e,t,n){let r=(new Date).getTime();const i=new Uint8Array(t);for(let e=0;e<t;e++)i[e]=e%256;const s=(new Date).getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let s=0;s<n;s++){const n=e(i),s=(new Date).getTime(),o=s-r;r=s,console.log("Hashed in "+o+"ms: "+n.substring(0,20)+"..."),console.log(Math.round(t/(1<<20)/(o/1e3)*100)/100+" MB PER SECOND")}}};const Fu=Vu;function qu(e,t,n){const r=e[t]+e[n];let i=e[t+1]+e[n+1];r>=4294967296&&i++,e[t]=r,e[t+1]=i}function Wu(e,t,n,r){let i=e[t]+n;n<0&&(i+=4294967296);let s=e[t+1]+r;i>=4294967296&&s++,e[t]=i,e[t+1]=s}function Zu(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function Ku(e,t,n,r,i,s){const o=Qu[i],a=Qu[i+1],c=Qu[s],l=Qu[s+1];qu(Ju,e,t),Wu(Ju,e,o,a);let d=Ju[r]^Ju[e],h=Ju[r+1]^Ju[e+1];Ju[r]=h,Ju[r+1]=d,qu(Ju,n,r),d=Ju[t]^Ju[n],h=Ju[t+1]^Ju[n+1],Ju[t]=d>>>24^h<<8,Ju[t+1]=h>>>24^d<<8,qu(Ju,e,t),Wu(Ju,e,c,l),d=Ju[r]^Ju[e],h=Ju[r+1]^Ju[e+1],Ju[r]=d>>>16^h<<16,Ju[r+1]=h>>>16^d<<16,qu(Ju,n,r),d=Ju[t]^Ju[n],h=Ju[t+1]^Ju[n+1],Ju[t]=h>>>31^d<<1,Ju[t+1]=d>>>31^h<<1}const Gu=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Yu=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map(function(e){return 2*e})),Ju=new Uint32Array(32),Qu=new Uint32Array(32);function Xu(e,t){let n=0;for(n=0;n<16;n++)Ju[n]=e.h[n],Ju[n+16]=Gu[n];for(Ju[24]=Ju[24]^e.t,Ju[25]=Ju[25]^e.t/4294967296,t&&(Ju[28]=~Ju[28],Ju[29]=~Ju[29]),n=0;n<32;n++)Qu[n]=Zu(e.b,4*n);for(n=0;n<12;n++)Ku(0,8,16,24,Yu[16*n+0],Yu[16*n+1]),Ku(2,10,18,26,Yu[16*n+2],Yu[16*n+3]),Ku(4,12,20,28,Yu[16*n+4],Yu[16*n+5]),Ku(6,14,22,30,Yu[16*n+6],Yu[16*n+7]),Ku(0,10,20,30,Yu[16*n+8],Yu[16*n+9]),Ku(2,12,22,24,Yu[16*n+10],Yu[16*n+11]),Ku(4,14,16,26,Yu[16*n+12],Yu[16*n+13]),Ku(6,8,18,28,Yu[16*n+14],Yu[16*n+15]);for(n=0;n<16;n++)e.h[n]=e.h[n]^Ju[n]^Ju[n+16]}const ep=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function tp(e,t,n,r){if(0===e||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&16!==n.length)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&16!==r.length)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};ep.fill(0),ep[0]=e,t&&(ep[1]=t.length),ep[2]=1,ep[3]=1,n&&ep.set(n,32),r&&ep.set(r,48);for(let e=0;e<16;e++)i.h[e]=Gu[e]^Zu(ep,4*e);return t&&(np(i,t),i.c=128),i}function np(e,t){for(let n=0;n<t.length;n++)128===e.c&&(e.t+=e.c,Xu(e,!1),e.c=0),e.b[e.c++]=t[n]}function rp(e){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;Xu(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(3&n);return t}function ip(e,t,n,r,i){n=n||64,e=Fu.normalizeInput(e),r&&(r=Fu.normalizeInput(r)),i&&(i=Fu.normalizeInput(i));const s=tp(n,t,r,i);return np(s,e),rp(s)}var sp={blake2b:ip,blake2bHex:function(e,t,n,r,i){const s=ip(e,t,n,r,i);return Fu.toHex(s)},blake2bInit:tp,blake2bUpdate:np,blake2bFinal:rp};const op=Vu;function ap(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function cp(e,t,n,r,i,s){up[e]=up[e]+up[t]+i,up[r]=lp(up[r]^up[e],16),up[n]=up[n]+up[r],up[t]=lp(up[t]^up[n],12),up[e]=up[e]+up[t]+s,up[r]=lp(up[r]^up[e],8),up[n]=up[n]+up[r],up[t]=lp(up[t]^up[n],7)}function lp(e,t){return e>>>t^e<<32-t}const dp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),hp=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),up=new Uint32Array(16),pp=new Uint32Array(16);function fp(e,t){let n=0;for(n=0;n<8;n++)up[n]=e.h[n],up[n+8]=dp[n];for(up[12]^=e.t,up[13]^=e.t/4294967296,t&&(up[14]=~up[14]),n=0;n<16;n++)pp[n]=ap(e.b,4*n);for(n=0;n<10;n++)cp(0,4,8,12,pp[hp[16*n+0]],pp[hp[16*n+1]]),cp(1,5,9,13,pp[hp[16*n+2]],pp[hp[16*n+3]]),cp(2,6,10,14,pp[hp[16*n+4]],pp[hp[16*n+5]]),cp(3,7,11,15,pp[hp[16*n+6]],pp[hp[16*n+7]]),cp(0,5,10,15,pp[hp[16*n+8]],pp[hp[16*n+9]]),cp(1,6,11,12,pp[hp[16*n+10]],pp[hp[16*n+11]]),cp(2,7,8,13,pp[hp[16*n+12]],pp[hp[16*n+13]]),cp(3,4,9,14,pp[hp[16*n+14]],pp[hp[16*n+15]]);for(n=0;n<8;n++)e.h[n]^=up[n]^up[n+8]}function gp(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=t?t.length:0;if(t&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(dp),b:new Uint8Array(64),c:0,t:0,outlen:e};return r.h[0]^=16842752^n<<8^e,n>0&&(mp(r,t),r.c=64),r}function mp(e,t){for(let n=0;n<t.length;n++)64===e.c&&(e.t+=e.c,fp(e,!1),e.c=0),e.b[e.c++]=t[n]}function yp(e){for(e.t+=e.c;e.c<64;)e.b[e.c++]=0;fp(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(3&n)&255;return t}function wp(e,t,n){n=n||32,e=op.normalizeInput(e);const r=gp(n,t);return mp(r,e),yp(r)}var bp={blake2s:wp,blake2sHex:function(e,t,n){const r=wp(e,t,n);return op.toHex(r)},blake2sInit:gp,blake2sUpdate:mp,blake2sFinal:yp};var vp={blake2b:sp.blake2b,blake2bHex:sp.blake2bHex,blake2bInit:sp.blake2bInit,blake2bUpdate:sp.blake2bUpdate,blake2bFinal:sp.blake2bFinal,blake2s:bp.blake2s,blake2sHex:bp.blake2sHex,blake2sInit:bp.blake2sInit,blake2sUpdate:bp.blake2sUpdate,blake2sFinal:bp.blake2sFinal},Ep={exports:{}};function xp(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var Ap=function(e,t,n){var r=n&&n.stringify||xp;if("object"==typeof e&&null!==e){var i=t.length+1;if(1===i)return e;var s=new Array(i);s[0]=r(e);for(var o=1;o<i;o++)s[o]=r(t[o]);return s.join(" ")}if("string"!=typeof e)return e;var a=t.length;if(0===a)return e;for(var c="",l=0,d=-1,h=e&&e.length||0,u=0;u<h;){if(37===e.charCodeAt(u)&&u+1<h){switch(d=d>-1?d:0,e.charCodeAt(u+1)){case 100:case 102:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Number(t[l]),d=u+2,u++;break;case 105:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Math.floor(Number(t[l])),d=u+2,u++;break;case 79:case 111:case 106:if(l>=a||void 0===t[l])break;d<u&&(c+=e.slice(d,u));var p=typeof t[l];if("string"===p){c+="'"+t[l]+"'",d=u+2,u++;break}if("function"===p){c+=t[l].name||"<anonymous>",d=u+2,u++;break}c+=r(t[l]),d=u+2,u++;break;case 115:if(l>=a)break;d<u&&(c+=e.slice(d,u)),c+=String(t[l]),d=u+2,u++;break;case 37:d<u&&(c+=e.slice(d,u)),c+="%",d=u+2,u++,l--}++l}++u}return-1===d?e:(d<h&&(c+=e.slice(d)),c)};const kp=Ap;Ep.exports=Op;const Ip=function(){function e(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}().console||{},Cp={mapHttpRequest:Lp,mapHttpResponse:Lp,wrapRequestSerializer:Dp,wrapResponseSerializer:Dp,wrapErrorSerializer:Dp,req:Lp,res:Lp,err:Mp,errWithCause:Mp};function Sp(e,t){return"silent"===e?1/0:t.levels.values[e]}const Pp=Symbol("pino.logFuncs"),Np=Symbol("pino.hierarchy"),_p={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Tp(e,t){const n={logger:t,parent:e[Np]};t[Np]=n}function Op(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const n=e.browser.write||Ip;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},i=function(e,t){return Array.isArray(e)?e.filter(function(e){return"!stdSerializers.err"!==e}):!0===e&&Object.keys(t)}(e.browser.serialize,r);let s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);"function"==typeof n&&a.forEach(function(e){n[e]=n}),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(n);l.log||(l.log=jp),function(e,t,n){const r={};t.forEach(e=>{r[e]=n[e]?n[e]:Ip[e]||Ip[_p[e]||"log"]||jp}),e[Pp]=r}(l,a,n),Tp({},l),Object.defineProperty(l,"levelVal",{get:function(){return Sp(this.level,this)}}),Object.defineProperty(l,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,$p(this,d,l,"error"),$p(this,d,l,"fatal"),$p(this,d,l,"warn"),$p(this,d,l,"info"),$p(this,d,l,"debug"),$p(this,d,l,"trace"),o.forEach(e=>{$p(this,d,l,e)})}});const d={transmit:t,serialize:i,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:Up(e),messageKey:e.messageKey||"msg",onChild:e.onChild||jp};function h(n,s,o){if(!s)throw new Error("missing bindings for child Pino");o=o||{},i&&s.serializers&&(o.serializers=s.serializers);const a=o.serializers;if(i&&a){var c=Object.assign({},r,a),l=!0===e.browser.serialize?Object.keys(c):i;delete s.serializers,Rp([s],l,c,this._stdErrSerialize)}function d(e){this._childLevel=1+(0|e._childLevel),this.bindings=s,c&&(this.serializers=c,this._serialize=l),t&&(this._logEvent=Bp([].concat(e._logEvent.bindings,s)))}d.prototype=this;const u=new d(this);return Tp(this,u),u.child=function(...e){return h.call(this,n,...e)},u.level=o.level||this.level,n.onChild(u),u}return l.levels=function(e){const t=e.customLevels||{},n=Object.assign({},Op.levels.values,t),r=Object.assign({},Op.levels.labels,function(e){const t={};return Object.keys(e).forEach(function(n){t[e[n]]=n}),t}(t));return{values:n,labels:r}}(e),l.level=c,l.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=jp,l.serializers=r,l._serialize=i,l._stdErrSerialize=s,l.child=function(...e){return h.call(this,d,...e)},t&&(l._logEvent=Bp()),l}function $p(e,t,n,r){if(Object.defineProperty(e,r,{value:Sp(e.level,n)>Sp(r,n)?jp:n[Pp][r],writable:!0,enumerable:!0,configurable:!0}),e[r]===jp){if(!t.transmit)return;const i=Sp(t.transmit.level||e.level,n);if(Sp(r,n)<i)return}e[r]=function(e,t,n,r){return function(i){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Ip?Ip:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(Rp(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),t.asObject||t.formatters?i.call(a,...function(e,t,n,r,i){const{level:s,log:o=e=>e}=i.formatters||{},a=n.slice();let c=a[0];const l={};let d=1+(0|e._childLevel);if(d<1&&(d=1),r&&(l.time=r),s){const n=s(t,e.levels.values[t]);Object.assign(l,n)}else l.level=e.levels.values[t];if(i.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());return[o(l),...a]}if(null!==c&&"object"==typeof c){for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());c=a.length?kp(a.shift(),a):void 0}else"string"==typeof c&&(c=kp(a.shift(),a));return void 0!==c&&(l[i.messageKey]=c),[o(l)]}(this,r,o,s,t)):i.apply(a,o),t.transmit){const i=Sp(t.transmit.level||e._level,n),a=Sp(r,n);if(a<i)return;!function(e,t,n,r=!1){const i=t.send,s=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;r||Rp(n,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=n.filter(function(e){return-1===l.indexOf(e)}),e._logEvent.level.label=o,e._logEvent.level.value=a,i(o,e._logEvent,c),e._logEvent=Bp(l)}(this,{ts:s,methodLevel:r,methodValue:a,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Sp(e._level,n)},o,l)}}}(e[Pp][r])}(e,t,n,r);const i=function(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[Np];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}(e);0!==i.length&&(e[r]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(i,e[r]))}function Rp(e,t,n,r){for(const i in e)if(r&&e[i]instanceof Error)e[i]=Op.stdSerializers.err(e[i]);else if("object"==typeof e[i]&&!Array.isArray(e[i])&&t)for(const r in e[i])t.indexOf(r)>-1&&r in n&&(e[i][r]=n[r](e[i][r]))}function Bp(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function Mp(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)void 0===t[n]&&(t[n]=e[n]);return t}function Up(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?zp:Hp}function Lp(){return{}}function Dp(e){return e}function jp(){}function zp(){return!1}function Hp(){return Date.now()}Op.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Op.stdSerializers=Cp,Op.stdTimeFunctions=Object.assign({},{nullTime:zp,epochTime:Hp,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),Ep.exports.default=Op,Ep.exports.pino=Op;const Vp="info",Fp="custom_context",qp=1024e3;var Wp=Object.defineProperty,Zp=(e,t,n)=>((e,t,n)=>t in e?Wp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);let Kp=class{constructor(e){Zp(this,"nodeValue"),Zp(this,"sizeInBytes"),Zp(this,"next"),this.nodeValue=e,this.sizeInBytes=(new TextEncoder).encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Gp=class{constructor(e){Zp(this,"lengthInNodes"),Zp(this,"sizeInBytes"),Zp(this,"head"),Zp(this,"tail"),Zp(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new Kp(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;null!==t;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}};function Yp(e){return"string"==typeof e?e:(e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString()+"n":t))(e)||""}var Jp=Object.defineProperty,Qp=(e,t,n)=>((e,t,n)=>t in e?Jp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);let Xp=class{constructor(e,t=qp){Qp(this,"logs"),Qp(this,"level"),Qp(this,"levelValue"),Qp(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Ep.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Gp(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Ep.exports.levels.values.error?console.error(e):t===Ep.exports.levels.values.warn?console.warn(e):t===Ep.exports.levels.values.debug?console.debug(e):t===Ep.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Yp({timestamp:(new Date).toISOString(),log:e}));const t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Gp(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Yp({extraMetadata:e})),new Blob(t,{type:"application/json"})}};var ef=Object.defineProperty,tf=(e,t,n)=>((e,t,n)=>t in e?ef(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);let nf=class{constructor(e,t=qp){tf(this,"baseChunkLogger"),this.baseChunkLogger=new Xp(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=t,n.download=`walletconnect-logs-${(new Date).toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(t)}};var rf=Object.defineProperty,sf=(e,t,n)=>((e,t,n)=>t in e?rf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);let of=class{constructor(e,t=qp){sf(this,"baseChunkLogger"),this.baseChunkLogger=new Xp(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var af=Object.defineProperty,cf=Object.defineProperties,lf=Object.getOwnPropertyDescriptors,df=Object.getOwnPropertySymbols,hf=Object.prototype.hasOwnProperty,uf=Object.prototype.propertyIsEnumerable,pf=(e,t,n)=>t in e?af(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ff=(e,t)=>{for(var n in t||(t={}))hf.call(t,n)&&pf(e,n,t[n]);if(df)for(var n of df(t))uf.call(t,n)&&pf(e,n,t[n]);return e},gf=(e,t)=>cf(e,lf(t));function mf(e){return gf(ff({},e),{level:e?.level||Vp})}function yf(e,t=Fp){return e[t]||""}function wf(e,t,n=Fp){const r=function(e,t,n=Fp){const r=yf(e,n);return r.trim()?`${r}/${t}`:t}(e,t,n);return function(e,t,n=Fp){return e[n]=t,e}(e.child({context:r}),r,n)}function bf(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const n=gf(ff({},e.opts),{level:"string"==typeof e.loggerOverride?e.loggerOverride:null==(t=e.opts)?void 0:t.level});return typeof window<"u"?function(e){var t,n;const r=new nf(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Ep.exports(gf(ff({},e.opts),{level:"trace",browser:gf(ff({},null==(n=e.opts)?void 0:n.browser),{write:e=>r.write(e)})})),chunkLoggerController:r}}(gf(ff({},e),{opts:n})):function(e){var t,n;const r=new of(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Ep.exports(gf(ff({},e.opts),{level:"trace",browser:gf(ff({},null==(n=e.opts)?void 0:n.browser),{write:e=>r.write(e)})}),r),chunkLoggerController:r}}(gf(ff({},e),{opts:n}))}function vf(e){const[t,n]=e.split(":");return{namespace:t,reference:n}}function Ef(e,t=[]){const n=[];return Object.keys(e).forEach(r=>{if(t.length&&!t.includes(r))return;const i=e[r];n.push(...i.accounts)}),n}function xf(e,t){return e.includes(":")?[e]:t.chains||[]}const Af={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}},kf={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 If(e,t){const{message:n,code:r}=kf[e];return{message:t?`${n} ${t}`:n,code:r}}function Cf(e,t){const{message:n,code:r}=Af[e];return{message:t?`${n} ${t}`:n,code:r}}const Sf="react-native",Pf="node",Nf="browser",_f="unknown",Tf="js";function Of(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function $f(){return!ge()&&!!me()&&"ReactNative"===navigator.product}function Rf(){return!Of()&&!!me()&&!!ge()}function Bf(){return $f()?Sf:Of()?Pf:Rf()?Nf:_f}function Mf(){try{return $f()&&typeof e<"u"&&typeof e?.Application<"u"?e.Application?.applicationId:void 0}catch{return}}function Uf(){return be()||{name:"",description:"",url:"",icons:[""]}}function Lf(t,n,r){const i=function(){if(Bf()===Sf&&typeof e<"u"&&typeof e?.Platform<"u"){const{OS:t,Version:n}=e.Platform;return[t,n].join("-")}const t=M();if(null===t)return"unknown";const n=t.os?t.os.replace(" ","").toLowerCase():"unknown";return"browser"===t.type?[n,t.name,t.version].join("-"):[n,t.version].join("-")}(),s=function(){const e=Bf();return e===Nf?[e,ye()?.host||"unknown"].join(":"):e}();return[[t,n].join("-"),[Tf,r].join("-"),i,s].join("/")}function Df({protocol:e,version:t,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),d={auth:i,ua:Lf(e,t,r),projectId:s,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=function(e,t){const n=new URLSearchParams(e);return Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,t])=>{null!=t&&n.set(e,String(t))}),n.toString()}(l[1]||"",d);return l[0]+"?"+h}function jf(e,t){return e.filter(e=>t.includes(e)).length===e.length}function zf(e){return Object.fromEntries(e.entries())}function Hf(e){return new Map(Object.entries(e))}function Vf(e=U.FIVE_MINUTES,t){const n=U.toMiliseconds(e||U.FIVE_MINUTES);let r,i,s,o;return{resolve:e=>{s&&r&&(clearTimeout(s),r(e),o=Promise.resolve(e))},reject:e=>{s&&i&&(clearTimeout(s),i(e))},done:()=>new Promise((e,a)=>{if(o)return e(o);s=setTimeout(()=>{const e=If("EXPIRED"),n=new Error(t||e.message);n.code=e.code,a(n)},n),r=e,i=a})}}function Ff(e,t,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),t);try{r(await e)}catch(e){i(e)}clearTimeout(s)})}function qf(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function Wf(e){const[t,n]=e.split(":"),r={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof n)r.topic=n;else{if("id"!==t||!Number.isInteger(Number(n)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${n}`);r.id=Number(n)}return r}function Zf(e,t){return U.fromMiliseconds(Date.now()+U.toMiliseconds(e))}function Kf(e){return Date.now()>=U.toMiliseconds(e)}function Gf(e,t){return`${e}${t?`:${t}`:""}`}function Yf(e=[],t=[]){return[...new Set([...e,...t])]}async function Jf({id:t,topic:n,wcDeepLink:r}){try{if(!r)return;const i=("string"==typeof r?JSON.parse(r):r)?.href;if("string"!=typeof i)return;const s=function(e,t,n){const r=`requestId=${t}&sessionTopic=${n}`;e.endsWith("/")&&(e=e.slice(0,-1));let i=`${e}`;if(e.startsWith("https://t.me")){i=`${i}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const n=(new TextEncoder).encode(e),r=new Array(n.length);for(let e=0;e<n.length;e++)r[e]=String.fromCharCode(n[e]);const i=btoa(r.join(""));return t?i.replace(/[=]/g,""):i}(r,!0)}`}else i=`${i}/wc?${r}`;return i}(i,t,n),o=Bf();if(o===Nf){if(!ge()?.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(s)}else o===Sf&&typeof e?.Linking<"u"&&await e.Linking.openURL(s)}catch(e){console.error(e)}}function Qf(e,t){if(!e.includes(t))return null;const n=e.split(/([&,?,=])/),r=n.indexOf(t);return n[r+2]}function Xf(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function eg(){return typeof process<"u"&&"true"===process.env.IS_VITEST}function tg(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return(new TextDecoder).decode(r)}let ng=class{constructor({limit:e}){this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const e=this.set.values().next().value;e&&this.set.delete(e)}this.set.add(e)}}has(e){return this.set.has(e)}};const rg="https://rpc.walletconnect.org/v1";function ig(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function sg(e){const t=`Ethereum Signed Message:\n${e.length}`,n=(new TextEncoder).encode(t+e);return"0x"+Xo($t(n),"base16")}async function og(e,t,n,r,i,s){switch(n.t){case"eip191":return await function(e,t,n){const r=$i(n);return ds({payload:sg(t),signature:r}).toLowerCase()===e.toLowerCase()}(e,t,n.s);case"eip1271":return await async function(e,t,n,r,i,s){const o=vf(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c=n.substring(2),l=(c.length/2).toString(16).padStart(64,"0"),d=o+(t.startsWith("0x")?t:sg(t)).substring(2)+a+l+c,h=await fetch(`${s||rg}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:ag(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:u}=await h.json();return!!u&&u.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function ag(){return Date.now()+Math.floor(1e3*Math.random())}function cg(e){const t=ig(e),n=(new TextEncoder).encode("TransactionData::"),r=new Uint8Array(n.length+t.length);r.set(n),r.set(t,n.length);const i=Fi(r,{dkLen:32});return as.encode(i)}function lg(e){const t=new Uint8Array(en(function(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("object"==typeof e&&e?.data)return new Uint8Array(Object.values(e.data));if("object"==typeof e&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}(e)));return as.encode(t)}function dg(e){const t=function(e,t){return new Gs(t).decode(e)}(ig(e)).txn;if(!t)throw new Error("Invalid signed transaction: missing 'txn' field");const n=(s=t,new Ls(o).encodeSharedRef(s)),r=Qs([(new TextEncoder).encode("TX"),new Uint8Array(n)]),i=rn(r);var s,o;return os.encode(i).replace(/=+$/,"")}function hg(e){const t=[];let n=BigInt(e);for(;n>=0x80n;)t.push(Number(0x7fn&n|0x80n)),n>>=7n;return t.push(Number(n)),new Uint8Array(t)}function ug(e){const t=ig(e.signed.bodyBytes),n=ig(e.signed.authInfoBytes),r=ig(e.signature.signature),i=[];i.push(new Uint8Array([10])),i.push(hg(t.length)),i.push(t),i.push(new Uint8Array([18])),i.push(hg(n.length)),i.push(n),i.push(new Uint8Array([26])),i.push(hg(r.length)),i.push(r);const s=Qs(i);return Xo(en(s),"base16").toUpperCase()}const pg="did:pkh:",fg={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},gg=e=>e?.split(":"),mg=e=>{const t=e&&gg(e);if(t)return t[2]+":"+t[3]},yg=e=>{const t=e&&gg(e);if(t)return t.pop()};async function wg(e){const{cacao:t,projectId:n}=e,{s:r,p:i}=t,s=bg(i,i.iss),o=yg(i.iss);return await og(o,s,r,mg(i.iss),n)}const bg=(e,t)=>{const n=(e=>{const t=e&&gg(e);if(t)return e.includes(pg)?t[2]:t[0]})(t);if(!n)throw new Error("Invalid issuer: "+t);const r=`${e.domain} wants you to sign in with your ${(e=>e?fg[e]||e:"")(n)} account:`,i=yg(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0;const o=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${(e=>{const t=e&&gg(e);if(t)return e.includes(pg)?t[3]:t[1]})(t)}`,l=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,h=e.exp?`Expiration Time: ${e.exp}`:void 0,u=e.nbf?`Not Before: ${e.nbf}`:void 0,p=e.requestId?`Request ID: ${e.requestId}`:void 0,f=e.resources?`Resources:${e.resources.map(e=>`\n- ${e}`).join("")}`:void 0,g=Pg(e.resources);if(g){s=function(e="",t){vg(t);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(n))return e;const r=[];let i=0;Object.keys(t.att).forEach(e=>{const n=Object.keys(t.att[e]).map(e=>({ability:e.split("/")[0],action:e.split("/")[1]}));n.sort((e,t)=>e.action.localeCompare(t.action));const s={};n.forEach(e=>{s[e.ability]||(s[e.ability]=[]),s[e.ability].push(e.action)});const o=Object.keys(s).map(t=>(i++,`(${i}) '${t}': '${s[t].join("', '")}' for '${e}'.`));r.push(o.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${e?e+" ":""}${o}`}(s,Ag(g))}return[r,i,"",s,"",o,a,c,l,d,h,u,p,f].filter(e=>null!=e).join("\n")};function vg(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(!t?.length)throw new Error("No resources found in `att` property");t.forEach(t=>{const n=e.att[t];if(Array.isArray(n))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof n)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(n).forEach(e=>{const t=n[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach(t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)})})})}function Eg(e,t,n={}){t=t?.sort((e,t)=>e.localeCompare(t));const r=t.map(t=>({[`${e}/${t}`]:[n]}));return Object.assign({},...r)}function xg(e){return vg(e),`urn:recap:${function(e){const t=JSON.stringify(e),n=(new TextEncoder).encode(t),r=new Array(n.length);for(let e=0;e<n.length;e++)r[e]=String.fromCharCode(n[e]);return btoa(r.join(""))}(e).replace(/=/g,"")}`}function Ag(e){const t=function(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return JSON.parse((new TextDecoder).decode(r))}(e.replace("urn:recap:",""));return vg(t),t}function kg(e,t,n){const r=function(e,t,n,r={}){return n?.sort((e,t)=>e.localeCompare(t)),{att:{[e]:Eg(t,n,r)}}}(e,t,n);return xg(r)}function Ig(e,t){const n=function(e,t){vg(e),vg(t);const n=Object.keys(e.att).concat(Object.keys(t.att)).sort((e,t)=>e.localeCompare(t)),r={att:{}};return n.forEach(n=>{Object.keys(e.att?.[n]||{}).concat(Object.keys(t.att?.[n]||{})).sort((e,t)=>e.localeCompare(t)).forEach(i=>{r.att[n]={...r.att[n],[i]:e.att[n]?.[i]||t.att[n]?.[i]}})}),r}(Ag(e),Ag(t));return xg(n)}function Cg(e){const t=Ag(e);vg(t);const n=t.att?.eip155;return n?Object.keys(n).map(e=>e.split("/")[1]):[]}function Sg(e){const t=Ag(e);vg(t);const n=[];return Object.values(t.att).forEach(e=>{Object.values(e).forEach(e=>{e?.[0]?.chains&&n.push(e[0].chains)})}),[...new Set(n.flat())]}function Pg(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}const Ng="base10",_g="base16",Tg="base64pad",Og="base64url",$g="utf8";function Rg(){return Xo(yt(32),_g)}function Bg(e){return Xo(sn(Qo(e,_g)),_g)}function Mg(e){return Xo(sn(Qo(e,$g)),_g)}function Ug(e){return Qo(`${e}`,Ng)}function Lg(e){return Number(Xo(e,Ng))}function Dg(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function jg(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+"=".repeat(n)}function zg(e){if(2===Lg(e.type))return Xo(Qs([e.type,e.sealed]),Tg);if(1===Lg(e.type)){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Xo(Qs([e.type,e.senderPublicKey,e.iv,e.sealed]),Tg)}return Xo(Qs([e.type,e.iv,e.sealed]),Tg)}function Hg(e){const t=Qo((e.encoding||Tg)===Og?jg(e.encoded):e.encoded,Tg),n=t.slice(0,1);if(1===Lg(n)){const e=33,r=e+12,i=t.slice(1,e),s=t.slice(e,r);return{type:n,sealed:t.slice(r),iv:s,senderPublicKey:i}}if(2===Lg(n)){return{type:n,sealed:t.slice(1),iv:yt(12)}}const r=t.slice(1,13);return{type:n,sealed:t.slice(13),iv:r}}function Vg(e){const t=e?.type||0;if(1===t){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Fg(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function qg(e){return 2===e.type}function Wg(e,t){const[n,r,i]=e.split("."),s=Qo(jg(i),Tg);if(64!==s.length)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=sn(`${n}.${r}`),l=function(e){const t=Qo(jg(e.x),Tg),n=Qo(jg(e.y),Tg);return Qs([new Uint8Array([4]),t,n])}(t);if(!ul.verify(Qs([o,a]),c,l))throw new Error("Invalid signature");return Lu(e).payload}function Zg(e){return e?.relay||{protocol:"irn"}}function Kg(e){const t=zu[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Gg(e,t="-"){const n={},r="relay"+t;return Object.keys(e).forEach(t=>{if(t.startsWith(r)){const i=t.replace(r,""),s=e[t];n[i]=s}}),n}function Yg(e){if(!e.includes("wc:")){const t=tg(e);t?.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),n=-1!==e.indexOf("?")?e.indexOf("?"):void 0,r=e.substring(0,t),i=e.substring(t+1,n).split("@"),s=typeof n<"u"?e.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:r,topic:Jg(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:Gg(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Jg(e){return e.startsWith("//")?e.substring(2):e}function Qg(e,t="-"){const n={};return Object.keys(e).forEach(r=>{const i=r,s="relay"+t+i;e[i]&&(n[s]=e[i])}),n}function Xg(e){const t=new URLSearchParams,n={...Qg(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(n).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,n])=>{void 0!==n&&t.append(e,String(n))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function em(e,t,n){return`${e}?wc_ev=${n}&topic=${t}`}function tm(e){const t=[];return e.forEach(e=>{const[n,r]=e.split(":");t.push(`${n}:${r}`)}),t}function nm(e){const t=[];return Object.values(e).forEach(e=>{t.push(...tm(e.accounts))}),[...new Set(t)]}function rm(e){return e.includes(":")}function im(e){return rm(e)?e.split(":")[0]:e}function sm(e){const t={};if(!cm(e))return t;for(const[n,r]of Object.entries(e)){const e=rm(n)?[n]:r.chains,i=r.methods||[],s=r.events||[],o=im(n);t[o]={...t[o],chains:Yf(e,t[o]?.chains),methods:Yf(i,t[o]?.methods),events:Yf(s,t[o]?.events)}}return t}function om(e,t){t=t.map(e=>e.replace("did:pkh:",""));const n=function(e){const t={};return e?.forEach(e=>{const[n,r]=e.split(":");t[n]||(t[n]={accounts:[],chains:[],events:[],methods:[]}),t[n].accounts.push(e),t[n].chains?.push(`${n}:${r}`)}),t}(t);for(const[t,r]of Object.entries(n))r.methods?r.methods=Yf(r.methods,e):r.methods=e,r.events=["chainChanged","accountsChanged"];return n}function am(e,t){return!!Array.isArray(e)}function cm(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function lm(e){return typeof e>"u"}function dm(e,t){return!(!t||!lm(e))||"string"==typeof e&&!!e.trim().length}function hm(e,t){return!(!t||!lm(e))||"number"==typeof e&&!isNaN(e)}function um(e){return!(!dm(e,!1)||!e.includes(":"))&&2===e.split(":").length}function pm(e){let t=!0;return am(e)?e.length&&(t=e.every(e=>dm(e,!1))):t=!1,t}function fm(e,t,n){let r=null;return Object.entries(e).forEach(([e,i])=>{if(r)return;const s=function(e,t,n){let r=null;return am(t)&&t.length?t.forEach(e=>{r||um(e)||(r=Cf("UNSUPPORTED_CHAINS",`${n}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):um(e)||(r=Cf("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}(e,xf(e,i),`${t} ${n}`);s&&(r=s)}),r}function gm(e,t){let n=null;return am(e)?e.forEach(e=>{n||function(e){if(dm(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&um(e)}}return!1}(e)||(n=Cf("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):n=Cf("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function mm(e,t){let n=null;return Object.values(e).forEach(e=>{if(n)return;const r=function(e,t){let n=null;return pm(e?.methods)?pm(e?.events)||(n=Cf("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):n=Cf("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),n}(e,`${t}, namespace`);r&&(n=r)}),n}function ym(e,t){let n=null;if(e&&cm(e)){const r=mm(e,t);r&&(n=r);const i=function(e,t){let n=null;return Object.values(e).forEach(e=>{if(n)return;const r=gm(e?.accounts,`${t} namespace`);r&&(n=r)}),n}(e,t);i&&(n=i)}else n=If("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return n}function wm(e){return dm(e.protocol,!0)}function bm(e){return typeof e<"u"&&null!==typeof e}function vm(e,t){return!(!um(t)||!nm(e).includes(t))}function Em(e,t,n){return!!dm(n,!1)&&function(e,t){const n=[];return Object.values(e).forEach(e=>{tm(e.accounts).includes(t)&&n.push(...e.methods)}),n}(e,t).includes(n)}function xm(e,t,n){return!!dm(n,!1)&&function(e,t){const n=[];return Object.values(e).forEach(e=>{tm(e.accounts).includes(t)&&n.push(...e.events)}),n}(e,t).includes(n)}function Am(e,t,n){let r=null;const i=function(e){const t={};return Object.keys(e).forEach(n=>{n.includes(":")?t[n]=e[n]:e[n].chains?.forEach(r=>{t[r]={methods:e[n].methods,events:e[n].events}})}),t}(e),s=function(e){const t={};return Object.keys(e).forEach(n=>{n.includes(":")?t[n]=e[n]:tm(e[n].accounts)?.forEach(r=>{t[r]={accounts:e[n].accounts.filter(e=>e.includes(`${r}:`)),methods:e[n].methods,events:e[n].events}})}),t}(t),o=Object.keys(i),a=Object.keys(s),c=km(Object.keys(e)),l=km(Object.keys(t)),d=c.filter(e=>!l.includes(e));return d.length&&(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),jf(o,a)||(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||r)return;const i=tm(t[e].accounts);i.includes(e)||(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${i.toString()}`))}),o.forEach(e=>{r||(jf(i[e].methods,s[e].methods)?jf(i[e].events,s[e].events)||(r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${e}`)):r=If("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${e}`))}),r}function km(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Im(){const t=Bf();return new Promise(n=>{switch(t){case Nf:n(Rf()&&navigator?.onLine);break;case Sf:n(async function(){return!($f()&&typeof e<"u"&&e?.NetInfo)||(await(e?.NetInfo.fetch()))?.isConnected}());break;default:n(!0)}})}function Cm(t){switch(Bf()){case Nf:!function(e){!$f()&&Rf()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}(t);break;case Sf:!function(t){$f()&&typeof e<"u"&&e?.NetInfo&&e?.NetInfo.addEventListener(e=>t(e?.isConnected))}(t)}}const Sm={};let Pm=class{static get(e){return Sm[e]}static set(e,t){Sm[e]=t}static delete(e){delete Sm[e]}};function Nm({publicKey:e,signature:t,payload:n}){const r=_m(n.method),i=128|parseInt(n.version?.toString()||"4"),s=function(e){const t=as.decode(e)[0];return 42===t?0:60===t?2:1}(n.address),o="00"===n.era?new Uint8Array([0]):_m(n.era);if(1!==o.length&&2!==o.length)throw new Error("Invalid era length");const a=parseInt(n.nonce,16),c=new Uint8Array([255&a,a>>8&255]),l=BigInt(`0x${function(e){return e.startsWith("0x")?e.slice(2):e}(n.tip)}`),d=function(e){if(e<64n)return new Uint8Array([Number(e<<2n)]);if(e<16384n){const t=e<<2n|0x01n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn)])}if(e<1n<<30n){const t=e<<2n|0x02n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}throw new Error("BigInt compact encoding not supported > 2^30")}(l),h=new Uint8Array([0,...e,s,...t,...o,...c,...d,...r]),u=function(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){const t=e<<2|1;return new Uint8Array([255&t,t>>8&255])}if(e<1<<30){const t=e<<2|2;return new Uint8Array([255&t,t>>8&255,t>>16&255,t>>24&255])}throw new Error("Compact encoding > 2^30 not supported")}(h.length+1);return new Uint8Array([...u,i,...h])}function _m(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Tm(e){const t=_m(e.signature),n=function(e){const t=as.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}(e.transaction.address);return function(e){const t=_m(e);return"0x"+Xo(vp.blake2b(t,void 0,32),"base16")}(Xo(Nm({publicKey:n,signature:t,payload:e.transaction}),"base16"))}function Om({logger:e,name:t}){const n="string"==typeof e?bf({opts:{level:e,name:t}}).logger:e;return n.level="string"==typeof e?e:e.level,n}class $m{}let Rm=class extends $m{constructor(e){super()}};const Bm=U.FIVE_SECONDS,Mm="heartbeat_pulse";let Um=class e extends Rm{constructor(e){super(e),this.events=new I.EventEmitter,this.interval=Bm,this.interval=e?.interval||Bm}static async init(t){const n=new e(t);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}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 initialize(){this.intervalRef=setInterval(()=>this.pulse(),U.toMiliseconds(this.interval))}pulse(){this.events.emit(Mm)}};const Lm=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,Dm=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,jm=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function zm(e,t){if(!("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t))return t;!function(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}(e)}function Hm(e,t={}){if("string"!=typeof e)return e;if('"'===e[0]&&'"'===e[e.length-1]&&-1===e.indexOf("\\"))return e.slice(1,-1);const n=e.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!jm.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(Lm.test(e)||Dm.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,zm)}return JSON.parse(e)}catch(n){if(t.strict)throw n;return e}}function Vm(e,...t){try{return(n=e(...t))&&"function"==typeof n.then?n:Promise.resolve(n)}catch(e){return Promise.reject(e)}var n}function Fm(e){if(function(e){const t=typeof e;return null===e||"object"!==t&&"function"!==t}(e))return String(e);if(function(e){const t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}(e)||Array.isArray(e))return JSON.stringify(e);if("function"==typeof e.toJSON)return Fm(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const qm="base64:";function Wm(e){return"string"==typeof e?e:qm+function(e){if(globalThis.Buffer)return Buffer.from(e).toString("base64");return globalThis.btoa(String.fromCodePoint(...e))}(e)}function Zm(e){return"string"!=typeof e?e:e.startsWith(qm)?function(e){if(globalThis.Buffer)return Buffer.from(e,"base64");return Uint8Array.from(globalThis.atob(e),e=>e.codePointAt(0))}(e.slice(7)):e}function Km(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Gm(...e){return Km(e.join(":"))}function Ym(e){return(e=Km(e))?e+":":""}const Jm=()=>{const e=new Map;return{name:"memory",getInstance:()=>e,hasItem:t=>e.has(t),getItem:t=>e.get(t)??null,getItemRaw:t=>e.get(t)??null,setItem(t,n){e.set(t,n)},setItemRaw(t,n){e.set(t,n)},removeItem(t){e.delete(t)},getKeys:()=>[...e.keys()],clear(){e.clear()},dispose(){e.clear()}}};function Qm(e={}){const t={mounts:{"":e.driver||Jm()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=e=>{for(const n of t.mountpoints)if(e.startsWith(n))return{base:n,relativeKey:e.slice(n.length),driver:t.mounts[n]};return{base:"",relativeKey:e,driver:t.mounts[""]}},r=(e,n)=>t.mountpoints.filter(t=>t.startsWith(e)||n&&e.startsWith(t)).map(n=>({relativeBase:e.length>n.length?e.slice(n.length):void 0,mountpoint:n,driver:t.mounts[n]})),i=(e,n)=>{if(t.watching){n=Km(n);for(const r of t.watchListeners)r(e,n)}},s=async()=>{if(t.watching){for(const e in t.unwatch)await t.unwatch[e]();t.unwatch={},t.watching=!1}},o=(e,t,r)=>{const i=new Map,s=e=>{let t=i.get(e.base);return t||(t={driver:e.driver,base:e.base,items:[]},i.set(e.base,t)),t};for(const r of e){const e="string"==typeof r,i=Km(e?r:r.key),o=e?void 0:r.value,a=e||!r.options?t:{...t,...r.options},c=n(i);s(c).items.push({key:i,value:o,relativeKey:c.relativeKey,options:a})}return Promise.all([...i.values()].map(e=>r(e))).then(e=>e.flat())},a={hasItem(e,t={}){e=Km(e);const{relativeKey:r,driver:i}=n(e);return Vm(i.hasItem,r,t)},getItem(e,t={}){e=Km(e);const{relativeKey:r,driver:i}=n(e);return Vm(i.getItem,r,t).then(e=>Hm(e))},getItems:(e,t={})=>o(e,t,e=>e.driver.getItems?Vm(e.driver.getItems,e.items.map(e=>({key:e.relativeKey,options:e.options})),t).then(t=>t.map(t=>({key:Gm(e.base,t.key),value:Hm(t.value)}))):Promise.all(e.items.map(t=>Vm(e.driver.getItem,t.relativeKey,t.options).then(e=>({key:t.key,value:Hm(e)}))))),getItemRaw(e,t={}){e=Km(e);const{relativeKey:r,driver:i}=n(e);return i.getItemRaw?Vm(i.getItemRaw,r,t):Vm(i.getItem,r,t).then(e=>Zm(e))},async setItem(e,t,r={}){if(void 0===t)return a.removeItem(e);e=Km(e);const{relativeKey:s,driver:o}=n(e);o.setItem&&(await Vm(o.setItem,s,Fm(t),r),o.watch||i("update",e))},async setItems(e,t){await o(e,t,async e=>{if(e.driver.setItems)return Vm(e.driver.setItems,e.items.map(e=>({key:e.relativeKey,value:Fm(e.value),options:e.options})),t);e.driver.setItem&&await Promise.all(e.items.map(t=>Vm(e.driver.setItem,t.relativeKey,Fm(t.value),t.options)))})},async setItemRaw(e,t,r={}){if(void 0===t)return a.removeItem(e,r);e=Km(e);const{relativeKey:s,driver:o}=n(e);if(o.setItemRaw)await Vm(o.setItemRaw,s,t,r);else{if(!o.setItem)return;await Vm(o.setItem,s,Wm(t),r)}o.watch||i("update",e)},async removeItem(e,t={}){"boolean"==typeof t&&(t={removeMeta:t}),e=Km(e);const{relativeKey:r,driver:s}=n(e);s.removeItem&&(await Vm(s.removeItem,r,t),(t.removeMeta||t.removeMata)&&await Vm(s.removeItem,r+"$",t),s.watch||i("remove",e))},async getMeta(e,t={}){"boolean"==typeof t&&(t={nativeOnly:t}),e=Km(e);const{relativeKey:r,driver:i}=n(e),s=Object.create(null);if(i.getMeta&&Object.assign(s,await Vm(i.getMeta,r,t)),!t.nativeOnly){const e=await Vm(i.getItem,r+"$",t).then(e=>Hm(e));e&&"object"==typeof e&&("string"==typeof e.atime&&(e.atime=new Date(e.atime)),"string"==typeof e.mtime&&(e.mtime=new Date(e.mtime)),Object.assign(s,e))}return s},setMeta(e,t,n={}){return this.setItem(e+"$",t,n)},removeMeta(e,t={}){return this.removeItem(e+"$",t)},async getKeys(e,t={}){e=Ym(e);const n=r(e,!0);let i=[];const s=[];let o=!0;for(const e of n){e.driver.flags?.maxDepth||(o=!1);const n=await Vm(e.driver.getKeys,e.relativeBase,t);for(const t of n){const n=e.mountpoint+Km(t);i.some(e=>n.startsWith(e))||s.push(n)}i=[e.mountpoint,...i.filter(t=>!t.startsWith(e.mountpoint))]}const a=void 0!==t.maxDepth&&!o;return s.filter(n=>(!a||function(e,t){if(void 0===t)return!0;let n=0,r=e.indexOf(":");for(;r>-1;)n++,r=e.indexOf(":",r+1);return n<=t}(n,t.maxDepth))&&function(e,t){return t?e.startsWith(t)&&"$"!==e[e.length-1]:"$"!==e[e.length-1]}(n,e))},async clear(e,t={}){e=Ym(e),await Promise.all(r(e,!1).map(async e=>{if(e.driver.clear)return Vm(e.driver.clear,e.relativeBase,t);if(e.driver.removeItem){const n=await e.driver.getKeys(e.relativeBase||"",t);return Promise.all(n.map(n=>e.driver.removeItem(n,t)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(e=>ey(e)))},watch:async e=>(await(async()=>{if(!t.watching){t.watching=!0;for(const e in t.mounts)t.unwatch[e]=await Xm(t.mounts[e],i,e)}})(),t.watchListeners.push(e),async()=>{t.watchListeners=t.watchListeners.filter(t=>t!==e),0===t.watchListeners.length&&await s()}),async unwatch(){t.watchListeners=[],await s()},mount(e,n){if((e=Ym(e))&&t.mounts[e])throw new Error(`already mounted at ${e}`);return e&&(t.mountpoints.push(e),t.mountpoints.sort((e,t)=>t.length-e.length)),t.mounts[e]=n,t.watching&&Promise.resolve(Xm(n,i,e)).then(n=>{t.unwatch[e]=n}).catch(console.error),a},async unmount(e,n=!0){(e=Ym(e))&&t.mounts[e]&&(t.watching&&e in t.unwatch&&(t.unwatch[e]?.(),delete t.unwatch[e]),n&&await ey(t.mounts[e]),t.mountpoints=t.mountpoints.filter(t=>t!==e),delete t.mounts[e])},getMount(e=""){e=Km(e)+":";const t=n(e);return{driver:t.driver,base:t.base}},getMounts(e="",t={}){e=Km(e);return r(e,t.parents).map(e=>({driver:e.driver,base:e.mountpoint}))},keys:(e,t={})=>a.getKeys(e,t),get:(e,t={})=>a.getItem(e,t),set:(e,t,n={})=>a.setItem(e,t,n),has:(e,t={})=>a.hasItem(e,t),del:(e,t={})=>a.removeItem(e,t),remove:(e,t={})=>a.removeItem(e,t)};return a}function Xm(e,t,n){return e.watch?e.watch((e,r)=>t(e,n+r)):()=>{}}async function ey(e){"function"==typeof e.dispose&&await Vm(e.dispose)}function ty(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function ny(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const r=ty(n);return(e,n)=>r.then(r=>n(r.transaction(t,e).objectStore(t)))}let ry;function iy(){return ry||(ry=ny("keyval-store","keyval")),ry}function sy(e,t=iy()){return t("readonly",t=>ty(t.get(e)))}function oy(e=iy()){return e("readonly",e=>{if(e.getAllKeys)return ty(e.getAllKeys());const t=[];return function(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},ty(e.transaction)}(e,e=>t.push(e.key)).then(()=>t)})}var ay=(e={})=>{const t=e.base&&e.base.length>0?`${e.base}:`:"",n=e=>t+e;let r;return e.dbName&&e.storeName&&(r=ny(e.dbName,e.storeName)),{name:"idb-keyval",options:e,hasItem:async e=>!(typeof await sy(n(e),r)>"u"),getItem:async e=>await sy(n(e),r)??null,setItem:(e,t)=>function(e,t,n=iy()){return n("readwrite",n=>(n.put(t,e),ty(n.transaction)))}(n(e),t,r),removeItem:e=>function(e,t=iy()){return t("readwrite",t=>(t.delete(e),ty(t.transaction)))}(n(e),r),getKeys:()=>oy(r),clear:()=>function(e=iy()){return e("readwrite",e=>(e.clear(),ty(e.transaction)))}(r)}};let cy=class{constructor(){this.indexedDb=Qm({driver:ay({dbName:"WALLET_CONNECT_V2_INDEXED_DB",storeName:"keyvaluestorage"})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(null!==t)return t}async setItem(e,t){await this.indexedDb.setItem(e,fl(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ly=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof e<"u"?e:typeof self<"u"?self:{},dy={exports:{}};function hy(e){var t;return[e[0],pl(null!=(t=e[1])?t:"")]}!function(){let e;function t(){}e=t,e.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},e.prototype.setItem=function(e,t){this[e]=String(t)},e.prototype.removeItem=function(e){delete this[e]},e.prototype.clear=function(){const e=this;Object.keys(e).forEach(function(t){e[t]=void 0,delete e[t]})},e.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},e.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ly<"u"&&ly.localStorage?dy.exports=ly.localStorage:typeof window<"u"&&window.localStorage?dy.exports=window.localStorage:dy.exports=new t}();let uy=class{constructor(){this.localStorage=dy.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(hy)}async getItem(e){const t=this.localStorage.getItem(e);if(null!==t)return pl(t)}async setItem(e,t){this.localStorage.setItem(e,fl(t))}async removeItem(e){this.localStorage.removeItem(e)}};const py=async(e,t)=>{t.length&&t.forEach(async t=>{await e.removeItem(t)})};let fy=class{constructor(){this.initialized=!1,this.setInitialized=e=>{this.storage=e,this.initialized=!0};const e=new uy;this.storage=e;try{(async(e,t,n)=>{const r="wc_storage_version",i=await t.getItem(r);if(i&&i>=1)return void n(t);const s=await e.getKeys();if(!s.length)return void n(t);const o=[];for(;s.length;){const n=s.shift();if(!n)continue;const r=n.toLowerCase();if(r.includes("wc@")||r.includes("walletconnect")||r.includes("wc_")||r.includes("wallet_connect")){const r=await e.getItem(n);await t.setItem(n,r),o.push(n)}}await t.setItem(r,1),n(t),py(e,o)})(e,new cy,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}},gy=class extends $m{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},my=class extends $m{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}},yy=class{constructor(e,t){this.logger=e,this.core=t}},wy=class extends $m{constructor(e,t){super(),this.relayer=e,this.logger=t}},by=class extends $m{constructor(e){super()}},vy=class{constructor(e,t,n,r){this.core=e,this.logger=t,this.name=n}},Ey=class extends $m{constructor(e,t){super(),this.relayer=e,this.logger=t}},xy=class extends $m{constructor(e,t){super(),this.core=e,this.logger=t}},Ay=class{constructor(e,t,n){this.core=e,this.logger=t,this.store=n}},ky=class{constructor(e,t){this.projectId=e,this.logger=t}},Iy=class{constructor(e,t,n){this.core=e,this.logger=t,this.telemetryEnabled=n}},Cy=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},Sy=class{constructor(e){this.client=e}};const Py="PARSE_ERROR",Ny="INVALID_REQUEST",_y="METHOD_NOT_FOUND",Ty="INVALID_PARAMS",Oy="INTERNAL_ERROR",$y="SERVER_ERROR",Ry=[-32700,-32600,-32601,-32602,-32603],By={[Py]:{code:-32700,message:"Parse error"},[Ny]:{code:-32600,message:"Invalid Request"},[_y]:{code:-32601,message:"Method not found"},[Ty]:{code:-32602,message:"Invalid params"},[Oy]:{code:-32603,message:"Internal error"},[$y]:{code:-32e3,message:"Server error"}},My=$y;function Uy(e){return Object.keys(By).includes(e)?By[e]:By[My]}function Ly(e,t,n){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${t}`):e}var Dy,jy={},zy={};var Hy,Vy={};function Fy(e=3){return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function qy(e=6){return BigInt(Fy(e))}function Wy(e,t,n){return{id:n||Fy(),jsonrpc:"2.0",method:e,params:t}}function Zy(e,t){return{id:e,jsonrpc:"2.0",result:t}}function Ky(e,t,n){return{id:e,jsonrpc:"2.0",error:Gy(t)}}function Gy(e,t){return void 0===e?Uy(Oy):("string"==typeof e&&(e=Object.assign(Object.assign({},Uy($y)),{message:e})),n=e.code,Ry.includes(n)&&(e=function(e){const t=Object.values(By).find(t=>t.code===e);return t||By[My]}(e.code)),e);var n}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=q;t.__exportStar(function(){if(Dy)return zy;function e(){return(null==o?void 0:o.crypto)||(null==o?void 0:o.msCrypto)||{}}function t(){const t=e();return t.subtle||t.webkitSubtle}return Dy=1,Object.defineProperty(zy,"__esModule",{value:!0}),zy.isBrowserCryptoAvailable=zy.getSubtleCrypto=zy.getBrowerCrypto=void 0,zy.getBrowerCrypto=e,zy.getSubtleCrypto=t,zy.isBrowserCryptoAvailable=function(){return!!e()&&!!t()},zy}(),e),t.__exportStar(function(){if(Hy)return Vy;function e(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product}function t(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}return Hy=1,Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.isBrowser=Vy.isNode=Vy.isReactNative=void 0,Vy.isReactNative=e,Vy.isNode=t,Vy.isBrowser=function(){return!e()&&!t()},Vy}(),e)}(jy);let Yy=class{},Jy=class extends Yy{constructor(){super()}},Qy=class extends Jy{constructor(e){super()}};function Xy(e,t){const n=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return void 0!==n&&new RegExp(t).test(n)}function ew(e){return Xy(e,"^https?:")}function tw(e){return Xy(e,"^wss?:")}function nw(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function rw(e){return nw(e)&&"method"in e}function iw(e){return nw(e)&&(sw(e)||ow(e))}function sw(e){return"result"in e}function ow(e){return"error"in e}let aw=class extends Qy{constructor(e){super(e),this.events=new I.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(Wy(e.method,e.params||[],e.id||qy().toString()),t)}async requestStrict(e,t){return new Promise(async(n,r)=>{if(!this.connection.connected)try{await this.open()}catch(e){r(e)}this.events.on(`${e.id}`,e=>{ow(e)?r(e.error):n(e.result)});try{await this.connection.send(e,t)}catch(e){r(e)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),iw(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&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(),"string"==typeof e&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};var cw,lw;const dw=e=>e.split("?")[0],hw=typeof WebSocket<"u"?WebSocket:typeof e<"u"&&typeof e.WebSocket<"u"?e.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:lw?cw:(lw=1,cw=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")});let uw=class{constructor(e){if(this.url=e,this.events=new I.EventEmitter,this.registering=!1,!tw(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)=>{typeof this.socket>"u"?t(new Error("Connection already closed")):(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close())})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(fl(e))}catch(t){this.onError(e.id,t)}}register(t=this.url){if(!tw(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise((e,t)=>{this.events.once("register_error",e=>{this.resetMaxListeners(),t(e)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const i=jy.isReactNative()?void 0:{rejectUnauthorized:(o=t,!new RegExp("wss?://localhost(:d{2,5})?").test(o))},s=new hw(t,[],i);var o;typeof WebSocket<"u"||typeof e<"u"&&typeof e.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?s.onerror=e=>{const t=e;r(this.emitError(t.error))}:s.on("error",e=>{r(this.emitError(e))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),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="string"==typeof e.data?pl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),r=Ky(e,n.message||n.toString());this.events.emit("payload",r)}parseError(e,t=this.url){return Ly(e,dw(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${dw(this.url)}`));return this.events.emit("register_error",t),t}};function pw(e){return null!=e&&"function"!=typeof e&&function(e){return Number.isSafeInteger(e)&&e>=0}(e.length)}function fw(e){return"__proto__"===e}function gw(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function mw(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function yw(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const ww="[object RegExp]",bw="[object String]",vw="[object Number]",Ew="[object Boolean]",xw="[object Arguments]",Aw="[object Symbol]",kw="[object Date]",Iw="[object Map]",Cw="[object Set]",Sw="[object Array]",Pw="[object ArrayBuffer]",Nw="[object Object]",_w="[object DataView]",Tw="[object Uint8Array]",Ow="[object Uint8ClampedArray]",$w="[object Uint16Array]",Rw="[object Uint32Array]",Bw="[object Int8Array]",Mw="[object Int16Array]",Uw="[object Int32Array]",Lw="[object Float32Array]",Dw="[object Float64Array]";function jw(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function zw(e,t,n,r=new Map,i=void 0){const s=i?.(e,t,n,r);if(void 0!==s)return s;if(gw(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){const t=new Array(e.length);r.set(e,t);for(let s=0;s<e.length;s++)t[s]=zw(e[s],s,n,r,i);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;r.set(e,t);for(const[s,o]of e)t.set(s,zw(o,s,n,r,i));return t}if(e instanceof Set){const t=new Set;r.set(e,t);for(const s of e)t.add(zw(s,void 0,n,r,i));return t}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e.subarray();if(jw(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);r.set(e,t);for(let s=0;s<e.length;s++)t[s]=zw(e[s],s,n,r,i);return t}if(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,t),Hw(t,e,n,r,i),t}if("undefined"!=typeof File&&e instanceof File){const t=new File([e],e.name,{type:e.type});return r.set(e,t),Hw(t,e,n,r,i),t}if("undefined"!=typeof Blob&&e instanceof Blob){const t=new Blob([e],{type:e.type});return r.set(e,t),Hw(t,e,n,r,i),t}if(e instanceof Error){const t=new e.constructor;return r.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,Hw(t,e,n,r,i),t}if(e instanceof Boolean){const t=new Boolean(e.valueOf());return r.set(e,t),Hw(t,e,n,r,i),t}if(e instanceof Number){const t=new Number(e.valueOf());return r.set(e,t),Hw(t,e,n,r,i),t}if(e instanceof String){const t=new String(e.valueOf());return r.set(e,t),Hw(t,e,n,r,i),t}if("object"==typeof e&&function(e){switch(yw(e)){case xw:case Sw:case Pw:case _w:case Ew:case kw:case Lw:case Dw:case Bw:case Mw:case Uw:case Iw:case vw:case Nw:case ww:case Cw:case bw:case Aw:case Tw:case Ow:case $w:case Rw:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return r.set(e,t),Hw(t,e,n,r,i),t}return e}function Hw(e,t,n=e,r,i){const s=[...Object.keys(t),...mw(t)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=zw(t[a],a,n,r,i))}}function Vw(e,t){return function(e,t){return zw(e,void 0,e,new Map,t)}(e,(t,n,r,i)=>{if("object"==typeof e){if(yw(e)===Nw&&"function"!=typeof e.constructor){const t={};return i.set(e,t),Hw(t,e,r,i),t}switch(Object.prototype.toString.call(e)){case vw:case bw:case Ew:{const t=new e.constructor(e?.valueOf());return Hw(t,e),t}case xw:{const t={};return Hw(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function Fw(e){return Vw(e)}function qw(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===yw(e)}function Ww(e){return"object"==typeof e&&null!==e}function Zw(e){return Ww(e)&&pw(e)}function Kw(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function Gw(e,t,n,r,i,s,o){const a=o(e,t,n,r,i,s);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return Yw(e,t,s,o)}return Yw(e,t,s,o)}function Yw(e,t,n,r){if(Object.is(e,t))return!0;let i=yw(e),s=yw(t);if(i===xw&&(i=Nw),s===xw&&(s=Nw),i!==s)return!1;switch(i){case bw:return e.toString()===t.toString();case vw:{const n=e.valueOf(),r=t.valueOf();return(o=n)===(a=r)||Number.isNaN(o)&&Number.isNaN(a)}case Ew:case kw:case Aw:return Object.is(e.valueOf(),t.valueOf());case ww:return e.source===t.source&&e.flags===t.flags;case"[object Function]":return e===t}var o,a;const c=(n=n??new Map).get(e),l=n.get(t);if(null!=c&&null!=l)return c===t;n.set(e,t),n.set(t,e);try{switch(i){case Iw:if(e.size!==t.size)return!1;for(const[i,s]of e.entries())if(!t.has(i)||!Gw(s,t.get(i),i,e,t,n,r))return!1;return!0;case Cw:{if(e.size!==t.size)return!1;const i=Array.from(e.values()),s=Array.from(t.values());for(let o=0;o<i.length;o++){const a=i[o],c=s.findIndex(i=>Gw(a,i,void 0,e,t,n,r));if(-1===c)return!1;s.splice(c,1)}return!0}case Sw:case Tw:case Ow:case $w:case Rw:case"[object BigUint64Array]":case Bw:case Mw:case Uw:case"[object BigInt64Array]":case Lw:case Dw:if("undefined"!=typeof Buffer&&Buffer.isBuffer(e)!==Buffer.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Gw(e[i],t[i],i,e,t,n,r))return!1;return!0;case Pw:return e.byteLength===t.byteLength&&Yw(new Uint8Array(e),new Uint8Array(t),n,r);case _w:return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Yw(new Uint8Array(e),new Uint8Array(t),n,r);case"[object Error]":return e.name===t.name&&e.message===t.message;case Nw:{if(!(Yw(e.constructor,t.constructor,n,r)||Kw(e)&&Kw(t)))return!1;const i=[...Object.keys(e),...mw(e)],s=[...Object.keys(t),...mw(t)];if(i.length!==s.length)return!1;for(let s=0;s<i.length;s++){const o=i[s],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!Gw(a,t[o],o,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Jw(){}function Qw(e,t){return function(e,t,n){return Gw(e,t,void 0,void 0,void 0,void 0,n)}(e,t,Jw)}function Xw(e){return jw(e)}function eb(e){if("object"!=typeof e)return!1;if(null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];if(null==t)return!1;return!!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function tb(e,t,n,r){if(gw(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(r.has(t))return function(e){if(gw(e))return e;if(Array.isArray(e)||jw(e)||e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(null==t)return Object.assign(Object.create(t),e);const n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){const t=new n(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new n(e.errors,e.message,{cause:e.cause}):new n(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}if("undefined"!=typeof File&&e instanceof File)return new n([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const n=Object.create(t);return Object.assign(n,e)}return e}(r.get(t));if(r.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const i=[...Object.keys(t),...mw(t)];for(let s=0;s<i.length;s++){const o=i[s];if(fw(o))continue;let a=t[o],c=e[o];if(qw(a)&&(a={...a}),qw(c)&&(c={...c}),"undefined"!=typeof Buffer&&Buffer.isBuffer(a)&&(a=Fw(a)),Array.isArray(a))if(Array.isArray(c)){const e=[],t=Reflect.ownKeys(c);for(let n=0;n<t.length;n++){const r=t[n];e[r]=c[r]}c=e}else if(Zw(c)){const e=[];for(let t=0;t<c.length;t++)e[t]=c[t];c=e}else c=[];const l=n(c,a,o,e,t,r);void 0!==l?e[o]=l:Array.isArray(a)||Ww(c)&&Ww(a)&&(eb(c)||eb(a)||Xw(c)||Xw(a))?e[o]=tb(c,a,n,r):null==c&&eb(a)?e[o]=tb({},a,n,r):null==c&&Xw(a)?e[o]=Fw(a):void 0!==c&&void 0===a||(e[o]=a)}return e}function nb(e,...t){return function(e,...t){const n=t.slice(0,-1),r=t[t.length-1];let i=e;for(let e=0;e<n.length;e++)i=tb(i,n[e],r,new Map);return i}(e,...t,Jw)}const rb="core",ib=`wc@2:${rb}:`,sb="error",ob={database:":memory:"},ab="client_ed25519_seed",cb=U.ONE_DAY,lb=U.SIX_HOURS,db="wss://relay.walletconnect.org",hb="relayer_message",ub="relayer_message_ack",pb="relayer_connect",fb="relayer_disconnect",gb="relayer_error",mb="relayer_connection_stalled",yb="relayer_publish",wb="payload",bb="connect",vb="disconnect",Eb="error",xb="2.23.9",Ab={link_mode:"link_mode",relay:"relay"},kb="inbound",Ib="outbound",Cb="WALLETCONNECT_LINK_MODE_APPS",Sb="subscription_created",Pb="subscription_deleted",Nb="subscription_sync",_b="subscription_resubscribed",Tb={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}}},Ob="pairing_create",$b="pairing_expire",Rb="pairing_delete",Bb="pairing_ping",Mb="history_created",Ub="history_updated",Lb="history_deleted",Db="history_sync",jb="expirer_created",zb="expirer_deleted",Hb="expirer_expired",Vb="expirer_sync",Fb="https://verify.walletconnect.org",qb=Fb,Wb=`${qb}/v3`,Zb=["https://verify.walletconnect.com",Fb],Kb="pairing_started",Gb="pairing_uri_validation_success",Yb="pairing_uri_not_expired",Jb="store_new_pairing",Qb="subscribing_pairing_topic",Xb="subscribe_pairing_topic_success",ev="existing_pairing",tv="pairing_not_expired",nv="emit_inactive_pairing",rv="emit_session_proposal",iv="no_internet_connection",sv="malformed_pairing_uri",ov="active_pairing_already_exists",av="subscribe_pairing_topic_failure",cv="pairing_expired",lv="proposal_listener_not_found",dv="session_approve_started",hv="session_namespaces_validation_success",uv="subscribing_session_topic",pv="subscribe_session_topic_success",fv="session_approve_publish_success",gv="store_session",mv="session_request_response_started",yv="session_request_response_validation_success",wv="session_request_response_publish_started",bv="no_internet_connection",vv="proposal_expired",Ev="subscribe_session_topic_failure",xv="session_approve_namespace_validation_failure",Av="proposal_not_found",kv="session_request_response_validation_failure",Iv="session_request_response_publish_failure",Cv="authenticated_session_approve_started",Sv="create_authenticated_session_topic",Pv="cacaos_verified",Nv="store_authenticated_session",_v="subscribing_authenticated_session_topic",Tv="subscribe_authenticated_session_topic_success",Ov="publishing_authenticated_session_approve",$v="no_internet_connection",Rv="invalid_cacao",Bv="subscribe_authenticated_session_topic_failure",Mv="authenticated_session_approve_publish_failure",Uv="authenticated_session_pending_request_not_found";let Lv=class{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name="keychain",this.version="0.3",this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=wf(t,this.name)}get context(){return yf(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,zf(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Hf(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Dv=class{constructor(e,t,n){this.core=e,this.logger=t,this.name="crypto",this.randomSessionIdentifier=Rg(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const e=Mu(Du(await this.getClientSeed()).publicKey);return this.clientId=e,e},this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=Dc.utils.randomPrivateKey(),t=Dc.getPublicKey(e);return{privateKey:Xo(e,_g),publicKey:Xo(t,_g)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Du(await this.getClientSeed()),n=this.randomSessionIdentifier,r=cb;return await ju(n,e,r,t)},this.generateSharedKey=(e,t,n)=>{this.isInitialized();const r=function(e,t){const n=Dc.getSharedSecret(Qo(e,_g),Qo(t,_g));return Xo(Aa(sn,n,void 0,void 0,32),_g)}(this.getPrivateKey(e),t);return this.setSymKey(r,n)},this.setSymKey=async(e,t)=>{this.isInitialized();const n=t||Bg(e);return await this.keychain.set(n,e),n},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,n)=>{this.isInitialized();const r=Vg(n),i=fl(t);if(qg(r))return function(e,t){const n=Ug(2),r=yt(12),i=zg({type:n,sealed:Qo(e,$g),iv:r});return t===Og?Dg(i):i}(i,n?.encoding);if(Fg(r)){const t=r.senderPublicKey,n=r.receiverPublicKey;e=await this.generateSharedKey(t,n)}const s=this.getSymKey(e),{type:o,senderPublicKey:a}=r;return function(e){const t=Ug(typeof e.type<"u"?e.type:0);if(1===Lg(t)&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof e.senderPublicKey<"u"?Qo(e.senderPublicKey,_g):void 0,r=typeof e.iv<"u"?Qo(e.iv,_g):yt(12),i=Qo(e.symKey,_g),s=zg({type:t,sealed:ba(i,r).encrypt(Qo(e.message,$g)),iv:r,senderPublicKey:n});return e.encoding===Og?Dg(s):s}({type:o,symKey:s,message:i,senderPublicKey:a,encoding:n?.encoding})},this.decode=async(e,t,n)=>{this.isInitialized();const r=function(e,t){const n=Hg({encoded:e,encoding:t?.encoding});return Vg({type:Lg(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?Xo(n.senderPublicKey,_g):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,n);if(qg(r)){const e=function(e,t){const{sealed:n}=Hg({encoded:e,encoding:t});return Xo(n,$g)}(t,n?.encoding);return pl(e)}if(Fg(r)){const t=r.receiverPublicKey,n=r.senderPublicKey;e=await this.generateSharedKey(t,n)}try{const r=function(e){const t=Qo(e.symKey,_g),{sealed:n,iv:r}=Hg({encoded:e.encoded,encoding:e.encoding}),i=ba(t,r).decrypt(n);if(null===i)throw new Error("Failed to decrypt");return Xo(i,$g)}({symKey:this.getSymKey(e),encoded:t,encoding:n?.encoding});return pl(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=(e,t=Tg)=>Lg(Hg({encoded:e,encoding:t}).type),this.getPayloadSenderPublicKey=(e,t=Tg)=>{const n=Hg({encoded:e,encoding:t});return n.senderPublicKey?Xo(n.senderPublicKey,_g):void 0},this.core=e,this.logger=wf(t,this.name),this.keychain=n||new Lv(this.core,this.logger)}get context(){return yf(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(ab)}catch{e=Rg(),await this.keychain.set(ab,e)}return Qo(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},jv=class extends yy{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t,n)=>{this.isInitialized();const r=Mg(t);let i=this.messages.get(e);if(typeof i>"u"&&(i={}),typeof i[r]<"u")return r;if(i[r]=t,this.messages.set(e,i),n===kb){const n=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,{...n,[r]:t})}return await this.persist(),r},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.getWithoutAck=e=>{this.isInitialized();const t={};for(const n of e){const e=this.messagesWithoutClientAck.get(n)||{};t[n]=Object.values(e)}return t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[Mg(t)]<"u"},this.ack=async(e,t)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(e);if(typeof n>"u")return;delete n[Mg(t)],0===Object.keys(n).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,n),await this.persist()},this.del=async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()},this.logger=wf(e,this.name),this.core=t}get context(){return yf(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,zf(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,zf(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Hf(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Hf(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},zv=class extends wy{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new I.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=U.toMiliseconds(U.ONE_MINUTE),this.initialPublishTimeout=U.toMiliseconds(15*U.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(e,t,n)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:n}});const r=n?.ttl||lb,i=n?.prompt||!1,s=n?.tag||0,o=n?.id||qy().toString(),a=Kg(Zg().protocol),c={id:o,method:n?.publishMethod||a.publish,params:{topic:e,message:t,ttl:r,prompt:i,tag:s,attestation:n?.attestation,...n?.tvf}},l=`Failed to publish payload, please try again. id:${o} tag:${s}`;try{lm(c.params?.prompt)&&delete c.params?.prompt,lm(c.params?.tag)&&delete c.params?.tag;const r=new Promise(async e=>{const t=({id:n})=>{c.id?.toString()===n.toString()&&(this.removeRequestFromQueue(n),this.relayer.events.removeListener(yb,t),e())};this.relayer.events.on(yb,t);const r=Ff(new Promise((e,t)=>{this.rpcPublish(c,n).then(e).catch(e=>{this.logger.warn(e,e?.message),t(e)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${o} tag:${s}`);try{await r,this.events.removeListener(yb,t)}catch(e){this.queue.set(o,{request:c,opts:n,attempt:1}),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:o,topic:e,message:t,opts:n}}),await Ff(r,this.publishTimeout,l)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),n?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(o)}},this.publishCustom=async e=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:e});const{payload:t,opts:n={}}=e,{attestation:r,tvf:i,publishMethod:s,prompt:o,tag:a,ttl:c=U.FIVE_MINUTES}=n,l=n.id||qy().toString(),d=Kg(Zg().protocol),h=s||d.publish,u={id:l,method:h,params:{...t,ttl:c,prompt:o,tag:a,attestation:r,...i}},p=`Failed to publish custom payload, please try again. id:${l} tag:${a}`;try{lm(u.params?.prompt)&&delete u.params?.prompt,lm(u.params?.tag)&&delete u.params?.tag;const e=new Promise(async e=>{const t=({id:n})=>{u.id?.toString()===n.toString()&&(this.removeRequestFromQueue(n),this.relayer.events.removeListener(yb,t),e())};this.relayer.events.on(yb,t);const r=Ff(new Promise((e,t)=>{this.rpcPublish(u,n).then(e).catch(e=>{this.logger.warn(e,e?.message),t(e)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${h} id:${l} tag:${a}`);try{await r,this.events.removeListener(yb,t)}catch(e){this.queue.set(l,{request:u,opts:n,attempt:1}),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,payload:t,opts:n}}),await Ff(e,this.publishTimeout,p)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),n?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(l)}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=wf(t,this.name),this.registerEventListeners()}get context(){return yf(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(yb,{...e,...t}),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const n=e.attempt+1;this.queue.set(t,{...e,attempt:n}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${e.request.params?.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Mm,()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(mb);this.checkQueue()}),this.relayer.on(ub,e=>{this.removeRequestFromQueue(e.id.toString())})}},Hv=class{constructor(){this.map=new Map,this.set=(e,t)=>{const n=this.get(e);this.exists(e,t)||this.map.set(e,[...n,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,t))return;const r=n.filter(e=>e!==t);r.length?this.map.set(e,r):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Vv=class extends Ey{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new Hv,this.events=new I.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.subscribeTimeout=U.toMiliseconds(U.ONE_MINUTE),this.initialSubscribeTimeout=U.toMiliseconds(15*U.ONE_SECOND),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const n=Zg(t),r={topic:e,relay:n,transportType:t?.transportType};t?.internal?.skipSubscribe||this.pending.set(e,r);const i=await this.rpcSubscribe(e,n,t);return"string"==typeof i&&(this.onSubscribe(i,r),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),i}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=e=>new Promise(t=>{t(this.topicMap.topics.includes(e))}),this.isKnownTopic=e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))}),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(Mm,async()=>{await this.checkPending()}),this.events.on(Sb,async e=>{const t=Sb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Pb,async e=>{const t=Pb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})},this.relayer=e,this.logger=wf(t,this.name),this.clientId=""}get context(){return yf(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 n=!1;try{n=this.getSubscription(e).topic===t}catch{}return n}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 n=this.topicMap.get(e);await Promise.all(n.map(async n=>await this.unsubscribeById(e,n,t)))}async unsubscribeById(e,t,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}});try{const r=Cf("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r);const i=Zg(n);await this.restartToComplete({topic:e,id:t,relay:i}),await this.rpcUnsubscribe(e,t,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,n){const r=await this.getSubscriptionId(e);if(n?.internal?.skipSubscribe)return r;(!n||n?.transportType===Ab.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const i={method:Kg(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});const s=n?.internal?.throwOnFailedPublish;try{if(n?.transportType===Ab.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(i).catch(e=>this.logger.warn(e))},U.toMiliseconds(U.ONE_SECOND)),r;const t=new Promise(async t=>{const n=r=>{r.topic===e&&(this.events.removeListener(Sb,n),t(r.id))};this.events.on(Sb,n);try{const r=await Ff(new Promise((e,t)=>{this.relayer.request(i).catch(e=>{this.logger.warn(e,e?.message),t(e)}).then(e)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Sb,n),t(r)}catch{}}),o=await Ff(t,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&s)throw new Error(`Subscribing to ${e} failed, please try again`);return o?r:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(mb),s)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t={method:Kg(e[0].relay.protocol).batchSubscribe,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await Ff(new Promise((e,n)=>{this.relayer.request(t).then(e).catch(e=>{this.logger.warn(e),n(e)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(mb),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:Kg(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map(e=>e.topic)}};let n;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{n=await await Ff(new Promise((e,n)=>{this.relayer.request(t).catch(e=>{this.logger.warn(e),n(e)}).then(e)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(mb)}return n}rpcUnsubscribe(e,t,n){const r={method:Kg(n.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,{...t,id:e}),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,{...e}),this.pending.delete(e.topic)})}async onUnsubscribe(e,t,n){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,n),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,{...t}),this.topicMap.set(t.topic,e),this.events.emit(Sb,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:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Pb,{...n,reason:t})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Nb)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<t;n++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit(_b)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(e=>e.topic===this.subscriptions.get(e.id)?.topic)){const{message:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e))return this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),void e.forEach(e=>{this.pending.set(e.topic,e)});this.onBatchSubscribe(await Promise.all(e.map(async e=>({...e,id:await this.getSubscriptionId(e.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 function(e){return new Promise(t=>setTimeout(t,e))}(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}=If("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 Mg(e+await this.getClientId())}},Fv=class extends by{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new I.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=U.toMiliseconds(15*U.ONE_SECOND),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=U.toMiliseconds(2*U.ONE_SECOND),this.stalledRestartMaxInterval=U.toMiliseconds(U.THIRTY_SECONDS),this.request=async e=>{this.logger.debug("Publishing Request Payload");const t=e.id||qy().toString();await this.toEstablishConnection();try{this.logger.trace({id:t,method:e.method,topic:e.params?.topic},"relayer.request - publishing...");const n=`${t}:${e.params?.tag||""}`;this.requestsInFlight.push(n);const r=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter(e=>e!==n),r}catch(e){throw this.logger.debug(`Failed to Publish Request: ${t}`),e}},this.resetPingTimeout=()=>{Of()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(e){this.logger.warn(e,e?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=e=>{this.onProviderPayload(e),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(pb)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(gb,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(e=>this.logger.warn(e))},this.registerProviderListeners=()=>{this.provider.on(wb,this.onPayloadHandler),this.provider.on(bb,this.onConnectHandler),this.provider.on(vb,this.onDisconnectHandler),this.provider.on(Eb,this.onProviderErrorHandler)},this.core=t.core,this.logger=Om({logger:t.logger??"error",name:this.name}),this.messages=new jv(this.logger,t.core),this.subscriber=new Vv(this,this.logger),this.publisher=new zv(this,this.logger),this.projectId=t.projectId,this.relayUrl=t.relayUrl||db,$f()&&typeof e<"u"&&typeof e?.Platform<"u"&&"android"===e?.Platform.OS?this.packageName=Mf():$f()&&typeof e<"u"&&typeof e?.Platform<"u"&&"ios"===e?.Platform.OS&&(this.bundleId=Mf()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return yf(this.logger)}get connected(){return 1===this.provider?.connection?.socket?.readyState}get connecting(){return 0===this.provider?.connection?.socket?.readyState||void 0!==this.connectPromise}async publish(e,t,n){this.isInitialized(),await this.publisher.publish(e,t,n),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Ab.relay},Ib)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){this.isInitialized(),(!t?.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const n=t?.internal?.throwOnFailedPublish??!0;let r,i=this.subscriber.topicMap.get(e)?.[0]||"";const s=t=>{t.topic===e&&(this.subscriber.off(Sb,s),r())};return await Promise.all([new Promise(e=>{r=e,this.subscriber.on(Sb,s)}),new Promise((r,s)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:n},...t}).then(e=>{i=e||i,r()}).catch(e=>{n?s(e):r()})})]),i}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 Ff(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(e){if(this.subscriber.hasAnyTopics){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=this.connect(e).finally(()=>{this.connectPromise=void 0}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.info("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await Im())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort((e,t)=>e.publishedAt-t.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:n}=e;if(!t.sessionExists){const e={topic:n,expiry:Zf(U.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,e)}this.events.emit(hb,e),await this.recordMessageEvent(e,kb)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let t=1;try{for(;t<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise((e,t)=>{const n=()=>{t(new Error("Connection interrupted while trying to connect"))};this.provider.once(vb,n),Ff(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>e()).catch(t).finally(()=>{this.provider.off(vb,n),clearTimeout(this.reconnectTimeout)})}),await new Promise((e,t)=>{const n=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(vb,n),this.subscriber.start().then(e).catch(t).finally(()=>{this.provider.off(vb,n)})}),this.hasExperiencedNetworkDisruption=!1}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(e=>setTimeout(e,U.toMiliseconds(1*t))),t++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(Of())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await Ff(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new aw(new uw(Df({sdkVersion:xb,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:n,message:r}=e;await this.messages.set(n,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:n}=e;if(!n||0===n.length)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),rw(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:n,message:r,publishedAt:i,attestation:s}=t.data,o={topic:n,message:r,publishedAt:i,transportType:Ab.relay,attestation:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:t.id,...o}),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else iw(e)&&this.events.emit(ub,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,kb),this.events.emit(hb,e))}async acknowledgePayload(e){const t=Zy(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(wb,this.onPayloadHandler),this.provider.off(bb,this.onConnectHandler),this.provider.off(vb,this.onDisconnectHandler),this.provider.off(Eb,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Im();Cm(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(e=>this.logger.error(e,e?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Mm,async()=>{if(!(this.transportExplicitlyClosed||this.connected||Rf()&&ge()&&"visible"!==ge()?.visibilityState))try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}),this.events.on(mb,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const e=0===this.stalledRestartBackoff?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${e?` in ${e}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(e){this.logger.error(e,e?.message)}finally{this.stalledRestartInProgress=!1}},e)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(fb),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed)return void(this.reconnectInProgress=!1);this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},U.toMiliseconds(.1))}}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}},qv=class extends vy{constructor(e,t,n,r=ib,i=void 0){super(e,t,n,r),this.core=e,this.logger=t,this.name=n,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{this.getKey&&null!==e&&!lm(e)?this.map.set(this.getKey(e),e):function(e){return e?.proposer?.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)}),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(n=>Qw(t[n],e[n]))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const n={...this.getData(e),...t};this.map.set(e,n),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())},this.logger=wf(t,this.name),this.storagePrefix=r,this.getKey=i}get context(){return yf(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:t}=If("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}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:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wv=class{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new C,this.initialized=!1,this.storagePrefix=ib,this.ignoredPayloadTypes=[1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async e=>{this.isInitialized();const t=Rg(),n=await this.core.crypto.setSymKey(t),r=Zf(U.FIVE_MINUTES),i={protocol:"irn"},s={topic:n,expiry:r,relay:i,active:!1,methods:e?.methods},o=Xg({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:t,relay:i,expiryTimestamp:r,methods:e?.methods});return this.events.emit(Ob,s),this.core.expirer.set(n,r),await this.pairings.set(n,s),await this.core.relayer.subscribe(n,{transportType:e?.transportType,internal:e?.internal}),{topic:n,uri:o}},this.pair=async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[Kb]}});this.isValidPair(e,t);const{topic:n,symKey:r,relay:i,expiryTimestamp:s,methods:o}=Yg(e.uri);let a;if(t.props.properties.topic=n,t.addTrace(Gb),t.addTrace(Yb),this.pairings.keys.includes(n)){if(a=this.pairings.get(n),t.addTrace(ev),a.active)throw t.setError(ov),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);t.addTrace(tv)}const c=s||Zf(U.FIVE_MINUTES),l={topic:n,relay:i,expiry:c,active:!1,methods:o};this.core.expirer.set(n,c),await this.pairings.set(n,l),t.addTrace(Jb),e.activatePairing&&await this.activate({topic:n}),this.events.emit(Ob,l),t.addTrace(nv),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(r,n),t.addTrace(Qb);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(iv)}try{await this.core.relayer.subscribe(n,{relay:i})}catch(e){throw t.setError(av),e}return t.addTrace(Xb),l},this.activate=async({topic:e})=>{this.isInitialized();const t=Zf(U.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:n,resolve:r,reject:i}=Vf();this.events.once(Gf("pairing_ping",e),({error:e})=>{e?i(e):r()}),await n()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Cf("USER_DISCONNECTED")),await this.deletePairing(t))},this.formatUriFromPairing=e=>{this.isInitialized();const{topic:t,relay:n,expiry:r,methods:i}=e,s=this.core.crypto.keychain.get(t);return Xg({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:s,relay:n,expiryTimestamp:r,methods:i})},this.sendRequest=async(e,t,n)=>{const r=Wy(t,n),i=await this.core.crypto.encode(e,r),s=Tb[t].req;return this.core.history.set(e,r),this.core.relayer.publish(e,i,s),r.id},this.sendResult=async(e,t,n)=>{const r=Zy(e,n),i=await this.core.crypto.encode(t,r),s=(await this.core.history.get(t,e)).request.method,o=Tb[s].res;await this.core.relayer.publish(t,i,o),await this.core.history.resolve(r)},this.sendError=async(e,t,n)=>{const r=Ky(e,n),i=await this.core.crypto.encode(t,r),s=(await this.core.history.get(t,e)).request.method,o=Tb[s]?Tb[s].res:Tb.unregistered_method.res;await this.core.relayer.publish(t,i,o),await this.core.history.resolve(r)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Cf("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter(e=>Kf(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))},this.onRelayEventRequest=async e=>{const{topic:t,payload:n}=e;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,n);default:return await this.onUnknownRpcMethodRequest(t,n)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:n}=e,r=(await this.core.history.get(t,n.id)).request.method;return"wc_pairingPing"===r?this.onPairingPingResponse(t,n):this.onUnknownRpcMethodResponse(r)},this.onPairingPingRequest=async(e,t)=>{const{id:n}=t;try{this.isValidPing({topic:e}),await this.sendResult(n,e,!0),this.events.emit(Bb,{id:n,topic:e})}catch(t){await this.sendError(n,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:n}=t;setTimeout(()=>{sw(t)?this.events.emit(Gf("pairing_ping",n),{}):ow(t)&&this.events.emit(Gf("pairing_ping",n),{error:t.error})},500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:n}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(Rb,{id:n,topic:e})}catch(t){await this.sendError(n,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:n,method:r}=t;try{if(this.registeredMethods.includes(r))return;const t=Cf("WC_METHOD_UNSUPPORTED",r);await this.sendError(n,e,t),this.logger.error(t)}catch(t){await this.sendError(n,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Cf("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=(e,t)=>{if(!bm(e)){const{message:n}=If("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(sv),new Error(n)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(dm(e,!1))return!!t(e)||t(tg(e))}catch{}return!1}(e.uri)){const{message:n}=If("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(sv),new Error(n)}const n=Yg(e?.uri);if(!n?.relay?.protocol){const{message:e}=If("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(sv),new Error(e)}if(!n?.symKey){const{message:e}=If("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(sv),new Error(e)}if(n?.expiryTimestamp&&U.toMiliseconds(n?.expiryTimestamp)<Date.now()){t.setError(cv);const{message:e}=If("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}},this.isValidPing=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!dm(e,!1)){const{message:t}=If("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=If("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=If("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=wf(t,this.name),this.pairings=new qv(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yf(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(hb,async e=>{const{topic:t,message:n,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==Ab.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const e=await this.core.crypto.decode(t,n);rw(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):iw(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,n)}catch(e){this.logger.error(e)}})}registerExpirerEvents(){this.core.expirer.on(Hb,async e=>{const{topic:t}=Wf(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit($b,{topic:t}))})}},Zv=class extends my{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new I.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.records.set(e.id,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:n}),this.records.has(t.id))return;const r={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:n,expiry:Zf(U.THIRTY_DAYS)};this.records.set(r.id,r),this.persist(),this.events.emit(Mb,r)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response<"u"||(t.response=ow(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(Ub,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach(n=>{if(n.topic===e){if(typeof t<"u"&&n.id!==t)return;this.records.delete(n.id),this.events.emit(Lb,n)}}),this.persist()},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=wf(t,this.name)}get context(){return yf(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 n={topic:t.topic,request:Wy(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(n)}),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:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Db)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(Mb,e=>{const t=Mb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ub,e=>{const t=Ub;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Lb,e=>{const t=Lb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Mm,()=>{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(Lb,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Kv=class extends xy{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new I.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ib,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.expirations.set(e.target,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const n=this.formatTarget(e),r={target:n,expiry:t};this.expirations.set(n,r),this.checkExpiry(n,r),this.events.emit(jb,{target:n,expiration:r})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),n=this.getExpiration(t);this.expirations.delete(t),this.events.emit(zb,{target:t,expiration:n})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=wf(t,this.name)}get context(){return yf(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("string"==typeof e)return function(e){return qf("topic",e)}(e);if("number"==typeof e)return function(e){return qf("id",e)}(e);const{message:t}=If("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(Vb)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=If("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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:t}=If("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:n}=t;U.toMiliseconds(n)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Hb,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Mm,()=>this.checkExpirations()),this.events.on(jb,e=>{const t=jb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Hb,e=>{const t=Hb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(zb,e=>{const t=zb;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}},Gv=class extends Ay{constructor(e,t,n){super(e,t,n),this.core=e,this.logger=t,this.store=n,this.name="verify-api",this.verifyUrlV3=Wb,this.storagePrefix=ib,this.version=2,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds(this.publicKey?.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async e=>{if(!Rf()||this.isDevEnv)return;const t=window.location.origin,{id:n,decryptedId:r}=e,i=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${n}&decryptedId=${r}`;try{const e=ge(),t=this.startAbortTimer(5*U.ONE_SECOND),r=await new Promise((r,s)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),s("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=i,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=i=>{if(i.data&&"string"==typeof i.data)try{const s=JSON.parse(i.data);if("verify_attestation"===s.type){if(Lu(s.attestation).payload.id!==n)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),r(null===s.attestation?"":s.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})});return this.logger.debug(r,"jwt attestation"),r}catch(e){this.logger.warn(e)}return""},this.resolve=async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:n,encryptedId:r}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if(Lu(t).payload.id!==r)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!n)return;const i=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(n,i)},this.fetchAttestation=async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const n=this.startAbortTimer(5*U.ONE_SECOND),r=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(n),200===r.status?await r.json():void 0},this.getVerifyUrl=e=>{let t=e||qb;return Zb.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${qb}`),t=qb),t},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(U.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}},this.persistPublicKey=async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const n=await this.fetchAndPersistPublicKey();try{if(n)return this.validateAttestation(e,n)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))});const e=await this.fetchPromise;return this.fetchPromise=void 0,e},this.validateAttestation=(e,t)=>{const n=Wg(e,t.publicKey),r={hasExpired:U.toMiliseconds(n.exp)<Date.now(),payload:n};if(r.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:r.payload.origin,isScam:r.payload.isScam,isVerified:r.payload.isVerified}},this.logger=wf(t,this.name),this.abortController=new AbortController,this.isDevEnv=eg(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return yf(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}},Yv=class extends ky{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context="echo",this.registerDeviceToken=async e=>{const{clientId:t,token:n,notificationType:r,enableEncrypted:i=!1}=e,s=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:r,token:n,always_raw:i})})},this.logger=wf(t,this.context)}},Jv=class extends Iy{constructor(e,t,n=!0){super(e,t,n),this.core=e,this.logger=t,this.context="event-client",this.storagePrefix=ib,this.storageVersion=.1,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!eg())try{const e={eventId:Xf(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Lf(this.core.relayer.protocol,this.core.relayer.version,xb)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}},this.createEvent=e=>{const{event:t="ERROR",type:n="",properties:{topic:r,trace:i}}=e,s=Xf(),o=this.core.projectId||"",a={eventId:s,timestamp:Date.now(),props:{event:t,type:n,properties:{topic:r,trace:i}},bundleId:o,domain:this.getAppDomain(),...this.setMethods(s)};return this.telemetryEnabled&&(this.events.set(s,a),this.shouldPersist=!0),a},this.getEvent=e=>{const{eventId:t,topic:n}=e;if(t)return this.events.get(t);const r=Array.from(this.events.values()).find(e=>e.props.properties.topic===n);return r?{...r,...this.setMethods(r.eventId)}:void 0},this.deleteEvent=e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Mm,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})},this.setMethods=e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}),this.addTrace=(e,t)=>{const n=this.events.get(e);n&&(n.props.properties.trace.push(t),this.events.set(e,n),this.shouldPersist=!0)},this.setError=(e,t)=>{const n=this.events.get(e);n&&(n.props.type=t,n.timestamp=Date.now(),this.events.set(e,n),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach(e=>{this.events.set(e.eventId,{...e,...this.setMethods(e.eventId)})})}catch(e){this.logger.warn(e)}},this.submit=async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,n]of this.events)n.props.type&&e.push(n);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}},this.sendEvent=async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${xb}${t}`,{method:"POST",body:JSON.stringify(e)})},this.getAppDomain=()=>Uf().url,this.logger=wf(t,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}};const Qv=class e extends gy{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=rb,this.events=new I.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.dispatchEnvelope=({topic:e,message:t,sessionExists:n})=>{if(!e||!t)return;const r={topic:e,message:t,publishedAt:Date.now(),transportType:Ab.link_mode};this.relayer.onLinkMessageEvent(r,{sessionExists:n})};const t=this.getGlobalCore(e?.customStoragePrefix);if(t)try{return this.customStoragePrefix=t.customStoragePrefix,this.logger=t.logger,this.heartbeat=t.heartbeat,this.crypto=t.crypto,this.history=t.history,this.expirer=t.expirer,this.storage=t.storage,this.relayer=t.relayer,this.pairing=t.pairing,this.verify=t.verify,this.echoClient=t.echoClient,this.linkModeSupportedApps=t.linkModeSupportedApps,this.eventClient=t.eventClient,this.initialized=t.initialized,this.logChunkController=t.logChunkController,t}catch(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||db,this.customStoragePrefix=e?.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=mf({level:"string"==typeof e?.logger&&e.logger?e.logger:sb,name:rb}),{logger:r,chunkLoggerController:i}=bf({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=i,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=wf(r,this.name),this.heartbeat=new Um,this.crypto=new Dv(this,this.logger,e?.keychain),this.history=new Zv(this,this.logger),this.expirer=new Kv(this,this.logger),this.storage=e?.storage?e.storage:new fy({...ob,...e?.storageOptions}),this.relayer=new Fv({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Wv(this,this.logger),this.verify=new Gv(this,this.logger,this.storage),this.echoClient=new Yv(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Jv(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new e(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem("WALLETCONNECT_CLIENT_ID",r),n}get context(){return yf(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Cb,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(Cb)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,n=`${t}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e.opts?.customStoragePrefix||""}`;globalThis[t]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&"true"===process.env.DISABLE_GLOBAL_CORE}catch{return!0}}},Xv="client",eE=`wc@2:${Xv}:`,tE=Xv,nE="error",rE="WALLETCONNECT_DEEPLINK_CHOICE",iE="Proposal expired",sE=U.SEVEN_DAYS,oE={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:3*U.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:3*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}}},aE={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},cE="IDLE",lE="ACTIVE",dE={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},hE=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],uE="wc@1.5:auth:",pE=`${uE}:PUB_KEY`;let fE=class extends Sy{constructor(t){super(t),this.name="engine",this.events=new C,this.initialized=!1,this.requestQueue={state:cE,queue:[]},this.sessionRequestQueue={state:cE,queue:[]},this.emittedSessionRequests=new ng({limit:500}),this.requestQueueDelay=U.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(oE)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t={...e,requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}};await this.isValidConnect(t),t.optionalNamespaces=function(e,t){const n=sm(e),r=sm(t),i={},s=Object.keys(n).concat(Object.keys(r));for(const e of s)i[e]={chains:Yf(n[e]?.chains,r[e]?.chains),methods:Yf(n[e]?.methods,r[e]?.methods),events:Yf(n[e]?.events,r[e]?.events)};return i}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:s,scopedProperties:o,relays:a,authentication:c,walletPay:l}=t,d=c?.[0]?.ttl||oE.wc_sessionPropose.req.ttl||U.FIVE_MINUTES;this.validateRequestExpiry(d);let h,u=n,p=!1;try{if(u){const e=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),p=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),e}if(!u||!p){const{topic:e,uri:t}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=e,h=t}if(!u){const{message:e}=If("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(e)}const f=await this.client.core.crypto.generateKeyPair(),g=Zf(d),m={requiredNamespaces:r,optionalNamespaces:i,relays:a??[{protocol:"irn"}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u,...s&&{sessionProperties:s},...o&&{scopedProperties:o},id:Fy(),...(c||l)&&{requests:{authentication:c?.map(e=>{const{domain:t,chains:n,nonce:r,uri:i,exp:s,nbf:o,type:a,statement:c,requestId:l,resources:d,signatureTypes:h}=e;return{domain:t,chains:n,nonce:r,type:a??"caip122",aud:i,version:"1",iat:(new Date).toISOString(),exp:s,nbf:o,statement:c,requestId:l,resources:d,signatureTypes:h}}),walletPay:l}}},y=Gf("session_connect",m.id),{reject:w,resolve:b,done:v}=Vf(d,iE),E=({id:e})=>{if(e===m.id){this.client.events.off("proposal_expire",E);const e=this.pendingSessions.get(m.id);if(e){const{sessionTopic:t,publicKey:n}=e;Promise.all([this.client.core.relayer.unsubscribe(t),this.client.core.crypto.keychain.has(t)?this.client.core.crypto.deleteSymKey(t):Promise.resolve(),this.client.core.crypto.keychain.has(n)?this.client.core.crypto.deleteKeyPair(n):Promise.resolve()]).catch(e=>this.client.logger.warn(e))}this.pendingSessions.delete(m.id),this.events.emit(y,{error:{message:iE,code:0}})}};return this.client.events.on("proposal_expire",E),this.events.once(y,({error:e,session:t})=>{this.client.events.off("proposal_expire",E),e?w(e):t&&b(t)}),await this.setProposal(m.id,m),await this.sendProposeSession({proposal:m,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:m.id}}}).catch(e=>{throw this.deleteProposal(m.id),e}),{uri:h,approval:v}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}},this.approve=async e=>{const t=this.client.core.eventClient.createEvent({properties:{topic:e?.id?.toString(),trace:[dv]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw t.setError(bv),e}try{await this.isValidProposalId(e?.id)}catch(n){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),t.setError(Av),n}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),t.setError(xv),e}const{id:n,relayProtocol:r,namespaces:i,sessionProperties:s,scopedProperties:o,sessionConfig:a,proposalRequestsResponses:c}=e,l=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:t.eventId});const{pairingTopic:d,proposer:h,requiredNamespaces:u,optionalNamespaces:p}=l;let f=this.client.core.eventClient?.getEvent({topic:d});f||(f=this.client.core.eventClient?.createEvent({type:dv,properties:{topic:d,trace:[dv,hv]}}));const g=await this.client.core.crypto.generateKeyPair(),m=h.publicKey,y=await this.client.core.crypto.generateSharedKey(g,m),w={relay:{protocol:r??"irn"},namespaces:i,controller:{publicKey:g,metadata:this.client.metadata},expiry:Zf(sE),...s&&{sessionProperties:s},...o&&{scopedProperties:o},...a&&{sessionConfig:a},proposalRequestsResponses:c},b=Ab.relay;f.addTrace(uv);try{await this.client.core.relayer.subscribe(y,{transportType:b,internal:{skipSubscribe:!0}})}catch(e){throw f.setError(Ev),e}f.addTrace(pv);const v={...w,topic:y,requiredNamespaces:u,optionalNamespaces:p,pairingTopic:d,acknowledged:!1,self:w.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:g,transportType:Ab.relay,authentication:c?.authentication,walletPayResult:c?.walletPay};await this.client.session.set(y,v),f.addTrace(gv);try{await this.sendApproveSession({sessionTopic:y,proposal:l,pairingProposalResponse:{relay:{protocol:r??"irn"},responderPublicKey:g},sessionSettleRequest:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:n,...this.getTVFApproveParams(v)}}}),f.addTrace(fv)}catch(e){throw this.client.logger.error(e),this.client.session.delete(y,Cf("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(y),e}return this.client.core.eventClient.deleteEvent({eventId:f.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:h.metadata}),await this.deleteProposal(n),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(y,Zf(sE)),{topic:y,acknowledged:()=>Promise.resolve(this.client.session.get(y))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:n}=e;let r;try{r=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}r&&await this.sendError({id:t,topic:r,error:n,rpcOpts:oE.wc_sessionPropose.reject}),await this.deleteProposal(t)},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:n}=e,{done:r,resolve:i,reject:s}=Vf(U.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),o=Fy(),a=qy().toString(),c=this.client.session.get(t).namespaces;return this.events.once(Gf("session_update",o),({error:e})=>{e?s(e):i()}),await this.client.session.update(t,{namespaces:n}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:a}).catch(e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:c}),s(e)}),{acknowledged:r}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,n=Fy(),{done:r,resolve:i,reject:s}=Vf(U.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Gf("session_extend",n),({error:e})=>{e?s(e):i()}),await this.setExpiry(t,Zf(sE)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(e=>{s(e)}),{acknowledged:r}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:n,topic:r,expiry:i=oE.wc_sessionRequest.req.ttl}=e,s=this.client.session.get(r);s?.transportType===Ab.relay&&await this.confirmOnlineStateOrThrow();const o=Fy(),a=qy().toString(),{done:c,resolve:l,reject:d}=Vf(i,"Request expired. Please try again.");this.events.once(Gf("session_request",o),({error:e,result:t})=>{e?d(e):l(t)});const h="wc_sessionRequest",u=this.getAppLinkIfEnabled(s.peer.metadata,s.transportType);if(u)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:r,method:h,params:{request:{...n,expiryTimestamp:Zf(i)},chainId:t},expiry:i,throwOnFailedPublish:!0,appLink:u}).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:t,id:o}),await c();const p={request:{...n,expiryTimestamp:Zf(i)},chainId:t};return await Promise.all([new Promise(async e=>{await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:r,method:h,params:p,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(o,p)}).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:t,id:o}),e()}),new Promise(async e=>{if(!s.sessionConfig?.disableDeepLink){const e=await async function(e,t){let n="";try{if(Rf()&&(n=localStorage.getItem(t),n))return n;n=await e.getItem(t)}catch(e){console.error(e)}return n}(this.client.core.storage,rE);await Jf({id:o,topic:r,wcDeepLink:e})}e()}),c()]).then(e=>e[2])},this.respond=async e=>{this.isInitialized();const t=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||e?.response?.id?.toString(),trace:[mv]}});try{await this.isValidRespond(e)}catch(e){throw t.addTrace(e?.message),t.setError(kv),e}t.addTrace(yv);const{topic:n,response:r}=e,{id:i}=r,s=this.client.session.get(n);s.transportType===Ab.relay&&await this.confirmOnlineStateOrThrow();const o=this.getAppLinkIfEnabled(s.peer.metadata,s.transportType);try{t.addTrace(wv),sw(r)?await this.sendResult({id:i,topic:n,result:r.result,throwOnFailedPublish:!0,appLink:o}):ow(r)&&await this.sendError({id:i,topic:n,error:r.error,appLink:o}),this.cleanupAfterResponse(e)}catch(e){throw t.addTrace(e?.message),t.setError(Iv),e}},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=Fy(),n=qy().toString(),{done:r,resolve:i,reject:s}=Vf(U.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Gf("session_ping",e),({error:e})=>{e?s(e):i()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:n}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&(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:t}))},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:n,chainId:r}=e,i=qy().toString(),s=Fy();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:n,chainId:r},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:s})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Cf("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=If("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>function(e,t){const{requiredNamespaces:n}=t,r=Object.keys(e.namespaces),i=Object.keys(n);let s=!0;return!!jf(i,r)&&(r.forEach(t=>{const{accounts:r,methods:i,events:o}=e.namespaces[t],a=tm(r),c=n[t];jf(xf(t,c),a)&&jf(c.methods,i)&&jf(c.events,o)||(s=!1)}),s)}(t,e))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{this.isInitialized(),this.isValidAuthenticate(e);const n=t&&this.client.core.linkModeSupportedApps.includes(t)&&this.client.metadata.redirect?.linkMode,r=n?Ab.link_mode:Ab.relay;r===Ab.relay&&await this.confirmOnlineStateOrThrow();const{chains:i,statement:s="",uri:o,domain:a,nonce:c,type:l,exp:d,nbf:h,methods:u=[],expiry:p}=e,f=[...e.resources||[]],{topic:g,uri:m}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:g,uri:m}}),this.client.auth.authKeys.keys.includes(pE)){const{responseTopic:e,publicKey:t}=this.client.auth.authKeys.get(pE);e&&(await this.client.core.relayer.unsubscribe(e).catch(e=>this.client.logger.warn(e)),await this.client.auth.pairingTopics.delete(e,{message:"replaced",code:0}).catch(e=>this.client.logger.warn(e))),t&&this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteKeyPair(t)}const y=await this.client.core.crypto.generateKeyPair(),w=Bg(y);if(await Promise.all([this.client.auth.authKeys.set(pE,{responseTopic:w,publicKey:y}),this.client.auth.pairingTopics.set(w,{topic:w,pairingTopic:g})]),await this.client.core.relayer.subscribe(w,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${g}`),u.length>0){const{namespace:e}=vf(i[0]);let t=kg(e,"request",u);Pg(f)&&(t=Ig(t,f.pop())),f.push(t)}const b=p&&p>oE.wc_sessionAuthenticate.req.ttl?p:oE.wc_sessionAuthenticate.req.ttl,v={authPayload:{type:l??"caip122",chains:i,statement:s,aud:o,domain:a,version:"1",nonce:c,iat:(new Date).toISOString(),exp:d,nbf:h,resources:f},requester:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:Zf(b)},E={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:i,methods:[...new Set(["personal_sign",...u])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:g,proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:Zf(oE.wc_sessionPropose.req.ttl),id:Fy()},{done:x,resolve:A,reject:k}=Vf(b,"Request expired"),I=Fy(),C=Gf("session_connect",E.id),S=Gf("session_request",I),P=async({error:e,session:t})=>{this.events.off(S,N),e?k(e):t&&A({session:t})},N=async e=>{if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),e.error){const t=Cf("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(C,P),k(e.error.message))}await this.deleteProposal(E.id),this.events.off(C,P);const{cacaos:n,responder:i}=e.result,s=[],o=[];for(const e of n){await wg({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),k(Cf("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,n=Pg(t.resources),r=[mg(t.iss)],i=yg(t.iss);if(n){const e=Cg(n),t=Sg(n);s.push(...e),r.push(...t)}for(const e of r)o.push(`${e}:${i}`)}const a=await this.client.core.crypto.generateSharedKey(y,i.publicKey);let c;s.length>0&&(c={topic:a,acknowledged:!0,self:{publicKey:y,metadata:this.client.metadata},peer:i,controller:i.publicKey,expiry:Zf(sE),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:g,namespaces:om([...new Set(s)],[...new Set(o)]),transportType:r},await this.client.core.relayer.subscribe(a,{transportType:r}),await this.client.session.set(a,c),g&&await this.client.core.pairing.updateMetadata({topic:g,metadata:i.metadata}),c=this.client.session.get(a)),this.client.metadata.redirect?.linkMode&&i.metadata.redirect?.linkMode&&i.metadata.redirect?.universal&&t&&(this.client.core.addLinkModeSupportedApp(i.metadata.redirect.universal),this.client.session.update(a,{transportType:Ab.link_mode})),A({auths:n,session:c})};let _;this.events.once(C,P),this.events.once(S,N);try{if(n){const e=Wy("wc_sessionAuthenticate",v,I);this.client.core.history.set(g,e);const n=await this.client.core.crypto.encode("",e,{type:2,encoding:Og});_=em(t,g,n)}else await Promise.all([this.sendRequest({topic:g,method:"wc_sessionAuthenticate",params:v,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:g,method:"wc_sessionPropose",params:E,expiry:oE.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(e){throw this.events.off(C,P),this.events.off(S,N),e}return await this.setProposal(E.id,E),await this.setAuthRequest(I,{request:{...v,verifyContext:{}},pairingTopic:g,transportType:r}),{uri:_??m,response:x}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:n}=e,r=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Cv]}});try{this.isInitialized()}catch(e){throw r.setError($v),e}const i=this.getPendingAuthRequest(t);if(!i)throw r.setError(Uv),new Error(`Could not find pending auth request with id ${t}`);const s=i.transportType||Ab.relay;s===Ab.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Bg(o),l={type:1,receiverPublicKey:o,senderPublicKey:a},d=[],h=[];for(const e of n){if(!await wg({cacao:e,projectId:this.client.core.projectId})){r.setError(Rv);const e=Cf("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:l}),new Error(e.message)}r.addTrace(Pv);const{p:n}=e,i=Pg(n.resources),s=[mg(n.iss)],o=yg(n.iss);if(i){const e=Cg(i),t=Sg(i);d.push(...e),s.push(...t)}for(const e of s)h.push(`${e}:${o}`)}const u=await this.client.core.crypto.generateSharedKey(a,o);let p;if(r.addTrace(Sv),d?.length>0){p={topic:u,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:i.requester.metadata},controller:o,expiry:Zf(sE),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:om([...new Set(d)],[...new Set(h)]),transportType:s},r.addTrace(_v);try{await this.client.core.relayer.subscribe(u,{transportType:s})}catch(e){throw r.setError(Bv),e}r.addTrace(Tv),await this.client.session.set(u,p),r.addTrace(Nv),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}r.addTrace(Ov);try{await this.sendResult({topic:c,id:t,result:{cacaos:n,responder:{publicKey:a,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,s)})}catch(e){throw r.setError(Mv),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:r.eventId}),{session:p}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:n}=e,r=this.getPendingAuthRequest(t);if(!r)throw new Error(`Could not find pending auth request with id ${t}`);r.transportType===Ab.relay&&await this.confirmOnlineStateOrThrow();const i=r.requester.publicKey,s=await this.client.core.crypto.generateKeyPair(),o=Bg(i),a={type:1,receiverPublicKey:i,senderPublicKey:s};await this.sendError({id:t,topic:o,error:n,encodeOpts:a,rpcOpts:oE.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(r.requester.metadata,r.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.deleteProposal(t)},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:n}=e;return bg(t,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(n=>n.peerMetadata?.url&&n.peerMetadata?.url===e.peer.metadata.url&&n.topic&&n.topic!==t.topic);if(0===n.length)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(e=>this.client.core.pairing.disconnect({topic:e.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}},this.deleteSession=async e=>{const{topic:t,expirerHasDeleted:n=!1,emitEvent:r=!0,id:i=0}=e,{self:s}=this.client.session.get(t);await this.client.core.relayer.unsubscribe(t),await this.client.session.delete(t,Cf("USER_DISCONNECTED")),this.addToRecentlyDeleted(t,"session"),this.client.core.crypto.keychain.has(s.publicKey)&&await this.client.core.crypto.deleteKeyPair(s.publicKey),this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteSymKey(t),n||this.client.core.expirer.del(t),this.client.core.storage.removeItem(rE).catch(e=>this.client.logger.warn(e)),t===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=cE),await Promise.all(this.getPendingSessionRequests().filter(e=>e.topic===t).map(e=>this.deletePendingSessionRequest(e.id,Cf("USER_DISCONNECTED")))),r&&this.client.events.emit("session_delete",{id:i,topic:t})},this.deleteProposal=async(e,t)=>{if(t)try{const t=this.client.proposal.get(e);this.client.core.eventClient.getEvent({topic:t.pairingTopic})?.setError(vv)}catch{}await Promise.all([this.client.proposal.delete(e,Cf("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")},this.deletePendingSessionRequest=async(e,t,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),n?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(t=>t.id!==e),n&&(this.sessionRequestQueue.state=cE,this.client.events.emit("session_request_expire",{id:e}))},this.deletePendingAuthRequest=async(e,t,n=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),n?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,Zf(oE.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:n,pairingTopic:r,transportType:i=Ab.relay}=t;this.client.core.expirer.set(e,n.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:e,pairingTopic:r,verifyContext:n.verifyContext,transportType:i})},this.setPendingSessionRequest=async e=>{const{id:t,topic:n,params:r,verifyContext:i}=e,s=r.request.expiryTimestamp||Zf(oE.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,s),await this.client.pendingRequest.set(t,{id:t,topic:n,params:r,verifyContext:i})},this.sendRequest=async t=>{const{topic:n,method:r,params:i,expiry:s,relayRpcId:o,clientRpcId:a,throwOnFailedPublish:c,appLink:l,tvf:d,publishOpts:h={}}=t,u=Wy(r,i,a);let p;const f=!!l;try{const e=f?Og:Tg;p=await this.client.core.crypto.encode(n,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),e}let g;if(hE.includes(r)){const e=Mg(JSON.stringify(u)),t=Mg(p);g=await this.client.core.verify.register({id:t,decryptedId:e})}const m={...oE[r].req,...h};if(m.attestation=g,s&&(m.ttl=s),o&&(m.id=o),this.client.core.history.set(n,u),f){const t=em(l,n,p);await e.Linking.openURL(t,this.client.name)}else m.tvf={...d,correlationId:u.id},c?(m.internal={...m.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(n,p,m)):this.client.core.relayer.publish(n,p,m).catch(e=>this.client.logger.error(e));return u.id},this.sendProposeSession=async e=>{const{proposal:t,publishOpts:n}=e,r=Wy("wc_sessionPropose",t,t.id);this.client.core.history.set(t.pairingTopic,r);const i=await this.client.core.crypto.encode(t.pairingTopic,r,{encoding:Tg}),s=Mg(JSON.stringify(r)),o=Mg(i),a=await this.client.core.verify.register({id:o,decryptedId:s});await this.client.core.relayer.publishCustom({payload:{pairingTopic:t.pairingTopic,sessionProposal:i},opts:{...n,publishMethod:"wc_proposeSession",attestation:a}})},this.sendApproveSession=async e=>{const{sessionTopic:t,pairingProposalResponse:n,proposal:r,sessionSettleRequest:i,publishOpts:s}=e,o=Zy(r.id,n),a=await this.client.core.crypto.encode(r.pairingTopic,o,{encoding:Tg}),c=Wy("wc_sessionSettle",i,s?.id),l=await this.client.core.crypto.encode(t,c,{encoding:Tg});this.client.core.history.set(t,c),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:r.pairingTopic,sessionProposalResponse:a,sessionSettlementRequest:l},opts:{...s,publishMethod:"wc_approveSession"}})},this.sendResult=async t=>{const{id:n,topic:r,result:i,throwOnFailedPublish:s,encodeOpts:o,appLink:a}=t,c=Zy(n,i);let l;const d=a&&typeof e?.Linking<"u";try{const e=d?Og:Tg;l=await this.client.core.crypto.encode(r,c,{...o||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),e}let h,u;try{h=await this.client.core.history.get(r,n);const e=h.request;try{u=this.getTVFParams(n,e.params,i)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),e}if(d){const t=em(a,r,l);await e.Linking.openURL(t,this.client.name)}else{const e=h.request.method,t=oE[e].res;t.tvf={...u,correlationId:n},s?(t.internal={...t.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(r,l,t)):this.client.core.relayer.publish(r,l,t).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(c)},this.sendError=async t=>{const{id:n,topic:r,error:i,encodeOpts:s,rpcOpts:o,appLink:a}=t,c=Ky(n,i);let l;const d=a&&typeof e?.Linking<"u";try{const e=d?Og:Tg;l=await this.client.core.crypto.encode(r,c,{...s||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),e}let h;try{h=await this.client.core.history.get(r,n)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),e}if(d){const t=em(a,r,l);await e.Linking.openURL(t,this.client.name)}else{const e=h.request.method,t=o||oE[e].res;this.client.core.relayer.publish(r,l,t)}await this.client.core.history.resolve(c)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach(t=>{let n=!1;Kf(t.expiry)&&(n=!0),this.client.core.crypto.keychain.has(t.topic)||(n=!0),n&&e.push(t.topic)}),this.client.proposal.getAll().forEach(e=>{Kf(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])},this.onProviderMessageEvent=async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==lE){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=lE;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=cE}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=async e=>{const{topic:t,payload:n,attestation:r,transportType:i,encryptedId:s}=e,o=n.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:n,attestation:r,encryptedId:s});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,n);case"wc_sessionPing":return await this.onSessionPingRequest(t,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:n,attestation:r,encryptedId:s,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(t,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:n,attestation:r,encryptedId:s,transportType:i});default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:n,transportType:r}=e,i=(await this.client.core.history.get(t,n.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(t,n,r);case"wc_sessionSettle":return this.onSessionSettleResponse(t,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,n);case"wc_sessionExtend":return this.onSessionExtendResponse(t,n);case"wc_sessionPing":return this.onSessionPingResponse(t,n);case"wc_sessionRequest":return this.onSessionRequestResponse(t,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,n);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:n}=If("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:n}=e,r=this.expectedPairingMethodMap.get(t);return!(!r||r.includes(n))&&!!(r.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:n,attestation:r,encryptedId:i}=e,{params:s,id:o}=n;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(lv)),this.isValidConnect({...n.params});const a={id:o,pairingTopic:t,expiryTimestamp:s.expiryTimestamp||Zf(oE.wc_sessionPropose.req.ttl),attestation:r,encryptedId:i,...s};await this.setProposal(o,a);const c=await this.getVerifyContext({attestationId:r,hash:Mg(JSON.stringify(n)),encryptedId:i,metadata:a.proposer.metadata});e?.addTrace(rv),this.client.events.emit("session_proposal",{id:o,params:a,verifyContext:c})}catch(e){await this.sendError({id:o,topic:t,error:e,rpcOpts:oE.wc_sessionPropose.autoReject}),this.client.logger.error(e)}},this.onSessionProposeResponse=async(e,t,n)=>{const{id:r}=t;if(sw(t)){const{result:i}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});const s=this.client.proposal.get(r);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:s});const o=s.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(r,{sessionTopic:c,pairingTopic:e,proposalId:r,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if(ow(t)){await this.deleteProposal(r);const e=Gf("session_connect",r);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:n,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:n,controller:i,expiry:s,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:l,proposalRequestsResponses:d}=t.params,h=[...this.pendingSessions.values()].find(t=>t.sessionTopic===e);if(!h)return this.client.logger.error(`Pending session not found for topic ${e}`);const u=this.client.proposal.get(h.proposalId),p={topic:e,relay:n,expiry:s,namespaces:o,acknowledged:!0,pairingTopic:h.pairingTopic,requiredNamespaces:u.requiredNamespaces,optionalNamespaces:u.optionalNamespaces,controller:i.publicKey,self:{publicKey:h.publicKey,metadata:this.client.metadata},peer:{publicKey:i.publicKey,metadata:i.metadata},...a&&{sessionProperties:a},...c&&{scopedProperties:c},...l&&{sessionConfig:l},transportType:Ab.relay,authentication:d?.authentication,walletPayResult:d?.walletPay};await this.client.session.set(p.topic,p),await this.setExpiry(p.topic,p.expiry),await this.client.core.pairing.updateMetadata({topic:h.pairingTopic,metadata:p.peer.metadata}),this.pendingSessions.delete(h.proposalId),this.deleteProposal(h.proposalId,!1),this.cleanupDuplicatePairings(p),await this.sendResult({id:t.id,topic:e,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:p}),this.events.emit(Gf("session_connect",h.proposalId),{session:p})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionSettleResponse=async(e,t)=>{const{id:n}=t;sw(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Gf("session_approve",n),{})):ow(t)&&(await this.deleteSession({topic:e,emitEvent:!1}),this.events.emit(Gf("session_approve",n),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:n,id:r}=t;try{const t=`${e}_session_update`,i=Pm.get(t);if(i&&this.isRequestOutOfSync(i,r))return this.client.logger.warn(`Discarding out of sync request - ${r}`),void this.sendError({id:r,topic:e,error:Cf("INVALID_UPDATE_REQUEST")});this.isValidUpdate({topic:e,...n});try{Pm.set(t,r),await this.client.session.update(e,{namespaces:n.namespaces}),await this.sendResult({id:r,topic:e,result:!0})}catch(e){throw Pm.delete(t),e}this.client.events.emit("session_update",{id:r,topic:e,params:n})}catch(t){await this.sendError({id:r,topic:e,error:t}),this.client.logger.error(t)}},this.isRequestOutOfSync=(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3),this.onSessionUpdateResponse=(e,t)=>{const{id:n}=t,r=Gf("session_update",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);sw(t)?this.events.emit(Gf("session_update",n),{}):ow(t)&&this.events.emit(Gf("session_update",n),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:n}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Zf(sE)),await this.sendResult({id:n,topic:e,result:!0}),this.client.events.emit("session_extend",{id:n,topic:e})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionExtendResponse=(e,t)=>{const{id:n}=t,r=Gf("session_extend",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);sw(t)?this.events.emit(Gf("session_extend",n),{}):ow(t)&&this.events.emit(Gf("session_extend",n),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:n}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:n,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:e})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionPingResponse=(e,t)=>{const{id:n}=t,r=Gf("session_ping",n);setTimeout(()=>{if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners 2176`);sw(t)?this.events.emit(Gf("session_ping",n),{}):ow(t)&&this.events.emit(Gf("session_ping",n),{error:t.error})},500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:n}=t;try{await this.isValidDisconnect({topic:e,reason:t.params}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Cf("USER_DISCONNECTED")}),await this.deleteSession({topic:e,id:n})}catch(e){this.client.logger.error(e)}},this.onSessionRequest=async e=>{const{topic:t,payload:n,attestation:r,encryptedId:i,transportType:s}=e,{id:o,params:a}=n;try{await this.isValidRequest({topic:t,...a});const e=this.client.session.get(t),n={id:o,topic:t,params:a,verifyContext:await this.getVerifyContext({attestationId:r,hash:Mg(JSON.stringify(Wy("wc_sessionRequest",a,o))),encryptedId:i,metadata:e.peer.metadata,transportType:s})};await this.setPendingSessionRequest(n),s===Ab.link_mode&&e.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(n):(this.addSessionRequestToSessionRequestQueue(n),this.processSessionRequestQueue())}catch(e){await this.sendError({id:o,topic:t,error:e}),this.client.logger.error(e)}},this.onSessionRequestResponse=(e,t)=>{const{id:n}=t,r=Gf("session_request",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);sw(t)?this.events.emit(Gf("session_request",n),{result:t.result}):ow(t)&&this.events.emit(Gf("session_request",n),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:n,params:r}=t;try{const t=`${e}_session_event_${r.event.name}`,i=Pm.get(t);if(i&&this.isRequestOutOfSync(i,n))return void this.client.logger.info(`Discarding out of sync request - ${n}`);this.isValidEmit({topic:e,...r}),this.client.events.emit("session_event",{id:n,topic:e,params:r}),Pm.set(t,n)}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:n}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),sw(t)?this.events.emit(Gf("session_request",n),{result:t.result}):ow(t)&&this.events.emit(Gf("session_request",n),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{const{topic:t,payload:n,attestation:r,encryptedId:i,transportType:s}=e;try{const{requester:e,authPayload:o,expiryTimestamp:a}=n.params,c=await this.getVerifyContext({attestationId:r,hash:Mg(JSON.stringify(n)),encryptedId:i,metadata:e.metadata,transportType:s}),l={requester:e,pairingTopic:t,id:n.id,authPayload:o,verifyContext:c,expiryTimestamp:a};await this.setAuthRequest(n.id,{request:l,pairingTopic:t,transportType:s}),s===Ab.link_mode&&e.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:t,params:n.params,id:n.id,verifyContext:c})}catch(e){this.client.logger.error(e);const r=n.params.requester.publicKey,i=await this.client.core.crypto.generateKeyPair(),o=this.getAppLinkIfEnabled(n.params.requester.metadata,s),a={type:1,receiverPublicKey:r,senderPublicKey:i};await this.sendError({id:n.id,topic:t,error:e,encodeOpts:a,rpcOpts:oE.wc_sessionAuthenticate.autoReject,appLink:o})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=cE,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(t=>t.topic===e&&"wc_sessionRequest"===t.request.method).forEach(e=>{this.events.emit(Gf("session_request",e.request.id),{error:t})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===lE)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")},this.emitSessionRequest=e=>{this.emittedSessionRequests.has(e.id)?this.client.logger.warn({id:e.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${e.id}`):(this.sessionRequestQueue.state=lE,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const e=this.client.core.relayer.subscriber.topics;if(0===e.length)return;const t=new Set(this.client.session.keys),n=new Set(this.client.core.pairing.pairings.keys),r=new Set([...this.pendingSessions.values()].map(e=>e.sessionTopic));let i;if(this.client.auth.authKeys.keys.includes(pE)){const{responseTopic:e}=this.client.auth.authKeys.get(pE);i=e}for(const s of e)if(!t.has(s)&&!n.has(s)&&!r.has(s)&&s!==i){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${s}`);try{await this.client.core.relayer.subscriber.unsubscribe(s)}catch(e){this.client.logger.warn(e,`Failed to clean up orphaned subscription: ${s}`)}}},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(t=>t.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:Wy("wc_sessionPropose",{...t,requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties},t.id),attestation:t.attestation,encryptedId:t.encryptedId})},this.isValidConnect=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:n,optionalNamespaces:r,sessionProperties:i,scopedProperties:s,relays:o}=e;if(lm(t)||await this.isValidPairingTopic(t),!function(e){let t=!1;return e?e&&am(e)&&e.length&&e.forEach(e=>{t=wm(e)}):t=!0,t}(o)){const{message:e}=If("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(n&&!lm(n)&&0!==cm(n)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(n,"requiredNamespaces")}if(r&&!lm(r)&&0!==cm(r)&&this.validateNamespaces(r,"optionalNamespaces"),i&&!lm(i)&&this.validateSessionProps(i,"sessionProperties"),s&&!lm(s)){this.validateSessionProps(s,"scopedProperties");const e=Object.keys(n||{}).concat(Object.keys(r||{}));if(!Object.keys(s).every(t=>e.includes(t.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(s)}, required/optional namespaces: ${JSON.stringify(e)}`)}},this.validateNamespaces=(e,t)=>{const n=function(e,t,n){let r=null;if(e&&cm(e)){const i=mm(e,t);i&&(r=i);const s=fm(e,t,n);s&&(r=s)}else r=If("MISSING_OR_INVALID",`${t}, ${n} should be an object with data`);return r}(e,"connect()",t);if(n)throw new Error(n.message)},this.isValidApprove=async e=>{if(!bm(e))throw new Error(If("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:n,relayProtocol:r,sessionProperties:i,scopedProperties:s}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),a=ym(n,"approve()");if(a)throw new Error(a.message);const c=Am(o.requiredNamespaces,n,"approve()");if(c)throw new Error(c.message);if(!dm(r,!0)){const{message:e}=If("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(e)}if(i&&!lm(i)&&this.validateSessionProps(i,"sessionProperties"),s&&!lm(s)){this.validateSessionProps(s,"scopedProperties");const e=new Set(Object.keys(n));if(!Object.keys(s).every(t=>e.has(t.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(s)}, approved namespaces: ${Array.from(e).join(", ")}`)}},this.isValidReject=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:n}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&hm(e.code,!1)&&e.message&&dm(e.message,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:n,namespaces:r,expiry:i}=e;if(!wm(t)){const{message:e}=If("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const s=function(e,t){let n=null;return dm(e?.publicKey,!1)||(n=If("MISSING_OR_INVALID",`${t} controller public key should be a string`)),n}(n,"onSessionSettleRequest()");if(s)throw new Error(s.message);const o=ym(r,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Kf(i)){const{message:e}=If("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:n}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const r=this.client.session.get(t),i=ym(n,"update()");if(i)throw new Error(i.message);const s=Am(r.requiredNamespaces,n,"update()");if(s)throw new Error(s.message)},this.isValidExtend=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:n,chainId:r,expiry:i}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:s}=this.client.session.get(t);if(!vm(s,r)){const{message:e}=If("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(e)}if(!function(e){return!(lm(e)||!dm(e.method,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(e)}if(!Em(s,r,n.method)){const{message:e}=If("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(e)}this.validateRequestExpiry(i)},this.isValidRespond=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:n}=e;try{await this.isValidSessionTopic(t)}catch(t){throw e?.response?.id&&this.cleanupAfterResponse(e),t}if(!function(e){return!(lm(e)||lm(e.result)&&lm(e.error)||!hm(e.id,!1)||!dm(e.jsonrpc,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(e)}const r=this.client.pendingRequest.get(n.id);if(r.topic!==t){const{message:e}=If("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${r.topic}, received topic: ${t}`);throw new Error(e)}},this.isValidPing=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:n,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:i}=this.client.session.get(t);if(!vm(i,r)){const{message:e}=If("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(e)}if(!function(e){return!(lm(e)||!dm(e.name,!1))}(n)){const{message:e}=If("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(e)}if(!xm(i,r,n.name)){const{message:e}=If("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!bm(e)){const{message:t}=If("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:n,domain:r,nonce:i}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!dm(n,!1))throw new Error("uri is required parameter");if(!dm(r,!1))throw new Error("domain is required parameter");if(!dm(i,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(e=>vf(e).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:s}=vf(t[0]);if("eip155"!==s)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async e=>{const{attestationId:t,hash:n,encryptedId:r,metadata:i,transportType:s}=e,o={verified:{verifyUrl:i.verifyUrl||qb,validation:"UNKNOWN",origin:i.url||""}};try{if(s===Ab.link_mode){const e=this.getAppLinkIfEnabled(i,s);return o.verified.validation=e&&new URL(e).origin===new URL(i.url).origin?"VALID":"INVALID",o}const e=await this.client.core.verify.resolve({attestationId:t,hash:n,encryptedId:r,verifyUrl:i.verifyUrl});e&&(o.verified.origin=e.origin,o.verified.isScam=e.isScam,o.verified.validation=e.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(e,t)=>{Object.values(e).forEach((n,r)=>{if(null==n){const{message:i}=If("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${n} for key ${Object.keys(e)[r]}`);throw new Error(i)}})},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const n of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(n)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:n}=If("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(n)}},this.isLinkModeEnabled=(t,n)=>!(!t||n!==Ab.link_mode)&&(!0===this.client.metadata?.redirect?.linkMode&&void 0!==this.client.metadata?.redirect?.universal&&""!==this.client.metadata?.redirect?.universal&&void 0!==t?.redirect?.universal&&""!==t?.redirect?.universal&&!0===t?.redirect?.linkMode&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof e?.Linking<"u"),this.getAppLinkIfEnabled=(e,t)=>this.isLinkModeEnabled(e,t)?e?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=Qf(e,"topic")||"",n=decodeURIComponent(Qf(e,"wc_ev")||""),r=this.client.session.keys.includes(t);r&&this.client.session.update(t,{transportType:Ab.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:n,sessionExists:r})},this.registerLinkModeListeners=async()=>{if(eg()||$f()&&this.client.metadata.redirect?.linkMode){const t=e?.Linking;if(typeof t<"u"){t.addEventListener("url",this.handleLinkModeMessage,this.client.name);const e=await t.getInitialURL();e&&setTimeout(()=>{this.handleLinkModeMessage({url:e})},50)}}},this.getTVFApproveParams=e=>{try{const t=nm(e.namespaces),n=function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...e.methods)}),[...new Set(t)]}(e.namespaces),r=function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...e.events)}),[...new Set(t)]}(e.namespaces),i=e.sessionProperties;return{approvedChains:t,approvedMethods:n,approvedEvents:r,sessionProperties:i,scopedProperties:e.scopedProperties}}catch(e){return this.client.logger.warn(e,"Error getting TVF approve params"),{}}},this.getTVFParams=(e,t,n)=>{if(!t.request?.method)return{};const r={correlationId:e,rpcMethods:[t.request.method],chainId:t.chainId};try{const e=this.extractTxHashesFromResult(t.request,n);r.txHashes=e,r.contractAddresses=this.isValidContractData(t.request.params)?[t.request.params?.[0]?.to]:[]}catch(e){this.client.logger.warn(e,"Error getting TVF params")}return r},this.isValidContractData=e=>{if(!e)return!1;try{const t=e?.data||e?.[0]?.data;if(!t.startsWith("0x"))return!1;const n=t.slice(2);return!!/^[0-9a-fA-F]*$/.test(n)&&n.length%2==0}catch{}return!1},this.extractTxHashesFromResult=(e,t)=>{try{if(!t)return[];const n=e.method,r=dE[n];if("sui_signTransaction"===n)return[cg(t.transactionBytes)];if("near_signTransaction"===n)return[lg(t)];if("near_signTransactions"===n)return t.map(e=>lg(e));if("xrpl_signTransactionFor"===n||"xrpl_signTransaction"===n)return[t.tx_json?.hash];if("polkadot_signTransaction"===n)return[Tm({transaction:e.params.transactionPayload,signature:t.signature})];if("algo_signTxn"===n)return am(t)?t.map(e=>dg(e)):[dg(t)];if("cosmos_signDirect"===n)return[ug(t)];if("wallet_sendCalls"===n)return function(e){const t=[];try{if("string"==typeof e)return t.push(e),t;if("object"!=typeof e)return t;e?.id&&t.push(e.id);const n=e?.capabilities?.caip345?.transactionHashes;n&&t.push(...n)}catch(e){console.warn("getWalletSendCallsHashes failed: ",e)}return t}(t);if("string"==typeof t)return[t];const i=t[r.key];if(am(i))return"solana_signAllTransactions"===n?i.map(e=>function(e){const t=ig(e),n=t[0];if(0===n)throw new Error("No signatures found");const r=1+64*n;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const i=t.slice(1,65);return as.encode(i)}(e)):i;if("string"==typeof i)return[i]}catch(e){this.client.logger.warn(e,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,n]of Object.entries(t))for(const t of n)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=If("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hb,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:n,attestation:r,transportType:i}=e,{publicKey:s}=this.client.auth.authKeys.keys.includes(pE)?this.client.auth.authKeys.get(pE):{publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,n,{receiverPublicKey:s,encoding:i===Ab.link_mode?Og:Tg});rw(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:r,transportType:i,encryptedId:Mg(n)})):iw(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:i}),this.client.core.history.delete(t,e.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(e)}`),await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:i})),await this.client.core.relayer.messages.ack(t,n)}catch(e){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(Hb,async e=>{const{topic:t,id:n}=Wf(e.target);return n&&this.client.pendingRequest.keys.includes(n)?await this.deletePendingSessionRequest(n,If("EXPIRED"),!0):n&&this.client.auth.requests.keys.includes(n)?await this.deletePendingAuthRequest(n,If("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n})))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Ob,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Rb,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!dm(e,!1)){const{message:t}=If("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}=If("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=If("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!dm(e,!1)){const{message:t}=If("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}=If("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=If("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=If("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)){if(dm(e,!1)){const{message:t}=If("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=If("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!function(e){return"number"==typeof e}(e)){const{message:t}=If("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=If("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Kf(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=If("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&!function(e,t){return hm(e,!1)&&e<=t.max&&e>=t.min}(e,aE)){const{message:t}=If("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${aE.min} and ${aE.max}`);throw new Error(t)}}},gE=class extends qv{constructor(e,t){super(e,t,"proposal",eE),this.core=e,this.logger=t}},mE=class extends qv{constructor(e,t){super(e,t,"session",eE),this.core=e,this.logger=t}},yE=class extends qv{constructor(e,t){super(e,t,"request",eE,e=>e.id),this.core=e,this.logger=t}},wE=class extends qv{constructor(e,t){super(e,t,"authKeys",uE,()=>pE),this.core=e,this.logger=t}};class bE extends qv{constructor(e,t){super(e,t,"pairingTopics",uE),this.core=e,this.logger=t}}let vE=class extends qv{constructor(e,t){super(e,t,"requests",uE,e=>e.id),this.core=e,this.logger=t}},EE=class{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new wE(this.core,this.logger),this.pairingTopics=new bE(this.core,this.logger),this.requests=new vE(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};const xE=class e extends Cy{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=tE,this.events=new I.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}},this.update=async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}},this.request=async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}},this.find=e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.authenticate=async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}},this.approveSessionAuthenticate=async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.rejectSessionAuthenticate=async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.name=e?.name||tE,this.metadata=function(e){const t=Uf();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter(e=>""!==e)),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(n){return console.warn("Error populating app metadata",n),e||t}}(e?.metadata),this.signConfig=e?.signConfig;const t=Om({logger:e?.logger||nE,name:this.name});this.logger=t,this.core=e?.core||new Qv(e),this.session=new mE(this.core,this.logger),this.proposal=new gE(this.core,this.logger),this.pendingRequest=new yE(this.core,this.logger),this.engine=new fE(this),this.auth=new EE(this.core,this.logger)}static async init(t){const n=new e(t);return await n.initialize(),n}get context(){return yf(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var AE={exports:{}};!function(e,t){var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==o&&o,r=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==o&&o||{},r="URLSearchParams"in n,i="Symbol"in n&&"iterator"in Symbol,s="FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),a="FormData"in n,c="ArrayBuffer"in n;if(c)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(e){return e&&l.indexOf(Object.prototype.toString.call(e))>-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function p(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return i&&(t[Symbol.iterator]=function(){return t}),t}function f(e){this.map={},e instanceof f?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function g(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function m(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function y(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function w(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:s&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:a&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():c&&s&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=w(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c&&(ArrayBuffer.prototype.isPrototypeOf(e)||d(e))?this._bodyArrayBuffer=w(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s&&(this.blob=function(){var e=g(this);if(e)return e;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 e=g(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(s)return this.blob().then(y);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,n,r,i,s=g(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:"utf-8",t.readAsText(e,i),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a&&(this.formData=function(){return this.text().then(x)}),this.json=function(){return this.text().then(JSON.parse)},this}f.prototype.append=function(e,t){e=h(e),t=u(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},f.prototype.delete=function(e){delete this.map[h(e)]},f.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},f.prototype.set=function(e,t){this.map[h(e)]=u(t)},f.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},f.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),p(e)},f.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),p(e)},f.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),p(e)},i&&(f.prototype[Symbol.iterator]=f.prototype.entries);var v=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function E(e,t){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,i,s=(t=t||{}).body;if(e instanceof E){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new f(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,s||null==e._bodyInit||(s=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new f(t.headers)),this.method=(r=t.method||this.method||"GET",i=r.toUpperCase(),v.indexOf(i)>-1?i:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&s)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(s),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var o=/([?&])_=[^&]*/;if(o.test(this.url))this.url=this.url.replace(o,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function x(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function A(e,t){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.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=void 0===t.statusText?"":""+t.statusText,this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},b.call(E.prototype),b.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var k=[301,302,303,307,308];A.redirect=function(e,t){if(-1===k.indexOf(t))throw new RangeError("Invalid status code");return new A(null,{status:t,headers:{location:e}})},t.DOMException=n.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function I(e,r){return new Promise(function(i,o){var a=new E(e,r);if(a.signal&&a.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var l=new XMLHttpRequest;function d(){l.abort()}if(l.onload=function(){var e,t,n={statusText:l.statusText,headers:(e=l.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();try{t.append(r,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===a.url.indexOf("file://")&&(l.status<200||l.status>599)?n.status=200:n.status=l.status,n.url="responseURL"in l?l.responseURL:n.headers.get("X-Request-URL");var r="response"in l?l.response:l.responseText;setTimeout(function(){i(new A(r,n))},0)},l.onerror=function(){setTimeout(function(){o(new TypeError("Network request failed"))},0)},l.ontimeout=function(){setTimeout(function(){o(new TypeError("Network request timed out"))},0)},l.onabort=function(){setTimeout(function(){o(new t.DOMException("Aborted","AbortError"))},0)},l.open(a.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(a.url),!0),"include"===a.credentials?l.withCredentials=!0:"omit"===a.credentials&&(l.withCredentials=!1),"responseType"in l&&(s?l.responseType="blob":c&&(l.responseType="arraybuffer")),r&&"object"==typeof r.headers&&!(r.headers instanceof f||n.Headers&&r.headers instanceof n.Headers)){var p=[];Object.getOwnPropertyNames(r.headers).forEach(function(e){p.push(h(e)),l.setRequestHeader(e,u(r.headers[e]))}),a.headers.forEach(function(e,t){-1===p.indexOf(t)&&l.setRequestHeader(t,e)})}else a.headers.forEach(function(e,t){l.setRequestHeader(t,e)});a.signal&&(a.signal.addEventListener("abort",d),l.onreadystatechange=function(){4===l.readyState&&a.signal.removeEventListener("abort",d)}),l.send(void 0===a._bodyInit?null:a._bodyInit)})}I.polyfill=!0,n.fetch||(n.fetch=I,n.Headers=f,n.Request=E,n.Response=A),t.Headers=f,t.Request=E,t.Response=A,t.fetch=I,Object.defineProperty(t,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t}(AE,AE.exports);var kE=a(AE.exports),IE=Object.defineProperty,CE=Object.defineProperties,SE=Object.getOwnPropertyDescriptors,PE=Object.getOwnPropertySymbols,NE=Object.prototype.hasOwnProperty,_E=Object.prototype.propertyIsEnumerable,TE=(e,t,n)=>t in e?IE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,OE=(e,t)=>{for(var n in t||(t={}))NE.call(t,n)&&TE(e,n,t[n]);if(PE)for(var n of PE(t))_E.call(t,n)&&TE(e,n,t[n]);return e},$E=(e,t)=>CE(e,SE(t));const RE={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"};let BE=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new I.EventEmitter,this.isAvailable=!1,this.registering=!1,!ew(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=fl(e),n=await(await kE(this.url,$E(OE({},RE),{body:t}))).json();this.onPayload({data:n})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!ew(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise((e,t)=>{this.events.once("register_error",e=>{this.resetMaxListeners(),t(e)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return t(new Error("HTTP connection is missing or invalid"));e()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=fl({id:1,jsonrpc:"2.0",method:"test",params:[]});await kE(e,$E(OE({},RE),{body:t}))}this.onOpen()}catch(e){const t=this.parseError(e);throw this.events.emit("register_error",t),this.onClose(),t}}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="string"==typeof e.data?pl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),r=Ky(e,n.message||n.toString());this.events.emit("payload",r)}parseError(e,t=this.url){return Ly(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}};const ME="error",UE="universal_provider",LE=`wc@2:${UE}:`,DE="https://rpc.walletconnect.org/v1/",jE="generic",zE=`${DE}bundler`,HE="call_status",VE="default_chain_changed";function FE(e,t,n){const r=vf(e);return t.rpcMap?.[r.reference]||`${DE}?chainId=${r.namespace}:${r.reference}&projectId=${n}`}function qE(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function WE(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t?.chains?.length&&t?.chains?.length>0))}function ZE(e={},t={}){return nb(WE(KE(e)),WE(KE(t)))}function KE(e){const t={};if(!cm(e))return t;for(const[n,r]of Object.entries(e)){const e=rm(n)?[n]:r.chains,i=r.methods||[],s=r.events||[],o=r.rpcMap||{},a=im(n);t[a]={...t[a],...r,chains:Yf(e,t[a]?.chains),methods:Yf(i,t[a]?.methods),events:Yf(s,t[a]?.events)},(cm(o)||cm(t[a]?.rpcMap||{}))&&(t[a].rpcMap={...o,...t[a]?.rpcMap})}return t}function GE(e){return e.includes(":")?e.split(":")[2]:e}function YE(e){const t={};for(const[n,r]of Object.entries(e)){const e=r.methods||[],i=r.events||[],s=r.accounts||[],o=rm(n)?[n]:r.chains?r.chains:qE(r.accounts);t[n]={chains:o,methods:e,events:i,accounts:s}}return t}function JE(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const QE={},XE=e=>QE[e],ex=(e,t)=>{QE[e]=t},tx="eip155",nx=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],rx=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,ix=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,sx=e=>Object.keys(e).filter(e=>nx.includes(e)).reduce((t,n)=>(t[n]=ox(e[n]),t),{}),ox=e=>"string"==typeof e&&function(e){try{const t=JSON.parse(e);return"object"==typeof t&&null!==t&&!Array.isArray(t)}catch{return!1}}(e)?JSON.parse(e):e;let ax,cx=class e{constructor(e){this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(t){return ax||(ax=new e(t)),ax}};async function lx(e,t){const n=vf(e.result.capabilities.caip345.caip2),r=e.result.capabilities.caip345.transactionHashes,i=await Promise.allSettled(r.map(e=>async function(e,t,n){return await n(parseInt(e)).request(Wy("eth_getTransactionReceipt",[t]))}(n.reference,e,t))),s=i.filter(e=>"fulfilled"===e.status).map(e=>e.value).filter(e=>e);i.filter(e=>"rejected"===e.status).forEach(e=>console.warn("Failed to fetch transaction receipt:",e.reason));const o=!s.length||s.some(e=>!e),a=s.every(e=>"0x1"===e?.status),c=s.every(e=>"0x0"===e?.status),l=s.some(e=>"0x0"===e?.status);let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function dx({resultId:e,storage:t}){const n=(await t.getItem(HE))?.[e];if(n&&!Kf(n.expiry))return n;await async function({resultId:e,storage:t}){const n=await t.getItem(HE);if(n){delete n[e],await t.setItem(HE,n);for(const e in n)Kf(n[e].expiry)&&delete n[e];await t.setItem(HE,n)}}({resultId:e,storage:t})}let hx=class{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=XE("events"),this.client=XE("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=cx.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(VE,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}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 n=t||FE(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new aw(new BE(n,XE("disableProviderPing")))}setHttpProvider(e,t){const n=this.createHttpProvider(e,t);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const n=parseInt(function(e){return e.includes(":")?e.split(":")[1]:e}(t));e[n]=this.createHttpProvider(n,this.namespace.rpcMap?.[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders={...this.httpProviders,[t]:this.createHttpProvider(t)},this.httpProviders[t])}async handleSwitchChain(e){let t=e.request.params?e.request.params[0]?.chainId:"0x0";t=t.startsWith("0x")?t:`0x${t}`;const n=parseInt(t,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:t}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${n}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){const t=e.request?.params?.[0],n=e.request?.params?.[1]||[];if(!t)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const r=this.client.session.get(e.topic),i=r?.sessionProperties?.capabilities||{},s=`${t}${n.length>0?n.join(","):`0x${this.chainId.toString(16)}`}`,o=i?.[s];if(o)return o;let a;try{a=((e,t,n)=>{const{sessionProperties:r={},scopedProperties:i={}}=e,s={};if(!cm(i)&&!cm(r))return;const o=sx(r);for(const e of n){const n=rx(e);if(!n)continue;s[ix(n)]=o;const r=i?.[`${tx}:${n}`];if(r){const e=r?.[`${tx}:${n}:${t}`];s[ix(n)]={...s[ix(n)],...sx(e||r)}}}for(const[e,t]of Object.entries(s))0===Object.keys(t).length&&delete s[e];return Object.keys(s).length>0?s:void 0})(r,t,n)}catch(e){console.warn("Failed to extract capabilities from session",e)}if(a)return a;const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:{...r.sessionProperties||{},capabilities:{...i||{},[s]:c}}})}catch(e){console.warn("Failed to update session with capabilities",e)}return c}async getCallStatus(e){const t=this.client.session.get(e.topic),n=t.sessionProperties?.bundler_name;if(n){const t=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const r=t.sessionProperties?.bundler_url;if(r)try{return await this.getUserOperationReceipt(r,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,r)}const i=await dx({resultId:e.request.params?.[0],storage:this.storage});if(i)try{return await lx(i,this.getHttpProvider.bind(this))}catch(e){console.warn("Failed to fetch call status from stored send calls",e,i)}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){const n=new URL(e),r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Wy("eth_getUserOperationReceipt",[t.request.params?.[0]]))});if(!r.ok)throw new Error(`Failed to fetch user operation receipt - ${r.status}`);return await r.json()}getBundlerUrl(e,t){return`${zE}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){const t=await this.client.request(e),n=e.request.params?.[0],r=t?.id,i=t?.capabilities||{},s=i?.caip345?.caip2,o=i?.caip345?.transactionHashes;return!r||!s||!o?.length||await async function({sendCalls:e,storage:t}){const n=await t.getItem(HE);await t.setItem(HE,{...n,[e.result.id]:{request:e.request,result:e.result,expiry:Zf(86400)}})}({sendCalls:{request:n,result:t},storage:this.storage}),t}},ux=class{constructor(e){this.name=jE,this.namespace=e.namespace,this.events=XE("events"),this.client=XE("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t);const n=this.chainId;this.chainId=e,this.events.emit(VE,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return vf(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace?.accounts?.forEach(t=>{const n=vf(t),r=this.namespace?.rpcMap?.[`${n.namespace}:${n.reference}`];e[n.reference]=this.createHttpProvider(t,r)}),e}getHttpProvider(e){const t=vf(e).reference,n=this.httpProviders[t];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,t){const n=this.createHttpProvider(e,t);n&&(this.httpProviders[e]=n)}createHttpProvider(e,t){const n=t||FE(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new aw(new BE(n,XE("disableProviderPing")))}};const px=class e{constructor(e){this.events=new C,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=e,this.logger=Om({logger:e.logger??ME,name:this.providerOpts.name??UE}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(t){const n=new e(t);return await n.initialize(),n}async request(e,t,n){const[r,i]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:{...e},chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,t,n,r){const i=(new Date).getTime();this.request(e,n,r).then(e=>t(null,Zy(i,e))).catch(e=>t(e,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(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Cf("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,t);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const e=YE(this.session.namespaces);this.namespaces=ZE(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}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:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await n();this.session=r;const i=YE(r.namespaces);return this.namespaces=ZE(this.namespaces,i),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[n,r]=this.validateChain(e),i=this.getProvider(n);i?i.setDefaultChain(r,t):this.session&&this.logger.warn(`Provider for namespace '${n}' not found in setDefaultChain`)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!am(t))return;for(const n of t)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}catch(e){this.logger.warn(e,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){if(this.client=this.providerOpts.client||await xE.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ME,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",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(e){throw this.logger.error(e,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[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(e=>im(e)))];ex("client",this.client),ex("events",this.events),ex("disableProviderPing",this.disableProviderPing),e.forEach(e=>{if(!this.session)return;const t=function(e,t){const n=Object.keys(t.namespaces).filter(t=>t.includes(e));if(!n.length)return[];const r=[];return n.forEach(e=>{const n=t.namespaces[e].accounts;r.push(...n)}),r}(e,this.session);if(0===t?.length)return;const n=qE(t),r={...ZE(this.namespaces,this.optionalNamespaces)[e],accounts:t,chains:n};if("eip155"===e)this.rpcProviders[e]=new hx({namespace:r});else this.rpcProviders[e]=new ux({namespace:r})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{const{topic:t}=e;t===this.session?.topic&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t,topic:n}=e;if(n!==this.session?.topic)return;const{event:r}=t;if("accountsChanged"===r.name){const e=r.data;e&&am(e)&&this.events.emit("accountsChanged",e.map(GE))}else if("chainChanged"===r.name){const e=t.chainId,n=t.event.data,r=im(e),i=JE(e)!==JE(n)?`${r}:${JE(n)}`:e;this.onChainChanged({currentCaipChainId:i})}else this.events.emit(r.name,r.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{if(e!==this.session?.topic)return;const{namespaces:n}=t,r=this.client?.session.get(e);this.session={...r,namespaces:n},this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{e.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",{...Cf("USER_DISCONNECTED"),data:e.topic}))}),this.on(VE,e=>{this.onChainChanged({...e,internal:!0})})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[jE]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{this.getProvider(e).updateNamespace(this.session?.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=ZE(t,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[t,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,n];if(t&&!Object.keys(this.namespaces||{}).map(e=>im(e)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&n)return[t,n];const r=im(Object.keys(this.namespaces)[0]);return[r,this.rpcProviders[r].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);if(i){if(this.updateNamespaceChain(r,i),n)this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:t});else{const e=this.getProvider(r);e?e.setDefaultChain(i):this.session&&this.logger.warn(`Provider for namespace '${r}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:n}){try{if(n===t)return;const r=this.session?.namespaces[e]?.accounts;if(!r)return;const i=r.filter(e=>e.includes(`${t}:`)).map(GE);if(!am(i))return;this.events.emit("accountsChanged",i)}catch(e){this.logger.warn(e,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=t):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){const n=this.session?.topic||"";await this.client.core.storage.setItem(`${LE}/${e}${n}`,t)}async getFromStore(e){const t=this.session?.topic||"";return await this.client.core.storage.getItem(`${LE}/${e}${t}`)}async deleteFromStore(e){const t=this.session?.topic||"";await this.client.core.storage.removeItem(`${LE}/${e}${t}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;const e=await this.client.core.storage.getKeys();for(const t of e)t.startsWith(LE)&&await this.client.core.storage.removeItem(t)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}},fx=["eth_sendTransaction","personal_sign"],gx=["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"],mx=["chainChanged","accountsChanged"],yx=["chainChanged","accountsChanged","message","disconnect","connect"];function wx(e){return Number(e[0].split(":")[1])}function bx(e){return`0x${e.toString(16)}`}let vx=class e{constructor(){this.events=new I.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY="wc@2:ethereum_provider:",this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(t){const n=new e;return await n.initialize(t),n}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,n){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),n)}get connected(){return!!this.signer.client&&this.signer.client.core.relayer.connected}get connecting(){return!!this.signer.client&&this.signer.client.core.relayer.connecting}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:n}=function(e){const{chains:t,optionalChains:n,methods:r,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=e;if(!am(t))throw new Error("Invalid chains");const c={chains:t,methods:r||fx,events:s||mx,rpcMap:{...t.length?{[wx(t)]:a[wx(t)]}:{}}},l=s?.filter(e=>!mx.includes(e)),d=r?.filter(e=>!fx.includes(e));if(!(n||o||i||l?.length||d?.length))return{required:t.length?c:void 0};const h={chains:[...new Set(l?.length&&d?.length||!n?c.chains.concat(n||[]):n)],methods:[...new Set(c.methods.concat(i?.length?i:gx))],events:[...new Set(c.events.concat(o?.length?o:yx))],rpcMap:a};return{required:t.length?c:void 0,optional:n.length?h:void 0}}(this.rpc);try{const r=await new Promise(async(r,i)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),i(new Error("Connection request reset. Please try again.")))}));const s=e?.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect({namespaces:{...t&&{[this.namespace]:t}},...n&&{optionalNamespaces:{[this.namespace]:n}},pairingTopic:e?.pairingTopic,scopedProperties:s}).then(e=>{r(e)}).catch(e=>{this.modal?.showErrorMessage("Unable to connect"),i(new Error(e.message))})});if(!r)return;const i=Ef(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:i),this.setAccounts(i),this.events.emit("connect",{chainId:bx(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.close()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const n=await new Promise(async(n,r)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),r(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate({...e,chains:this.rpc.chains},t).then(e=>{n(e)}).catch(e=>{this.modal?.showErrorMessage("Unable to connect"),r(new Error(e.message))})}),r=n.session;if(r){const e=Ef(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:e),this.setAccounts(e),this.events.emit("connect",{chainId:bx(this.chainId)})}return n}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.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:n}=t;"accountsChanged"===n.name?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):"chainChanged"===n.name?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.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",bx(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",{...Cf("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"string"==typeof e&&e.startsWith(`${this.namespace}:`)}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(e=>this.isCompatibleChainId(e)).map(e=>this.parseChainId(e));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",bx(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,n,r]=e.split(":");return{chainId:`${t}:${n}`,address:r}}setAccounts(e){this.accounts=e.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){const t=e?.chains??[],n=e?.optionalChains??[],r=t.concat(n);if(!r.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const i=t.length?e?.methods||fx:[],s=t.length?e?.events||mx:[],o=e?.optionalMethods||[],a=e?.optionalEvents||[],c=e?.rpcMap||this.buildRpcMap(r,e.projectId),l=e?.qrModalOptions||void 0;return{chains:t?.map(e=>this.formatChainId(e)),optionalChains:n.map(e=>this.formatChainId(e)),methods:i,events:s,optionalMethods:o,optionalEvents:a,rpcMap:c,showQrModal:!!e?.showQrModal,qrModalOptions:l,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const n={};return e.forEach(e=>{n[e]=this.getRpcUrl(e,t)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?wx(this.rpc.chains):wx(this.rpc.optionalChains),this.signer=await px.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 e;try{const t=await(async()=>{const{createAppKit:e}=await Promise.resolve().then(function(){return p5});return e})(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return Ix}),r=n({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!r.networks.length)throw new Error("No networks found for WalletConnect");e=t({...r,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:!0===this.rpc.qrModalOptions?.enableMobileFullScreen})}catch(e){throw console.warn(e),new Error("To use QR modal, please install @reown/appkit package")}if(e)try{this.modal=e}catch(e){throw this.signer.logger.error(e),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:n,rpcMap:r}=e;t&&am(t)&&(this.rpc.chains=t.map(e=>this.formatChainId(e)),t.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)})),n&&am(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(e=>this.formatChainId(e)),n.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)}))}getRpcUrl(e,t){return this.rpc.rpcMap?.[e]||`https://rpc.walletconnect.org/v1/?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?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(e=>this.signer.logger.warn(e))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return"string"==typeof e||e instanceof String?[this.parseAccount(e)]:e.map(e=>this.parseAccount(e))}};const Ex=vx;function xx(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const Ax=e=>{const[t,n]=e.split(":");return kx({id:n,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function kx(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var Ix=Object.freeze({__proto__:null,convertWCMToAppKitOptions:function(e){const t=e.chains?.map(Ax).filter(Boolean);if(0===t.length)throw new Error("At least one chain must be specified");const n=t.find(t=>t.id===e.defaultChain?.id),r={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:xx(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:n,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:"NONE"===e.explorerRecommendedWalletIds?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:"ALL"===e.explorerExcludedWalletIds?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){const t=[...(e.mobileWallets||[]).map(e=>({id:e.id,name:e.name,links:e.links})),...(e.desktopWallets||[]).map(e=>({id:e.id,name:e.name,links:{native:e.links.native,universal:e.links.universal}}))],n=[...r.featuredWalletIds||[],...r.excludeWalletIds||[]],i=t.filter(e=>!n.includes(e.id));i.length&&(r.customWallets=i)}return r},defineChain:kx}),Cx=Object.freeze({__proto__:null,EthereumProvider:Ex,OPTIONAL_EVENTS:yx,OPTIONAL_METHODS:gx,REQUIRED_EVENTS:mx,REQUIRED_METHODS:fx,default:vx});const Sx=[{name:"MetaMask",icon:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",universalLink:e=>`https://metamask.app.link/wc?uri=${encodeURIComponent(e)}`},{name:"Trust Wallet",icon:"https://trustwallet.com/assets/images/favicon.png",universalLink:e=>`https://link.trustwallet.com/wc?uri=${encodeURIComponent(e)}`},{name:"Rainbow",icon:"https://rainbow.me/favicon.ico",universalLink:e=>`https://rnbwapp.com/wc?uri=${encodeURIComponent(e)}`},{name:"Coinbase Wallet",icon:"https://www.coinbase.com/favicon.ico",universalLink:e=>`https://go.cb-w.com/wc?uri=${encodeURIComponent(e)}`}];class Px{constructor(){this.injectedProviders=[],this.selectedProvider=null,this.wcProvider=null,this.connectedAddress=null,this.connectionType=null,this._wcSessionReady=!1,this._accountsChangedHandler=null,this._chainChangedHandler=null,this._wcSessionRequestSentHandler=null,this._onWCUri=null,this._onWCConnected=null,this._onWCDisconnected=null;["isMobile","isIOS","discoverInjectedWallets","connectInjected","initWalletConnect","connectWalletConnect","getActiveChainId","getApprovedChainIds","isSessionAlive","switchNetwork","disconnect","_openWalletForApproval","_attachProviderListeners","_cleanupWC","_connectionResult","isConnected","getAddress","getProvider","getMobileWallets"].forEach(e=>{this[e]=this[e].bind(this)})}isMobile(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}isIOS(){return/iPhone|iPad|iPod/i.test(navigator.userAgent)}async getActiveChainId(){const e=this.selectedProvider;if(!e)return null;try{const t=await e.request({method:"eth_chainId"}),n=parseInt(t,16);return console.log("[WalletService] eth_chainId RPC →",n),n}catch(e){return console.error("[WalletService] eth_chainId RPC failed:",e.message),null}}getApprovedChainIds(){if(!this._wcSessionReady)return[];const e=this.wcProvider?.session?.namespaces?.eip155?.accounts??[],t=new Set;for(const n of e){const e=n.split(":"),r=parseInt(e[1],10);e.length>=3&&!isNaN(r)&&r>0&&t.add(r)}return[...t]}async isSessionAlive(){if(!this.selectedProvider)return!1;try{return await this.selectedProvider.request({method:"eth_chainId"}),!0}catch{return!1}}discoverInjectedWallets(){return new Promise(e=>{this.injectedProviders=[];const t=e=>{const{info:t,provider:n}=e.detail??{};if(!t||!n)return;const r=this.injectedProviders.some(e=>e.info.uuid===t.uuid);r||this.injectedProviders.push({info:t,provider:n})};window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{window.removeEventListener("eip6963:announceProvider",t),0===this.injectedProviders.length&&window.ethereum&&this.injectedProviders.push({info:{uuid:"legacy",name:window.ethereum.isMetaMask?"MetaMask":"Browser Wallet",icon:window.ethereum.isMetaMask?"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg":null},provider:window.ethereum}),console.log(`[WalletService] Injected providers found (${this.injectedProviders.length}):`,this.injectedProviders.map(e=>e.info.name)),e(this.injectedProviders)},300)})}async connectInjected(e){const t=this.injectedProviders[e];if(!t)throw new Error(`[WalletService] No injected provider at index ${e}`);let n;console.log(`[WalletService] Connecting injected: ${t.info.name}`);try{n=await t.provider.request({method:"eth_requestAccounts"})}catch(e){if(4001===e.code){const e=new Error("User rejected the connection");throw e.code="USER_CANCELLED",e}throw e}if(!n?.length){const e=new Error("No accounts returned");throw e.code="USER_CANCELLED",e}this.selectedProvider=t.provider,this.connectedAddress=n[0],this.connectionType="injected",this._wcSessionReady=!1,this._attachProviderListeners(t.provider);const r=await this.getActiveChainId();return console.log(`[WalletService] Injected connected — address: ${this.connectedAddress} | chain: ${r}`),this._connectionResult()}async initWalletConnect(e,t,n){const{EthereumProvider:r}=await Promise.resolve().then(function(){return Cx});if(this.wcProvider){try{await this.wcProvider.disconnect()}catch(e){}this.wcProvider=null}this._wcSessionReady=!1;const s=Object.values(i).map(e=>e.chainId),o={};Object.values(i).forEach(e=>{o[e.chainId]=e.rpcUrl}),console.log("[WalletService] Initializing WalletConnect — supported chains:",s);const a=await r.init({projectId:"3a2347dfc8ba5a336fe715a34644f490",optionalChains:s,showQrModal:!1,rpcMap:o,metadata:{name:"KwesPay",description:"Crypto payment widget",url:window.location.origin,icons:["https://arthuremma2.github.io/img-hosting/kwespay-icon.png"]}});return this._onWCUri=e,this._onWCConnected=t,this._onWCDisconnected=n,a.on("display_uri",e=>{this._onWCUri&&this._onWCUri(e)}),a.on("connect",async()=>{const e=a.session,t=e?.namespaces?.eip155?.accounts??[];if(0===t.length)return void console.error("[WalletService] WC connected but session has no accounts");const n=t[0].split(":")[2];this.wcProvider=a,this.selectedProvider=a,this.connectedAddress=n,this.connectionType="walletconnect",this._wcSessionReady=!0,this._attachProviderListeners(a);const r=await this.getActiveChainId(),i=this.getApprovedChainIds();console.log(`[WalletService] WC session ready — address: ${n} | active chain: ${r} | approved chains: [${i}]`),this._onWCConnected&&this._onWCConnected()}),a.on("disconnect",()=>{console.log("[WalletService] WC session disconnected"),this._cleanupWC(),this._onWCDisconnected&&this._onWCDisconnected()}),a.on("chainChanged",e=>{this._wcSessionReady&&console.log("[WalletService] WC chainChanged event — new chain:",parseInt(e,16))}),this._wcSessionRequestSentHandler=()=>{this.isMobile()&&(console.log("[WalletService] session_request_sent — opening wallet for approval"),this._openWalletForApproval())},a.on("session_request_sent",this._wcSessionRequestSentHandler),this.wcProvider=a,a}async connectWalletConnect(e){if(!this.wcProvider)throw new Error("[WalletService] Call initWalletConnect first");if(!e)throw new Error("[WalletService] targetChainId is required for connectWalletConnect");console.log(`[WalletService] Starting WC handshake — requesting session on chain ${e}`),await this.wcProvider.connect({optionalNamespaces:{eip155:{methods:["eth_sendTransaction","eth_signTransaction","eth_sign","personal_sign","eth_signTypedData"],chains:[`eip155:${e}`],events:["chainChanged","accountsChanged"]}}})}_openWalletForApproval(){const e=this.wcProvider?.session,t=e?.peer?.metadata?.redirect?.native,n=e?.peer?.metadata?.redirect?.universal,r=t||n;r?this.isIOS()?window.location.href=r:window.open(r,"_blank","noreferrer noopener"):console.warn("[WalletService] No redirect URI in session metadata — user must switch manually")}async switchNetwork(e,t,n,r,i){const s=this.selectedProvider;if(!s)throw new Error("[WalletService] No provider connected");const o="0x"+e.toString(16);try{await s.request({method:"wallet_switchEthereumChain",params:[{chainId:o}]})}catch(e){if(4902!==e.code&&-32603!==e.code)throw e;console.log(`[WalletService] Chain ${t} unknown to wallet — adding it`),await s.request({method:"wallet_addEthereumChain",params:[{chainId:o,chainName:t,rpcUrls:[n],nativeCurrency:{name:r,symbol:r,decimals:i}}]}),console.log(`[WalletService] Chain ${t} added and switched`)}}_attachProviderListeners(e){this._accountsChangedHandler=e=>{console.log("[WalletService] accountsChanged →",e[0]??"none"),this.connectedAddress=e[0]??null},this._chainChangedHandler=e=>{"injected"===this.connectionType&&console.log("[WalletService] chainChanged (injected) →",parseInt(e,16))},e.on("accountsChanged",this._accountsChangedHandler),e.on("chainChanged",this._chainChangedHandler)}async disconnect(){if(this.selectedProvider){try{this.selectedProvider.removeListener?.("accountsChanged",this._accountsChangedHandler)}catch(e){}try{this.selectedProvider.removeListener?.("chainChanged",this._chainChangedHandler)}catch(e){}}this._cleanupWC(),this.selectedProvider=null,this.connectedAddress=null,this.connectionType=null,this._wcSessionReady=!1,console.log("[WalletService] Disconnected")}_cleanupWC(){if(this.wcProvider){try{this.wcProvider.removeListener?.("display_uri",this._onWCUri)}catch(e){}try{this.wcProvider.removeListener?.("connect",this._onWCConnected)}catch(e){}try{this.wcProvider.removeListener?.("disconnect",this._onWCDisconnected)}catch(e){}try{this.wcProvider.removeListener?.("session_request_sent",this._wcSessionRequestSentHandler)}catch(e){}try{this.wcProvider.disconnect()}catch(e){}this.wcProvider=null}this._wcSessionReady=!1,this._onWCUri=null,this._onWCConnected=null,this._onWCDisconnected=null,this._wcSessionRequestSentHandler=null}_connectionResult(){return{address:this.connectedAddress,shortAddress:this._truncate(this.connectedAddress),provider:this.selectedProvider,connectionType:this.connectionType}}_truncate(e){return e?`${e.slice(0,6)}...${e.slice(-4)}`:""}isConnected(){return!!this.connectedAddress}getAddress(){return this.connectedAddress}getProvider(){return this.selectedProvider}getMobileWallets(){return Sx}}let Nx=class{constructor(e,t){this.apiKey=e,this.graphqlEndpoint=t,this.client=null,console.log("[KwesPay] PaymentService initialized",{apiKey:this.apiKey?.slice(0,6)+"..."})}async _initClient(){if(this.client)return;console.log("[KwesPay] Initializing SDK client...");const{KwesPayClient:e}=await Promise.resolve().then(function(){return Y9});this.client=new e({apiKey:this.apiKey}),console.log("[KwesPay] SDK client ready")}async validateAPIKey(){try{await this._initClient();const e=await this.client.validateKey();return e.isValid?{valid:!0,keyId:e.keyId,vendorInfo:e.vendorInfo,allowedVendors:e.scope.allowedVendors??null,allowedNetworks:e.scope.allowedNetworks??null,allowedTokens:e.scope.allowedTokens??null}:(console.error("[KwesPay] Invalid API key:",e.error),{valid:!1,error:e.error??"Invalid access key"})}catch(e){return console.error("[KwesPay] API key validation error:",e),{valid:!1,error:e.message}}}async getQuote(e){await this._initClient(),console.log("[KwesPay] Requesting quote...",e);const t=await this.client.quote({vendorIdentifier:e.vendorId,fiatAmount:e.fiatAmount,fiatCurrency:e.fiatCurrency||"USD",cryptoCurrency:e.cryptoCurrency,network:e.network,payerWalletAddress:e.payerWalletAddress});return console.log("[KwesPay] Quote received:",t),t}async createPayment({payload:e,walletProvider:t,onStatusUpdate:n}){await this._initClient(),console.log("[KwesPay] 💳 createPayment called",{payloadKeys:e?Object.keys(e):null,amountBaseUnits:e?.amountBaseUnits,contractAddress:e?.contractAddress,paymentId:e?.paymentId,vendorAddress:e?.vendorAddress,expiresAt:e?.expiresAt,providerType:t?.constructor?.name});try{const r=await this.client.pay({provider:t,payload:e,onStatus:e=>{console.log("[KwesPay] 📋 Payment status update:",e),n?.(e)}});return console.log("[KwesPay] ✅ Payment completed:",r),{hash:r.txHash,blockNumber:r.blockNumber,transactionReference:r.transactionReference,paymentIdBytes32:r.paymentIdBytes32}}catch(e){throw console.error("[KwesPay] ❌ createPayment error:",{message:e?.message,code:e?.code,reason:e?.reason,data:e?.data,transaction:e?.transaction?{to:e.transaction?.to,from:e.transaction?.from,value:e.transaction?.value?.toString(),gasLimit:e.transaction?.gasLimit?.toString(),data:e.transaction?.data}:void 0,receipt:e?.receipt?{status:e.receipt?.status,gasUsed:e.receipt?.gasUsed?.toString(),blockNumber:e.receipt?.blockNumber,transactionHash:e.receipt?.transactionHash}:void 0,stack:e?.stack,raw:e}),e}}async getTransactionStatus(e){await this._initClient(),console.log("[KwesPay] Fetching transaction status:",e);const t=await this.client.getTransactionStatus(e);return console.log("[KwesPay] Transaction status:",t),t}async pollTransactionStatus(e,{onStatus:t,intervalMs:n=4e3,maxAttempts:r=60}={}){await this._initClient(),console.log("[KwesPay] Starting polling...",{transactionReference:e,intervalMs:n});let i=0;return new Promise((s,o)=>{const a=setInterval(async()=>{i++;try{const n=await this.getTransactionStatus(e);console.log(`[KwesPay] Poll attempt ${i}:`,n.transactionStatus),t?.(n.transactionStatus);["completed","failed","expired","underpaid","overpaid","refunded"].includes(n.transactionStatus)?(console.log("[KwesPay] Final status reached:",n.transactionStatus),clearInterval(a),s(n)):i>=r&&(console.error("[KwesPay] Polling timeout"),clearInterval(a),o(new Error("Transaction status polling timed out.")))}catch(e){console.error("[KwesPay] Polling error:",e),i>=r&&(clearInterval(a),o(e))}},n)})}};function _x(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Tx(e,t={}){const n=new CustomEvent(`kwespay:${e}`,{detail:t,bubbles:!0,cancelable:!0});window.dispatchEvent(n)}function Ox(e){const t=e?.message??"";return 4001===e?.code||"ACTION_REJECTED"===e?.code||t.includes("rejected")||t.includes("denied")||t.includes("cancelled")?"USER_REJECTED":t.toLowerCase().includes("insufficient")?"INSUFFICIENT_BALANCE":t.includes("User rejected")||t.includes("User closed modal")||t.includes("Connection request reset")?"CONNECTION_REJECTED":t.includes("timeout")?"TIMEOUT":"UNKNOWN"}const $x={_init(){this._injectFonts(),this._injectStyles(),this._createWidgetDOM()},_injectFonts(){if(!document.querySelector('link[href*="fonts.googleapis.com/css2?family=Syne"]')){const e=document.createElement("link");e.href="https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=DM+Mono:wght@300;400;500&family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap",e.rel="stylesheet",document.head.appendChild(e)}},_injectStyles(){if(!document.getElementById("kwespay-widget-styles")){const e=document.createElement("style");e.id="kwespay-widget-styles",e.textContent="\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n\n * { margin: 0; padding: 0; box-sizing: border-box; }\n\n :root {\n --kp-bg: #0a0a0f;\n --kp-surface: #0f0f18;\n --kp-surface-2: #16161f;\n --kp-border: rgba(255,255,255,0.06);\n --kp-border-active: rgba(99,102,241,0.5);\n --kp-accent: #6366f1;\n --kp-accent-dim: rgba(99,102,241,0.1);\n --kp-accent-glow: rgba(99,102,241,0.25);\n --kp-green: #10b981;\n --kp-red: #f43f5e;\n --kp-text: #f1f0ff;\n --kp-muted: #6b6a80;\n --kp-mono: 'Inter', monospace;\n --kp-sans: 'Inter', sans-serif;\n }\n\n body.kwespay-open {\n overflow: hidden;\n touch-action: none;\n }\n\n .kwespay-overlay {\n position: fixed;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.75);\n backdrop-filter: blur(8px) saturate(1.2);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n padding: 20px;\n font-family: var(--kp-sans);\n }\n\n .kwespay-overlay.open { display: flex; }\n\n .kwespay-close-btn {\n position: absolute;\n top: 20px; right: 20px;\n background: rgba(255,255,255,0.06);\n border: 1px solid var(--kp-border);\n color: var(--kp-muted);\n width: 34px; height: 34px;\n border-radius: 8px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 18px;\n transition: all 0.15s;\n z-index: 1000000;\n }\n\n .kwespay-close-btn:hover {\n background: rgba(255,255,255,0.1);\n color: var(--kp-text);\n border-color: var(--kp-border-active);\n }\n\n .material-symbols-outlined {\n font-variation-settings: \"FILL\" 0, \"wght\" 400, \"GRAD\" 0, \"opsz\" 24;\n }\n\n .kwespay-container {\n position: relative;\n display: flex;\n height: 640px;\n max-height: 92vh;\n min-height: 520px;\n width: 100%;\n max-width: 390px;\n flex-direction: column;\n background: var(--kp-bg);\n border: 1px solid var(--kp-border);\n box-shadow:\n 0 0 0 1px rgba(255,255,255,0.03),\n 0 32px 64px rgba(0,0,0,0.9),\n 0 0 80px rgba(99,102,241,0.06);\n overflow: hidden;\n border-radius: 20px;\n font-family: var(--kp-sans);\n animation: kpSlideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;\n }\n\n @keyframes kpSlideUp {\n from { opacity: 0; transform: translateY(20px) scale(0.98); }\n to { opacity: 1; transform: translateY(0) scale(1); }\n }\n\n .step {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n display: none;\n opacity: 0;\n }\n\n .step.active {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n animation: kpFadeIn 0.2s ease forwards;\n }\n\n .step.exiting {\n animation: kpFadeOut 0.15s ease forwards;\n }\n\n @keyframes kpFadeIn {\n from { opacity: 0; transform: translateY(6px); }\n to { opacity: 1; transform: translateY(0); }\n }\n\n @keyframes kpFadeOut {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n\n .kp-topbar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 20px;\n border-bottom: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .kp-topbar-brand {\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .kp-back-btn {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border-radius: 7px;\n background: rgba(255,255,255,0.04);\n border: 1px solid var(--kp-border);\n color: var(--kp-muted);\n cursor: pointer;\n transition: all 0.15s;\n flex-shrink: 0;\n margin-right: 4px;\n }\n\n .kp-back-btn:hover {\n background: rgba(255,255,255,0.08);\n color: var(--kp-text);\n border-color: rgba(255,255,255,0.12);\n }\n\n .kp-back-btn .material-symbols-outlined { font-size: 16px; }\n\n .kp-topbar-dot {\n width: 7px; height: 7px;\n border-radius: 50%;\n background: var(--kp-accent);\n box-shadow: 0 0 8px var(--kp-accent-glow);\n animation: kpPulse 2s ease infinite;\n }\n\n @keyframes kpPulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n\n .kp-topbar-name {\n font-size: 13px;\n font-weight: 600;\n color: var(--kp-text);\n letter-spacing: -0.01em;\n }\n\n .kp-topbar-secure {\n display: flex;\n align-items: center;\n gap: 5px;\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.04em;\n font-weight: 500;\n }\n\n .kp-topbar-secure .material-symbols-outlined {\n font-size: 13px;\n color: var(--kp-green);\n }\n\n .kp-amount-block {\n padding: 20px 20px 16px;\n border-bottom: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .kp-amount-label {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.08em;\n text-transform: uppercase;\n margin-bottom: 6px;\n font-weight: 500;\n }\n\n .kp-amount-value {\n font-size: 32px;\n font-weight: 700;\n color: var(--kp-text);\n letter-spacing: -0.03em;\n line-height: 1;\n }\n\n .kp-amount-hint {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-muted);\n margin-top: 6px;\n min-height: 16px;\n font-weight: 400;\n }\n\n .kp-amount-crypto {\n font-family: var(--kp-mono);\n font-size: 12px;\n color: var(--kp-accent);\n margin-top: 6px;\n min-height: 16px;\n transition: opacity 0.2s;\n font-weight: 500;\n }\n\n .kp-amount-crypto.loading { opacity: 0.4; }\n\n .progress-section {\n padding: 14px 20px 12px;\n border-bottom: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .progress-info {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 8px;\n }\n\n .progress-step {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.06em;\n font-weight: 500;\n }\n\n .progress-label {\n font-size: 11px;\n font-weight: 600;\n color: var(--kp-accent);\n letter-spacing: 0.02em;\n text-transform: uppercase;\n }\n\n .progress-bars { display: flex; width: 100%; gap: 5px; }\n\n .progress-bar {\n height: 2px;\n flex: 1;\n border-radius: 999px;\n background: var(--kp-surface-2);\n transition: background 0.3s ease;\n }\n\n .progress-bar.active {\n background: var(--kp-accent);\n box-shadow: 0 0 8px var(--kp-accent-glow);\n }\n\n .section-hint {\n font-size: 12px;\n color: var(--kp-muted);\n margin-bottom: 14px;\n line-height: 1.6;\n font-weight: 400;\n }\n\n .content-scroll {\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n padding: 16px 20px;\n -webkit-overflow-scrolling: touch;\n }\n\n .content-scroll::-webkit-scrollbar { width: 3px; }\n .content-scroll::-webkit-scrollbar-track { background: transparent; }\n .content-scroll::-webkit-scrollbar-thumb {\n background: rgba(99,102,241,0.2);\n border-radius: 10px;\n }\n\n .item-list {\n display: flex;\n flex-direction: column;\n gap: 6px;\n margin-bottom: 6px;\n }\n\n .kp-testnet-section { margin-top: 20px; }\n\n .kp-section-divider {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.08em;\n text-transform: uppercase;\n margin-bottom: 10px;\n padding-bottom: 8px;\n border-bottom: 1px solid var(--kp-border);\n font-weight: 500;\n }\n\n .list-item {\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--kp-surface);\n padding: 12px 14px;\n border-radius: 12px;\n border: 1px solid var(--kp-border);\n cursor: pointer;\n transition: all 0.15s;\n }\n\n .list-item:hover {\n border-color: var(--kp-border-active);\n background: var(--kp-accent-dim);\n transform: translateX(2px);\n }\n\n .item-icon {\n width: 36px; height: 36px;\n border-radius: 10px;\n display: flex; align-items: center; justify-content: center;\n background: var(--kp-surface-2);\n overflow: hidden;\n border: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .item-icon img { width: 22px; height: 22px; object-fit: contain; }\n .item-info { display: flex; flex-direction: column; flex: 1; }\n .item-name-row { display: flex; align-items: center; gap: 7px; }\n\n .item-name {\n font-size: 13px;\n font-weight: 600;\n color: var(--kp-text);\n }\n\n .item-badge {\n padding: 1px 6px;\n border-radius: 4px;\n font-size: 9px;\n font-weight: 600;\n font-family: var(--kp-mono);\n letter-spacing: 0.04em;\n text-transform: uppercase;\n }\n\n .badge-testnet {\n background: rgba(251,146,60,0.08);\n color: #fb923c;\n border: 1px solid rgba(251,146,60,0.2);\n }\n\n .item-desc {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n margin-top: 3px;\n font-weight: 400;\n }\n\n .item-chevron { color: var(--kp-muted); font-size: 16px; }\n\n .token-item {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 13px 14px;\n cursor: pointer;\n transition: all 0.15s;\n border: 1px solid var(--kp-border);\n border-radius: 12px;\n margin-bottom: 6px;\n background: var(--kp-surface);\n position: relative;\n overflow: hidden;\n }\n\n .token-item:last-child { margin-bottom: 0; }\n .token-item:hover { border-color: var(--kp-border-active); background: var(--kp-accent-dim); }\n .token-item.selected { background: var(--kp-accent-dim); border-color: var(--kp-accent); }\n .token-item.selected::after {\n content: '';\n position: absolute; inset: 0;\n background: linear-gradient(90deg, rgba(99,102,241,0.08) 0%, transparent 100%);\n pointer-events: none;\n }\n .token-item.selected .token-symbol { color: var(--kp-accent); }\n\n .token-left { display: flex; align-items: center; gap: 12px; flex: 1; }\n\n .token-icon {\n width: 36px; height: 36px;\n border-radius: 10px;\n background: var(--kp-surface-2);\n border: 1px solid var(--kp-border);\n overflow: hidden;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .token-icon img { width: 22px; height: 22px; object-fit: contain; }\n .token-info { display: flex; flex-direction: column; justify-content: center; }\n\n .token-symbol {\n color: var(--kp-text);\n font-size: 13px;\n font-weight: 600;\n line-height: 1;\n margin-bottom: 3px;\n transition: color 0.15s;\n }\n\n .token-name {\n font-family: var(--kp-mono);\n color: var(--kp-muted);\n font-size: 10px;\n line-height: 1;\n font-weight: 400;\n }\n\n .token-chevron { color: var(--kp-muted); font-size: 16px; flex-shrink: 0; }\n #kwespay-tokenList { display: flex; flex-direction: column; }\n\n .bottom-action {\n padding: 12px 20px 16px;\n background: var(--kp-bg);\n border-top: 1px solid var(--kp-border);\n flex-shrink: 0;\n }\n\n .action-btn {\n width: 100%;\n padding: 13px;\n border-radius: 12px;\n background: var(--kp-accent);\n color: white;\n font-weight: 600;\n font-size: 14px;\n border: none;\n cursor: pointer;\n transition: all 0.15s;\n font-family: var(--kp-sans);\n letter-spacing: -0.01em;\n position: relative;\n overflow: hidden;\n }\n\n .action-btn::before {\n content: '';\n position: absolute; inset: 0;\n background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, transparent 60%);\n pointer-events: none;\n }\n\n .action-btn:hover { background: #5254cc; box-shadow: 0 0 20px var(--kp-accent-glow); }\n .action-btn:active { transform: scale(0.99); }\n\n .action-btn.secondary {\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n color: var(--kp-muted);\n }\n\n .action-btn.secondary::before { display: none; }\n .action-btn.secondary:hover {\n background: var(--kp-surface-2);\n border-color: var(--kp-border-active);\n color: var(--kp-text);\n box-shadow: none;\n }\n\n .action-btn:disabled { opacity: 0.3; cursor: not-allowed; box-shadow: none; }\n\n .kp-footer {\n padding: 10px 20px 12px;\n background: var(--kp-bg);\n border-top: 1px solid var(--kp-border);\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 6px;\n flex-shrink: 0;\n }\n\n .kp-footer-lock { font-size: 11px; color: var(--kp-green); }\n\n .kp-footer-text {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n letter-spacing: 0.02em;\n font-weight: 400;\n }\n\n .kp-footer-text span { color: var(--kp-text); font-weight: 500; }\n\n .loading-container {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 24px 20px;\n flex: 1;\n }\n\n .spinner-wrapper {\n position: relative;\n width: 64px; height: 64px;\n display: flex; align-items: center; justify-content: center;\n margin-bottom: 20px;\n }\n\n .spinner-ring {\n position: absolute;\n width: 64px; height: 64px;\n border-radius: 50%;\n border: 2px solid transparent;\n border-top-color: var(--kp-accent);\n animation: kpSpin 0.85s linear infinite;\n }\n\n .spinner-ring-2 {\n position: absolute;\n width: 48px; height: 48px;\n border-radius: 50%;\n border: 2px solid transparent;\n border-bottom-color: rgba(99,102,241,0.3);\n animation: kpSpin 1.2s linear infinite reverse;\n }\n\n @keyframes kpSpin { to { transform: rotate(360deg); } }\n\n .spinner-icon {\n z-index: 10;\n width: 32px; height: 32px;\n background: var(--kp-accent-dim);\n border-radius: 8px;\n display: flex; align-items: center; justify-content: center;\n border: 1px solid rgba(99,102,241,0.2);\n }\n\n .spinner-icon .material-symbols-outlined { font-size: 18px; color: var(--kp-accent); }\n\n .headline {\n color: var(--kp-text);\n font-size: 18px;\n font-weight: 700;\n line-height: 1.3;\n text-align: center;\n margin-bottom: 8px;\n letter-spacing: -0.02em;\n }\n\n .body-text {\n color: var(--kp-muted);\n font-size: 13px;\n line-height: 1.6;\n text-align: center;\n padding: 0 8px;\n margin-bottom: 8px;\n font-weight: 400;\n }\n\n .success-icon {\n width: 64px; height: 64px;\n border-radius: 16px;\n background: rgba(16,185,129,0.1);\n border: 1px solid rgba(16,185,129,0.2);\n display: flex; align-items: center; justify-content: center;\n margin-bottom: 16px;\n }\n\n .success-icon .material-symbols-outlined { font-size: 36px; color: var(--kp-green); }\n\n .error-icon {\n width: 64px; height: 64px;\n border-radius: 16px;\n background: rgba(244,63,94,0.1);\n border: 1px solid rgba(244,63,94,0.2);\n display: flex; align-items: center; justify-content: center;\n margin-bottom: 16px;\n }\n\n .error-icon .material-symbols-outlined { font-size: 36px; color: var(--kp-red); }\n\n .network-status { padding: 14px 20px 0; }\n\n .status-card {\n display: flex;\n align-items: center;\n gap: 10px;\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 10px;\n padding: 10px 14px;\n }\n\n .status-icon {\n width: 24px; height: 24px;\n border-radius: 6px;\n background: var(--kp-surface-2);\n overflow: hidden; flex-shrink: 0;\n display: flex; align-items: center; justify-content: center;\n }\n\n .status-icon img { width: 16px; height: 16px; object-fit: contain; }\n .status-text { color: var(--kp-accent); font-size: 12px; font-weight: 600; flex: 1; }\n\n .kp-review-body { flex: 1; overflow-y: auto; padding: 16px 20px; }\n .kp-review-body::-webkit-scrollbar { width: 3px; }\n .kp-review-body::-webkit-scrollbar-thumb { background: rgba(99,102,241,0.2); border-radius: 10px; }\n\n .kp-review-amount {\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n border-radius: 14px;\n padding: 18px;\n margin-bottom: 12px;\n text-align: center;\n }\n\n .kp-review-fiat {\n font-size: 28px;\n font-weight: 700;\n color: var(--kp-text);\n letter-spacing: -0.03em;\n line-height: 1;\n margin-bottom: 6px;\n }\n\n .kp-review-crypto-line {\n font-family: var(--kp-mono);\n font-size: 13px;\n color: var(--kp-accent);\n font-weight: 500;\n }\n\n .kp-review-crypto-line.loading { opacity: 0.4; }\n\n .kp-detail-block {\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n border-radius: 14px;\n overflow: hidden;\n margin-bottom: 10px;\n }\n\n .kp-detail-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 11px 16px;\n border-bottom: 1px solid var(--kp-border);\n }\n\n .kp-detail-row:last-child { border-bottom: none; }\n\n .kp-detail-key {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-muted);\n letter-spacing: 0.02em;\n font-weight: 400;\n }\n\n .kp-detail-val {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-text);\n font-weight: 500;\n text-align: right;\n }\n\n .kp-detail-val.accent { color: var(--kp-accent); }\n .kp-detail-val.green { color: var(--kp-green); }\n\n .kp-fee-block {\n background: rgba(16,185,129,0.04);\n border: 1px solid rgba(16,185,129,0.1);\n border-radius: 14px;\n overflow: hidden;\n margin-bottom: 10px;\n }\n\n .kp-fee-block .kp-detail-row { border-bottom-color: rgba(16,185,129,0.08); }\n\n .kp-fee-header {\n padding: 10px 16px;\n background: rgba(16,185,129,0.06);\n border-bottom: 1px solid rgba(16,185,129,0.1);\n display: flex; align-items: center; gap: 6px;\n }\n\n .kp-fee-header-text {\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-green);\n letter-spacing: 0.06em;\n text-transform: uppercase;\n font-weight: 500;\n }\n\n .kp-fee-header .material-symbols-outlined { font-size: 13px; color: var(--kp-green); }\n\n .tx-details {\n width: 100%;\n background: var(--kp-surface);\n border: 1px solid var(--kp-border);\n border-radius: 14px;\n overflow: hidden;\n margin-top: 16px;\n }\n\n .tx-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 10px 16px;\n border-bottom: 1px solid var(--kp-border);\n }\n\n .tx-row:last-child { border-bottom: none; }\n\n .tx-label { font-family: var(--kp-mono); color: var(--kp-muted); font-size: 10px; letter-spacing: 0.02em; font-weight: 400; }\n .tx-value { color: var(--kp-text); font-size: 11px; font-weight: 500; font-family: var(--kp-mono); }\n .tx-hash-row { display: flex; align-items: center; gap: 8px; }\n\n .explorer-link {\n display: flex; align-items: center; justify-content: center;\n width: 24px; height: 24px;\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 6px;\n cursor: pointer;\n transition: all 0.15s;\n flex-shrink: 0;\n }\n\n .explorer-link:hover { background: rgba(99,102,241,0.2); }\n .explorer-link .material-symbols-outlined { font-size: 12px; color: var(--kp-accent); }\n\n .mobile-instruction {\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 10px;\n padding: 12px;\n margin: 12px 0 0;\n display: flex;\n align-items: flex-start;\n gap: 10px;\n }\n\n .mobile-instruction-icon { color: var(--kp-accent); font-size: 18px; flex-shrink: 0; margin-top: 1px; }\n .mobile-instruction-text { flex: 1; }\n .mobile-instruction-title { color: var(--kp-text); font-size: 12px; font-weight: 600; margin-bottom: 3px; }\n .mobile-instruction-desc { color: var(--kp-muted); font-size: 11px; line-height: 1.5; font-weight: 400; }\n\n .kp-quote-timer {\n display: flex;\n align-items: center;\n gap: 5px;\n font-family: var(--kp-mono);\n font-size: 10px;\n color: var(--kp-muted);\n margin-top: 6px;\n font-weight: 400;\n }\n\n .kp-quote-timer .material-symbols-outlined { font-size: 12px; }\n .kp-quote-timer.urgent { color: #fb923c; }\n .kp-quote-timer.expired { color: var(--kp-red); }\n\n @media (max-width: 480px) {\n .kwespay-overlay {\n padding: 0;\n align-items: flex-end;\n background: rgba(0,0,0,0.6);\n }\n\n .kwespay-close-btn { top: 14px; right: 14px; }\n\n .kwespay-container {\n width: 100vw;\n max-width: 100vw;\n height: calc(100vh - 120px);\n max-height: calc(100vh - 120px);\n min-height: 60vh;\n border-radius: 20px 20px 0 0;\n animation: kpSheetUp 0.32s cubic-bezier(0.16, 1, 0.3, 1) forwards;\n border-bottom: none;\n }\n\n .kwespay-container.closing {\n animation: kpSheetDown 0.28s ease forwards;\n }\n\n .kwespay-container::before {\n content: '';\n display: block;\n position: absolute;\n top: 8px; left: 50%;\n transform: translateX(-50%);\n width: 28px; height: 3px;\n border-radius: 2px;\n background: rgba(255,255,255,0.12);\n z-index: 10;\n }\n }\n\n\n.kp-mobile-connect-status {\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--kp-accent-dim);\n border: 1px solid rgba(99,102,241,0.2);\n border-radius: 12px;\n padding: 14px 16px;\n margin-bottom: 4px;\n}\n\n.kp-mobile-status-icon {\n width: 28px; height: 28px;\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0;\n}\n\n.kp-mobile-status-text { flex: 1; }\n\n.kp-mobile-status-title {\n font-size: 13px;\n font-weight: 600;\n color: var(--kp-text);\n margin-bottom: 2px;\n}\n\n.kp-mobile-status-desc {\n font-family: var(--kp-mono);\n font-size: 11px;\n color: var(--kp-muted);\n}\n\n.kp-wallet-option:active {\n transform: scale(0.98);\n background: var(--kp-accent-dim);\n border-color: var(--kp-border-active);\n}\n\n\n @keyframes kpSheetUp {\n from { transform: translateY(100%); opacity: 0.8; }\n to { transform: translateY(0); opacity: 1; }\n }\n\n @keyframes kpSheetDown {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(100%); opacity: 0; }\n }\n",document.head.appendChild(e)}},_createWidgetDOM(){document.getElementById("kwespay-widget-overlay")?.remove();const e=document.createElement("div");e.className="kwespay-overlay",e.id="kwespay-widget-overlay";const t=document.createElement("button");t.className="kwespay-close-btn",t.innerHTML="×",t.onclick=()=>this.close(),e.appendChild(t);const n=document.createElement("div");var r,i;n.className="kwespay-container",n.id="kwespay-widget-container",n.innerHTML=(r=this.config.amount,i=this.config.currency,`\n <div class="step active" id="kwespay-step0">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="loading-container" style="flex:1">\n <div class="spinner-wrapper">\n <div class="spinner-ring"></div>\n <div class="spinner-ring-2"></div>\n <div class="spinner-icon">\n <span class="material-symbols-outlined">shield_lock</span>\n </div>\n </div>\n <h2 class="headline">Initializing</h2>\n <p class="body-text">Establishing a secure payment session.</p>\n </div>\n <div class="kp-footer">\n <span class="material-symbols-outlined kp-footer-lock" style="font-size:12px">lock</span>\n <span class="kp-footer-text">Powered by · <span>KwesPay</span></span>\n </div>\n </div>\n\n <div class="step" id="kwespay-step0-invalid">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot" style="background:var(--kp-red);box-shadow:none;animation:none"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="error-icon">\n <span class="material-symbols-outlined">wifi_off</span>\n </div>\n <h2 class="headline">Payment Unavailable</h2>\n <p class="body-text">We couldn't start your payment session. Please try again or contact the store for help.</p>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-retryInitBtn">Try Again</button>\n </div>\n </div>\n\n <div class="step" id="kwespay-step1">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="kp-amount-block">\n <div class="kp-amount-label">Total due</div>\n <div class="kp-amount-value" id="kwespay-paymentAmount">${r} ${i}</div>\n <div class="kp-amount-hint">Select a network to continue</div>\n </div>\n <div class="progress-section">\n <div class="progress-info">\n <span class="progress-step">01 / 03</span>\n <span class="progress-label">Select Network</span>\n </div>\n <div class="progress-bars">\n <div class="progress-bar active"></div>\n <div class="progress-bar"></div>\n <div class="progress-bar"></div>\n </div>\n </div>\n <div class="content-scroll">\n <p class="section-hint">Choose the blockchain network you want to pay on.</p>\n <div class="item-list" id="kwespay-mainnetList"></div>\n <div class="kp-testnet-section" id="kwespay-testnetSection" style="display:none">\n <div class="kp-section-divider">Testnets</div>\n <div class="item-list" id="kwespay-testnetList"></div>\n </div>\n </div>\n </div>\n\n <div class="step" id="kwespay-step2">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-back2">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="kp-amount-block">\n <div class="kp-amount-label">Total due</div>\n <div class="kp-amount-value">${r} ${i}</div>\n <div class="kp-amount-hint">Select a token — exact amount shown at review</div>\n </div>\n <div class="progress-section">\n <div class="progress-info">\n <span class="progress-step">02 / 03</span>\n <span class="progress-label">Select Token</span>\n </div>\n <div class="progress-bars">\n <div class="progress-bar active"></div>\n <div class="progress-bar active"></div>\n <div class="progress-bar"></div>\n </div>\n </div>\n <div class="network-status">\n <div class="status-card">\n <div class="status-icon" id="kwespay-selectedNetworkIcon"></div>\n <p class="status-text" id="kwespay-selectedNetworkName">—</p>\n <span class="material-symbols-outlined" style="color:var(--kp-accent);font-size:15px">check_circle</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:10px">\n <p class="section-hint">Select the token you want to pay with. The exact crypto amount will be confirmed on the next screen.</p>\n <div id="kwespay-tokenList"></div>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-continueToWalletConnect" disabled>Connect Wallet</button>\n </div>\n </div>\n\n <div class="step" id="kwespay-step3">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-back3">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n \n </div>\n <div class="progress-section">\n <div class="progress-info">\n <span class="progress-step">03 / 03</span>\n <span class="progress-label">Review & Pay</span>\n </div>\n <div class="progress-bars">\n <div class="progress-bar active"></div>\n <div class="progress-bar active"></div>\n <div class="progress-bar active"></div>\n </div>\n </div>\n <div class="kp-review-body">\n <div class="kp-review-amount">\n <div class="kp-review-fiat" id="kwespay-reviewFiatAmount">${r} ${i}</div>\n <div class="kp-review-crypto-line" id="kwespay-reviewCryptoLine">Fetching live quote…</div>\n <div class="kp-quote-timer" id="kwespay-quoteTimer" style="display:none;justify-content:center">\n <span class="material-symbols-outlined">schedule</span>\n <span id="kwespay-quoteTimerText">—</span>\n </div>\n </div>\n\n <div class="kp-detail-block">\n <div class="kp-detail-row">\n <span class="kp-detail-key">wallet</span>\n <span class="kp-detail-val" id="kwespay-connectedWalletAddress">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">network</span>\n <span class="kp-detail-val" id="kwespay-summaryNetwork">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">token</span>\n <span class="kp-detail-val accent" id="kwespay-summaryToken">—</span>\n </div>\n </div>\n\n <div class="kp-fee-block">\n <div class="kp-fee-header">\n <span class="material-symbols-outlined">receipt_long</span>\n <span class="kp-fee-header-text">Fee Breakdown</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">payment amount</span>\n <span class="kp-detail-val" id="kwespay-feePaymentAmount">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">platform fee (0.25%)</span>\n <span class="kp-detail-val" id="kwespay-feePlatformFee">—</span>\n </div>\n <div class="kp-detail-row">\n <span class="kp-detail-key">vendor receives</span>\n <span class="kp-detail-val green" id="kwespay-feeVendorAmount">—</span>\n </div>\n </div>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-proceedToPayment">Pay Now</button>\n <button class="action-btn secondary" style="margin-top:8px" id="kwespay-cancelConnection">Cancel</button>\n </div>\n </div>\n\n <div class="step" id="kwespay-step4">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">KwesPay Checkout</span>\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="spinner-wrapper">\n <div class="spinner-ring"></div>\n <div class="spinner-ring-2"></div>\n <div class="spinner-icon">\n <span class="material-symbols-outlined">payments</span>\n </div>\n </div>\n <h2 class="headline" id="kwespay-processingTitle">Processing Payment</h2>\n <p class="body-text" id="kwespay-processingText">Waiting for wallet confirmation.</p>\n <div class="mobile-instruction" id="kwespay-mobileTransactionInstruction" style="display:none">\n <span class="material-symbols-outlined mobile-instruction-icon">phone_iphone</span>\n <div class="mobile-instruction-text">\n <div class="mobile-instruction-title">Check Your Wallet App</div>\n <div class="mobile-instruction-desc">A confirmation request has been sent to your wallet. Tap Approve to complete the payment.</div>\n </div>\n </div>\n </div>\n </div>\n\n <div class="step" id="kwespay-step5">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot" style="background:var(--kp-green);box-shadow:0 0 8px rgba(16,185,129,0.4);animation:none"></div>\n <span class="kp-topbar-name">Payment Complete</span>\n </div>\n <div class="kp-topbar-secure">\n <span class="material-symbols-outlined" style="color:var(--kp-green)">check_circle</span>\n CONFIRMED\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="success-icon">\n <span class="material-symbols-outlined">check_circle</span>\n </div>\n <h2 class="headline">Payment Successful</h2>\n <p class="body-text">Your transaction has been confirmed on-chain.</p>\n <div class="tx-details">\n <div class="tx-row">\n <span class="tx-label">tx hash</span>\n <div class="tx-hash-row">\n <span class="tx-value" id="kwespay-txHash">—</span>\n <a class="explorer-link" id="kwespay-explorerLink" target="_blank" rel="noopener noreferrer">\n <span class="material-symbols-outlined">open_in_new</span>\n </a>\n </div>\n </div>\n <div class="tx-row">\n <span class="tx-label">amount paid</span>\n <span class="tx-value" id="kwespay-txFiatAmount">${r} ${i}</span>\n </div>\n <div class="tx-row">\n <span class="tx-label">crypto amount</span>\n <span class="tx-value" id="kwespay-txCryptoAmount">—</span>\n </div>\n <div class="tx-row">\n <span class="tx-label">network</span>\n <span class="tx-value" id="kwespay-txNetwork">—</span>\n </div>\n </div>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-closeSuccessBtn">Done</button>\n </div>\n <div class="kp-footer">\n <span class="material-symbols-outlined kp-footer-lock" style="font-size:12px">lock</span>\n <span class="kp-footer-text">Secured by <span>KwesPay</span> · On-chain verified</span>\n </div>\n </div>\n\n <div class="step" id="kwespay-step6">\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <div class="kp-topbar-dot" style="background:var(--kp-red);box-shadow:none;animation:none"></div>\n <span class="kp-topbar-name">Payment Failed</span>\n </div>\n </div>\n <div class="loading-container" style="flex:1">\n <div class="error-icon">\n <span class="material-symbols-outlined">error</span>\n </div>\n <h2 class="headline" id="kwespay-errorTitle">Something went wrong</h2>\n <p class="body-text" id="kwespay-errorMessage">An error occurred while processing your payment.</p>\n </div>\n <div class="bottom-action">\n <button class="action-btn" id="kwespay-retryPayment">Try Again</button>\n <button class="action-btn secondary" style="margin-top:8px" id="kwespay-backToStartBtn">Start Over</button>\n </div>\n </div>\n `),e.appendChild(n),document.body.appendChild(e),this._setupEventListeners(),this._setupSwipeToClose(n)},_setupSwipeToClose(e){let t=0,n=0,r=!1;e.addEventListener("touchstart",i=>{const s=i.touches[0];s.clientY-e.getBoundingClientRect().top<=40&&(t=s.clientY,n=s.clientY,r=!0,e.style.transition="none")},{passive:!0}),e.addEventListener("touchmove",i=>{if(!r)return;n=i.touches[0].clientY;const s=n-t;s>0&&(e.style.transform=`translateY(${s}px)`)},{passive:!0}),e.addEventListener("touchend",()=>{if(!r)return;r=!1,e.style.transition="";n-t>120?this.close():e.style.transform="translateY(0)"})},_setupEventListeners(){document.getElementById("kwespay-retryInitBtn")?.addEventListener("click",()=>this._validateAPIKey()),this._renderNetworkList(),document.getElementById("kwespay-back2")?.addEventListener("click",()=>{this.state.selectedToken=null,this.state.selectedTokenConfig=null;const e=document.getElementById("kwespay-continueToWalletConnect");e&&(e.disabled=!0),this._goToStep(1)}),document.getElementById("kwespay-back3")?.addEventListener("click",async()=>{await this.walletService.disconnect(),this._clearQuoteTimer(),this._goToStep(2)}),document.getElementById("kwespay-continueToWalletConnect")?.addEventListener("click",async()=>{await this._handleWalletConnection()}),document.getElementById("kwespay-proceedToPayment")?.addEventListener("click",async()=>{await this._handlePaymentProcessing()}),document.getElementById("kwespay-cancelConnection")?.addEventListener("click",async()=>{await this.walletService.disconnect(),this._clearQuoteTimer(),Tx("paymentCancelled",{reason:"user_cancelled_review"}),this._goToStep(1)}),document.getElementById("kwespay-retryPayment")?.addEventListener("click",async()=>{this.walletService.isConnected()?(await this._loadReviewStep(),this._goToStep(3)):await this._handleWalletConnection()}),document.getElementById("kwespay-closeSuccessBtn")?.addEventListener("click",()=>this.close()),document.getElementById("kwespay-backToStartBtn")?.addEventListener("click",()=>{Tx("paymentCancelled",{reason:"user_started_over"}),this._reset(),this._goToStep(1)});const e=document.getElementById("kwespay-networkSearch");e&&e.addEventListener("input",e=>{const t=e.target.value.toLowerCase();document.querySelectorAll(".kwespay-container .list-item").forEach(e=>{const n=e.querySelector(".item-name")?.textContent.toLowerCase();n&&(e.style.display=n.includes(t)?"flex":"none")})});const t=document.getElementById("kwespay-tokenSearch");t&&t.addEventListener("input",e=>{const t=e.target.value.toLowerCase();document.querySelectorAll("#kwespay-tokenList .token-item").forEach(e=>{const n=e.querySelector(".token-name")?.textContent.toLowerCase(),r=e.querySelector(".token-symbol")?.textContent.toLowerCase();n&&r&&(e.style.display=n.includes(t)||r.includes(t)?"flex":"none")})})}},Rx={_goToStep(e){document.querySelectorAll(".kwespay-container .step").forEach(e=>e.classList.remove("active","exiting")),this._activateStep(e),this.state.currentStep=e},_activateStep(e){let t;t=.5===e?document.getElementById("kwespay-step0-invalid"):"string"==typeof e?document.getElementById(`kwespay-step-${e}`):document.getElementById(`kwespay-step${e}`),t?t.classList.add("active"):console.warn(`[KwesPayWidget] Step not found: ${e}`)},_removeCustomStep(e){document.getElementById(e)?.remove()},_showError(e,t){const n=document.getElementById("kwespay-errorTitle"),r=document.getElementById("kwespay-errorMessage");n&&(n.textContent=e),r&&(r.textContent=t),this._goToStep(6)},_reset(){this._clearQuoteTimer(),this._removeCustomStep("kwespay-step-wallet-picker"),this._removeCustomStep("kwespay-step-wc"),this.state.selectedNetwork=null,this.state.selectedNetworkName="",this.state.selectedChainId=null,this.state.selectedRpcUrl=null,this.state.selectedContractAddress=null,this.state.selectedToken=null,this.state.selectedTokenConfig=null,this.state.currentPayload=null,this.state.wcUri=null}},Bx={async _validateAPIKey(){try{const e=await this.paymentService.validateAPIKey();e.valid?(this.state.vendorInfo=e.vendorInfo,this.state.keyAllowedNetworks=e.allowedNetworks??null,this.state.keyAllowedTokens=e.allowedTokens??null,this._goToStep(1),Tx("apiKeyValidated",{vendorInfo:this.state.vendorInfo})):(this._goToStep(.5),Tx("apiKeyInvalid",{}))}catch(e){console.error("[KwesPayWidget] API key validation error:",e.message),this._goToStep(.5),Tx("apiKeyError",{error:e.message})}}},Mx={_renderNetworkList(){const e=document.getElementById("kwespay-mainnetList"),t=document.getElementById("kwespay-testnetList"),n=document.getElementById("kwespay-testnetSection");if(!e||!t)return;e.innerHTML="",t.innerHTML="";const r=this.state.keyAllowedNetworks?new Set(this.state.keyAllowedNetworks.map(e=>e.toLowerCase())):null,o=this._effectiveAllowedTokens();let a=!1;Object.entries(i).forEach(([n,i])=>{if(r&&!r.has(n.toLowerCase()))return;if(o){const e=(s[n]||[]).map(e=>e.symbol.toUpperCase());if(!o.some(t=>e.includes(t)))return}const c=document.createElement("div");c.className="list-item",c.innerHTML=`\n <div class="item-icon"><img src="${i.logo}" alt="${i.name}" /></div>\n <div class="item-info">\n <div class="item-name-row">\n <p class="item-name">${i.name}</p>\n ${"testnet"===i.type?'<span class="item-badge badge-testnet">Testnet</span>':""}\n </div>\n <p class="item-desc">${"mainnet"===i.type?"Mainnet · Production":"Testnet · Development"}</p>\n </div>\n <span class="material-symbols-outlined item-chevron">chevron_right</span>\n `,c.addEventListener("click",()=>this._handleNetworkSelection(n,i)),"mainnet"===i.type?e.appendChild(c):(t.appendChild(c),a=!0)}),n&&(n.style.display=a?"block":"none")},_renderTokenList(){if(!this.state.selectedNetwork)return;const e=document.getElementById("kwespay-tokenList");if(!e)return;const t=this._effectiveAllowedTokens();let n=s[this.state.selectedNetwork]||[];t&&(n=n.filter(e=>t.includes(e.symbol.toUpperCase()))),e.innerHTML="",0!==n.length?n.forEach(t=>{const n=document.createElement("div");n.className="token-item",n.setAttribute("data-token-symbol",t.symbol),n.innerHTML=`\n <div class="token-left">\n <div class="token-icon"><img src="${t.icon}" alt="${t.symbol}" /></div>\n <div class="token-info">\n <p class="token-symbol">${t.symbol}</p>\n <p class="token-name">${t.name}</p>\n </div>\n </div>\n <span class="material-symbols-outlined token-chevron">chevron_right</span>\n `,n.addEventListener("click",()=>this._handleTokenSelection(t)),e.appendChild(n)}):e.innerHTML='<div style="text-align:center;padding:24px;font-family:var(--kp-mono);font-size:11px;color:var(--kp-muted)">No accepted tokens on this network.</div>'},_effectiveAllowedTokens(){const e=this.state.keyAllowedTokens?.map(e=>e.toUpperCase())??null,t=this.config.acceptedTokens;return e||t?e?t?e.filter(e=>t.includes(e)):e:t:null},async _handleNetworkSelection(e,t){this.state.selectedNetwork=e,this.state.selectedNetworkName=t.name,this.state.selectedChainId=t.chainId,this.state.selectedRpcUrl=t.rpcUrl,this.state.selectedContractAddress=t.contractAddress,this.state.selectedToken=null,this.state.selectedTokenConfig=null;const n=document.getElementById("kwespay-selectedNetworkName");n&&(n.textContent=`${t.name} ${"mainnet"===t.type?"Mainnet":"Testnet"}`);const r=document.getElementById("kwespay-selectedNetworkIcon");r&&(r.innerHTML=`<img src="${t.logo}" alt="${t.name}" />`);const i=document.getElementById("kwespay-continueToWalletConnect");i&&(i.disabled=!0),this._renderTokenList(),this._goToStep(2)},_handleTokenSelection(e){document.querySelectorAll("#kwespay-tokenList .token-item").forEach(e=>e.classList.remove("selected")),document.querySelector(`#kwespay-tokenList .token-item[data-token-symbol="${e.symbol}"]`)?.classList.add("selected"),this.state.selectedToken=e.symbol,this.state.selectedTokenConfig=e;const t=document.getElementById("kwespay-continueToWalletConnect");t&&(t.disabled=!1)}},Ux={async _handleWalletConnection(){this.state.selectedToken&&this.state.selectedTokenConfig?this._renderWalletPickerStep():alert("Please select a token first")},_renderWalletPickerStep(){this._removeCustomStep("kwespay-step-wallet-picker");const e=document.getElementById("kwespay-widget-container"),t=document.createElement("div");t.className="step",t.id="kwespay-step-wallet-picker",t.innerHTML=`\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-picker-back">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">Connect Wallet</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:16px">\n <p class="section-hint">Choose how to connect your wallet.</p>\n <div class="item-list" id="kwespay-injected-list">\n <div style="text-align:center;padding:12px;font-family:var(--kp-mono);font-size:11px;color:var(--kp-muted)">Detecting wallets…</div>\n </div>\n <div class="kp-section-divider" style="margin-top:20px">Or scan QR code</div>\n <div class="item-list" id="kwespay-wc-list">\n <div class="list-item" id="kwespay-wc-option" style="cursor:pointer">\n <div class="item-icon" style="background:transparent">\n <svg width="22" height="22" viewBox="0 0 22 22" fill="none">\n <path d="M4 4C7.3 1 14.7 1 18 4C18 4 15 7.5 11 7.5C7 7.5 4 4 4 4Z" fill="#3396FF"/>\n <path d="M4 4C4 4 6.5 9 11 9C15.5 9 18 4 18 4" stroke="#3396FF" stroke-width="1.5" fill="none"/>\n <path d="M7.5 10L9.5 14L11 11L12.5 14L14.5 10" stroke="#3396FF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </div>\n <div class="item-info">\n <div class="item-name-row"><p class="item-name">WalletConnect</p></div>\n <p class="item-desc">${_x()?"Open your mobile wallet":"Scan QR with any wallet"}</p>\n </div>\n <span class="material-symbols-outlined item-chevron">chevron_right</span>\n </div>\n </div>\n </div>\n `,e.appendChild(t),t.querySelector("#kwespay-picker-back")?.addEventListener("click",()=>{this._removeCustomStep("kwespay-step-wallet-picker"),this._goToStep(2)}),t.querySelector("#kwespay-wc-option")?.addEventListener("click",()=>{this._removeCustomStep("kwespay-step-wallet-picker"),this._startWalletConnect()}),this._goToStep("wallet-picker"),this.walletService.discoverInjectedWallets().then(e=>{const t=document.getElementById("kwespay-injected-list");t&&(t.innerHTML="",0!==e.length?e.forEach((e,n)=>{const r=e.info.icon?`<img src="${e.info.icon}" alt="${e.info.name}" style="width:22px;height:22px;object-fit:contain;border-radius:6px">`:'<span class="material-symbols-outlined" style="font-size:18px;color:var(--kp-accent)">account_balance_wallet</span>',i=document.createElement("div");i.className="list-item",i.style.cursor="pointer",i.innerHTML=`\n <div class="item-icon">${r}</div>\n <div class="item-info">\n <div class="item-name-row"><p class="item-name">${e.info.name}</p></div>\n <p class="item-desc">Browser extension</p>\n </div>\n <span class="material-symbols-outlined item-chevron">chevron_right</span>\n `,i.addEventListener("click",async()=>{this._removeCustomStep("kwespay-step-wallet-picker"),await this._connectInjectedProvider(n)}),t.appendChild(i)}):t.innerHTML='<div style="text-align:center;padding:12px;font-family:var(--kp-mono);font-size:11px;color:var(--kp-muted)">No browser wallet detected.</div>')})},async _connectInjectedProvider(e){try{const t=await this.walletService.connectInjected(e);await this._onWalletConnected(t)}catch(e){if("USER_CANCELLED"===e.code||4001===e.code)return;console.error("[KwesPayWidget] Injected connect error:",e.message),this._showError("Connection Failed",e.message||"Could not connect wallet."),Tx("walletConnectionError",{error:e.message})}},async _startWalletConnect(){this._renderWCStep();try{await this.walletService.initWalletConnect(e=>this._onWCUri(e),()=>this._onWCConnected(),()=>this._onWCDisconnected()),_x()&&this._renderWCMobileStep(),await this.walletService.connectWalletConnect(this.state.selectedChainId)}catch(e){if(e.message?.includes("User rejected")||e.message?.includes("cancelled"))return;console.error("[KwesPayWidget] WC connect error:",e.message),this._showError("Connection Failed",e.message||"WalletConnect failed.")}},_renderWCStep(){this._removeCustomStep("kwespay-step-wc");const e=document.getElementById("kwespay-widget-container"),t=document.createElement("div");t.className="step",t.id="kwespay-step-wc",t.innerHTML=_x()?this._wcMobileHTML():this._wcDesktopHTML(),e.appendChild(t),t.querySelector("#kwespay-wc-back")?.addEventListener("click",async()=>{await this.walletService.disconnect(),this._removeCustomStep("kwespay-step-wc"),this._renderWalletPickerStep()}),t.querySelector("#kwespay-wc-copy")?.addEventListener("click",()=>{if(this.state.wcUri){navigator.clipboard.writeText(this.state.wcUri).catch(()=>{});const e=document.getElementById("kwespay-wc-copy");e&&(e.textContent="Copied!"),setTimeout(()=>{e&&(e.textContent="Copy URI")},2e3)}}),this._goToStep("wc")},_wcDesktopHTML:()=>'\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-wc-back">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">Scan QR Code</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:16px;display:flex;flex-direction:column;align-items:center;gap:16px">\n <p class="section-hint" style="text-align:center">Open any WalletConnect-compatible wallet app and scan the code below.</p>\n <div id="kwespay-qr-canvas" style="width:220px;height:220px;background:white;border-radius:12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--kp-border)">\n <p style="font-size:11px;color:#888;font-family:var(--kp-mono)">Generating QR…</p>\n </div>\n <button class="action-btn secondary" id="kwespay-wc-copy" style="width:auto;padding:8px 20px;font-size:12px">Copy URI</button>\n <p style="font-size:11px;color:var(--kp-muted);font-family:var(--kp-mono);text-align:center">Waiting for wallet connection…</p>\n </div>\n ',_wcMobileHTML(){const e=this.walletService.getMobileWallets().map((e,t)=>`\n <div class="list-item kp-wallet-option" data-index="${t}" style="cursor:pointer">\n <div class="item-icon">\n <img src="${e.icon}" alt="${e.name}" style="width:22px;height:22px;object-fit:contain;border-radius:6px" onerror="this.style.display='none'">\n </div>\n <div class="item-info">\n <div class="item-name-row"><p class="item-name">${e.name}</p></div>\n <p class="item-desc">Tap to open and approve</p>\n </div>\n <span class="material-symbols-outlined item-chevron">open_in_new</span>\n </div>\n `).join("");return`\n <div class="kp-topbar">\n <div class="kp-topbar-brand">\n <button class="kp-back-btn" id="kwespay-wc-back">\n <span class="material-symbols-outlined">arrow_back</span>\n </button>\n <div class="kp-topbar-dot"></div>\n <span class="kp-topbar-name">Connect Wallet</span>\n </div>\n </div>\n <div class="content-scroll" style="padding-top:16px">\n <div class="kp-mobile-connect-status" id="kwespay-wc-status-card">\n <div class="kp-mobile-status-icon">\n <div class="spinner-ring" style="width:20px;height:20px;border-width:2px"></div>\n </div>\n <div class="kp-mobile-status-text">\n <p class="kp-mobile-status-title">Preparing connection</p>\n <p class="kp-mobile-status-desc" id="kwespay-wc-status">This only takes a moment…</p>\n </div>\n </div>\n <p class="section-hint" style="margin-top:16px">Choose your wallet app to connect.</p>\n <div class="item-list" id="kwespay-mobile-wallet-list">${e}</div>\n <p style="font-size:10px;color:var(--kp-muted);font-family:var(--kp-mono);text-align:center;margin-top:16px;line-height:1.6">\n After approving in your wallet, return here to complete payment.\n </p>\n </div>\n `},_renderWCMobileStep(){const e=document.getElementById("kwespay-mobile-wallet-list");e&&e.querySelectorAll(".kp-wallet-option").forEach(e=>{const t=parseInt(e.getAttribute("data-index"),10),n=this.walletService.getMobileWallets()[t];e.addEventListener("click",()=>{if(!this.state.wcUri){const e=document.getElementById("kwespay-wc-status");return void(e&&(e.textContent="Still connecting — please wait…"))}const e=n.universalLink(this.state.wcUri);this.walletService.isIOS()?window.location.href=e:window.open(e,"_blank","noreferrer noopener")})})},_onWCUri(e){if(this.state.wcUri=e,_x()){const e=document.getElementById("kwespay-wc-status"),t=document.querySelector(".kp-mobile-status-title"),n=document.querySelector(".kp-mobile-status-icon");e&&(e.textContent="Ready. Tap a wallet below to connect."),t&&(t.textContent="Connection ready"),n&&(n.innerHTML='<span class="material-symbols-outlined" style="font-size:18px;color:var(--kp-accent)">check_circle</span>')}else this._renderQRCode(e)},_renderQRCode(e){const t=document.getElementById("kwespay-qr-canvas");if(t){if("undefined"!=typeof QRCode)return t.innerHTML="",void new QRCode(t,{text:e,width:200,height:200,colorDark:"#000000",colorLight:"#ffffff",correctLevel:QRCode.CorrectLevel.M});if(void 0!==window.qrcode){const n=window.qrcode(0,"M");return n.addData(e),n.make(),void(t.innerHTML=n.createImgTag(3))}t.innerHTML=`\n <div style="display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px">\n <p style="font-size:10px;color:#888;font-family:monospace;word-break:break-all;text-align:center;max-width:180px">${e.slice(0,80)}…</p>\n <p style="font-size:10px;color:#888;font-family:monospace">Use Copy URI button</p>\n </div>\n `}},_onWCConnected(){const e=this.walletService._connectionResult();this._removeCustomStep("kwespay-step-wc"),this._onWalletConnected(e)},_onWCDisconnected(){this._removeCustomStep("kwespay-step-wc"),this._goToStep(2)},async _onWalletConnected(e){const t=document.getElementById("kwespay-connectedWalletAddress");t&&(t.textContent=e.shortAddress);const n=document.getElementById("kwespay-summaryNetwork");n&&(n.textContent=this.state.selectedNetworkName);const r=document.getElementById("kwespay-summaryToken");r&&(r.textContent=this.state.selectedToken);const i=document.getElementById("kwespay-reviewCryptoLine"),s=document.getElementById("kwespay-quoteTimer"),o=document.getElementById("kwespay-proceedToPayment");i&&(i.textContent="loading…",i.classList.add("loading")),s&&(s.style.display="none"),o&&(o.disabled=!0),this._goToStep(3);try{await this._loadReviewStep()}catch(e){console.error("[KwesPayWidget] Quote load failed after wallet connect:",e.message),i&&(i.textContent="Could not load rate — please try again.",i.classList.remove("loading"))}Tx("walletConnected",{address:e.address})}};function Lx(e,t){const n=BigInt(10**t),r=e/n,i=e%n;if(0n===i)return`${r}`;const s=i.toString().padStart(t,"0");if(r>0n){const e=s.slice(0,4).replace(/0+$/,"");return e?`${r}.${e}`:`${r}`}let o=-1;for(let e=0;e<s.length;e++)if("0"!==s[e]){o=e;break}if(-1===o)return`${r}`;const a=s.slice(o,o+4).replace(/0+$/,"");return`0.${s.slice(0,o)+a}`}const Dx={async _loadReviewStep(){this._clearQuoteTimer();const e=document.getElementById("kwespay-reviewCryptoLine"),t=document.getElementById("kwespay-quoteTimer"),n=document.getElementById("kwespay-feePaymentAmount"),r=document.getElementById("kwespay-feePlatformFee"),i=document.getElementById("kwespay-feeVendorAmount"),s=document.getElementById("kwespay-proceedToPayment");e&&(e.textContent="loading…",e.classList.add("loading")),t&&(t.style.display="none"),s&&(s.disabled=!0);try{const t=await this.paymentService.getQuote({vendorId:this.config.vendorId,cryptoCurrency:this.state.selectedToken,fiatAmount:this.config.amount,fiatCurrency:this.config.currency,network:this.state.selectedNetwork,payerWalletAddress:this.walletService.getAddress()});this.state.currentPayload=t;const o=this.state.selectedTokenConfig?.decimals??6,a=BigInt(t.amountBaseUnits),c=25*Number(a)/1e4,l=BigInt(Math.max(1,Math.round(c))),d=a-l,h=this.state.selectedToken,u=e=>`${Lx(e,o)} ${h}`;e&&(e.textContent=u(a),e.classList.remove("loading")),n&&(n.textContent=u(a)),r&&(r.textContent=u(l)),i&&(i.textContent=u(d<0n?0n:d)),s&&(s.disabled=!1),this._startQuoteTimer(t.expiresAt)}catch(t){console.error("[KwesPayWidget] Quote fetch failed:",t.message),e&&(e.textContent="Could not load please try again.",e.classList.remove("loading")),s&&(s.disabled=!0)}},_startQuoteTimer(e){const t=document.getElementById("kwespay-quoteTimer"),n=document.getElementById("kwespay-quoteTimerText");if(!t||!n)return;t.style.display="flex";const r=()=>{const r=Math.max(0,new Date(e).getTime()-Date.now()),i=Math.ceil(r/1e3),s=Math.floor(i/60),o=i%60;if(n.textContent=`Price locks in ${s}:${String(o).padStart(2,"0")}`,t.className="kp-quote-timer"+(i<=30?" urgent":"")+(i<=0?" expired":""),i<=0){n.textContent="Refreshing your rate…";const e=document.getElementById("kwespay-proceedToPayment");e&&(e.disabled=!0),this._clearQuoteTimer(),this._loadReviewStep()}};r(),this.state.quoteTimerInterval=setInterval(r,1e3)},_clearQuoteTimer(){this.state.quoteTimerInterval&&(clearInterval(this.state.quoteTimerInterval),this.state.quoteTimerInterval=null)}},jx={async _handlePaymentProcessing(){if(this.state.currentPayload)try{this._clearQuoteTimer(),this._goToStep(4);const e=(e,t)=>{const n=document.getElementById("kwespay-processingTitle"),r=document.getElementById("kwespay-processingText");n&&(n.textContent=e),r&&(r.textContent=t)},t="walletconnect"===this.walletService.connectionType,n=this.walletService.isMobile(),r=t&&n,s=this.walletService.getProvider(),o=this.state.selectedChainId;if(!s)throw new Error("No wallet provider");if(!await this.walletService.isSessionAlive()){console.error("[KwesPay] Session liveness check failed — session appears stale"),await this.walletService.disconnect();const e=new Error("Your wallet session expired. Please reconnect your wallet.");throw e.code="SESSION_EXPIRED",e}if(n&&document.getElementById("kwespay-mobileTransactionInstruction")?.style.setProperty("display","flex"),r)await this._assertMobileChain(s,o);else{const t=await s.request({method:"eth_chainId"}),n=parseInt(t,16);console.log("[KwesPay] Desktop chain check —",{currentChainId:n,targetChainId:o}),n!==o&&(e("Switching network…","Approve the network change in your wallet."),await this._switchNetworkSafe(o,this.state.selectedNetworkName,this.state.selectedRpcUrl,this.state.selectedToken,this.state.selectedTokenConfig.decimals),console.log("[KwesPay] Network switched"))}r?(e("Opening your wallet…","Approve the payment in your wallet."),this.walletService._openWalletForApproval(),await new Promise(e=>setTimeout(e,700))):e("Waiting for approval…","Confirm the transaction in your wallet.");const a=await this.paymentService.createPayment({payload:this.state.currentPayload,walletProvider:s,onStatusUpdate:e});document.getElementById("kwespay-mobileTransactionInstruction")?.style.setProperty("display","none");const c=this.state.selectedTokenConfig?.decimals??6,l=`${Lx(BigInt(this.state.currentPayload.amountBaseUnits),c)} ${this.state.selectedToken}`;document.getElementById("kwespay-txHash").textContent=function(e,t=10,n=8){return e?`${e.slice(0,t)}...${e.slice(-n)}`:""}(a.hash),document.getElementById("kwespay-txFiatAmount").textContent=`${this.config.amount} ${this.config.currency}`,document.getElementById("kwespay-txCryptoAmount").textContent=l,document.getElementById("kwespay-txNetwork").textContent=this.state.selectedNetworkName,document.getElementById("kwespay-explorerLink").href=i[this.state.selectedNetwork].explorer+a.hash,this._goToStep(5),Tx("paymentSuccess",{transactionReference:a.transactionReference,paymentIdBytes32:a.paymentIdBytes32,transactionHash:a.hash,fiatAmount:this.config.amount,currency:this.config.currency,token:this.state.selectedToken,network:this.state.selectedNetwork})}catch(e){console.error("[KwesPay] Payment error —",e.code??"UNKNOWN",":",e.message),document.getElementById("kwespay-mobileTransactionInstruction")?.style.setProperty("display","none");const t=Ox(e);let n="Payment Failed",r=function(e,t={}){const n=Ox(e);switch(console.error("[KwesPay] Payment error breakdown:",{errorType:n,message:e?.message,code:e?.code,data:e?.data,reason:e?.reason,stack:e?.stack,raw:e,context:t}),e?.data&&console.error("[KwesPay] Contract revert data:",e.data),e?.transaction&&console.error("[KwesPay] Failed tx details:",e.transaction),e?.receipt&&console.error("[KwesPay] Tx receipt:",e.receipt),n){case"USER_REJECTED":return"You cancelled the transaction in your wallet.";case"INSUFFICIENT_BALANCE":return`Not enough ${t.token||"funds"} to complete this payment.`;case"CONNECTION_REJECTED":return"Wallet connection was cancelled.";case"TIMEOUT":return"Connection timed out. Please try again.";default:return e?.reason||e?.message||"Something went wrong while processing your payment."}}(e,{token:this.state.selectedToken});"SESSION_EXPIRED"===e.code?(n="Session Expired",r=e.message):"WRONG_NETWORK"===e.code?(n="Wrong Network",r=e.message):"USER_REJECTED"===t?(n="Transaction Cancelled",r="You rejected the transaction in your wallet."):"INSUFFICIENT_BALANCE"===t&&(n="Insufficient Balance"),this._showError(n,r),Tx("paymentError",{error:r,errorType:t})}else this._showError("Payment Error","Something went wrong. Please go back and try again.")},async _assertMobileChain(e,t){for(let r=1;r<=3;r++){let i=null;try{const t=await e.request({method:"eth_chainId"});i=parseInt(t,16)}catch(n){console.error(`[KwesPay] eth_chainId RPC failed (attempt ${r}/3):`,n.message)}if(console.log(`[KwesPay] Chain check attempt ${r}/3 —`,{currentChainId:i,targetChainId:t}),i===t)return void console.log("[KwesPay] Chain confirmed ✅",i);r<3&&await new Promise(e=>setTimeout(e,1e3))}const n=new Error(`Please switch to ${this.state.selectedNetworkName} in your wallet and try again.`);throw n.code="WRONG_NETWORK",n},async _switchNetworkSafe(e,t,n,r,i){const s=this.walletService.switchNetwork,o=this.walletService.getProvider();if(!o)throw new Error("[WalletService] No provider connected");const a=e=>{if(null==e)return null;try{const t="string"==typeof e?e.startsWith("0x")?parseInt(e,16):parseInt(e,10):Number(e);return isNaN(t)?null:"0x"+t.toString(16)}catch{return null}},c=a(e);try{const e=a(await o.request({method:"eth_chainId"}));if(e&&e===c)return}catch(e){console.warn("[KwesPay] Could not read chainId before switch:",e.message)}try{await s(e,t,n,r,i)}catch(e){if(4001===e.code)throw e;console.warn("[KwesPay] switchNetwork threw (verifying anyway):",e.message)}const l=Date.now();for(;Date.now()-l<15e3;){await new Promise(e=>setTimeout(e,500));try{const e=a(await o.request({method:"eth_chainId"}));if(e&&e===c)return void console.log(`[KwesPay] Network switch confirmed after ${Date.now()-l}ms ✅`)}catch(e){console.warn("[KwesPay] Poll eth_chainId error:",e.message)}}throw new Error(`Could not confirm network switch to ${t} after 15s. Please switch manually in your wallet and try again.`)}};class zx{constructor(e){if(!e.apiKey)throw new Error("[KwesPayWidget] apiKey is required");if(!e.vendorId)throw new Error("[KwesPayWidget] vendorId is required");if(!e.amount||parseFloat(e.amount)<=0)throw new Error("[KwesPayWidget] Valid amount is required");var i;if(this.config={apiKey:e.apiKey,vendorId:e.vendorId,amount:parseFloat(e.amount),currency:e.currency||r.currency,graphqlEndpoint:r.graphqlEndpoint,acceptedTokens:(i=e.acceptedTokens,i?"stablecoins"===i?n:Array.isArray(i)&&i.length?i.map(e=>e.toUpperCase()):null:null)},!Object.values(t).includes(this.config.currency))throw new Error(`[KwesPayWidget] Unsupported currency: ${this.config.currency}`);this.walletService=new Px,this.paymentService=new Nx(this.config.apiKey,this.config.graphqlEndpoint),this.state={isOpen:!1,currentStep:0,selectedNetwork:null,selectedNetworkName:"",selectedChainId:null,selectedRpcUrl:null,selectedContractAddress:null,selectedToken:null,selectedTokenConfig:null,vendorInfo:null,keyAllowedNetworks:null,keyAllowedTokens:null,currentPayload:null,quoteTimerInterval:null,wcUri:null},this._init()}async open(){const e=document.getElementById("kwespay-widget-overlay"),t=document.getElementById("kwespay-widget-container");e&&t&&(t.classList.remove("closing"),e.classList.add("open"),document.body.classList.add("kwespay-open"),this.state.isOpen=!0,await this._validateAPIKey(),Tx("widgetOpened",{}))}close(){const e=document.getElementById("kwespay-widget-overlay"),t=document.getElementById("kwespay-widget-container");if(!e||!t)return;this._clearQuoteTimer();const n=5===this.state.currentStep;window.innerWidth<=480?(t.classList.add("closing"),setTimeout(()=>{t.classList.remove("closing"),e.classList.remove("open"),document.body.classList.remove("kwespay-open"),this.state.isOpen=!1,Tx("widgetClosed",{completedPayment:n})},300)):(e.classList.remove("open"),document.body.classList.remove("kwespay-open"),this.state.isOpen=!1,Tx("widgetClosed",{completedPayment:n}))}isOpen(){return this.state.isOpen}updateAmount(e,n){const r=parseFloat(e);isNaN(r)||r<=0||(this.config.amount=r,n&&Object.values(t).includes(n)&&(this.config.currency=n),document.querySelectorAll('[id*="paymentAmount"], [id*="summaryFiatAmount"], [id*="txFiatAmount"], [id*="reviewFiatAmount"]').forEach(e=>{e.textContent=`${this.config.amount} ${this.config.currency}`}),Tx("amountUpdated",{amount:this.config.amount,currency:this.config.currency}))}getState(){return{...this.state,config:{...this.config}}}destroy(){this._clearQuoteTimer(),document.body.classList.remove("kwespay-open"),this.walletService?.disconnect(),document.getElementById("kwespay-widget-overlay")?.remove(),document.getElementById("kwespay-widget-styles")?.remove(),this.state=null,this.config=null,this.walletService=null,this.paymentService=null,Tx("widgetDestroyed",{})}}Object.assign(zx.prototype,$x,Rx,Bx,Mx,Ux,Dx,jx);const Hx={isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase()},Vx={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"},Fx={caipNetworkIdToNumber:e=>e?Number(e.split(":")[1]):void 0,parseEvmChainId(e){return"string"==typeof e?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace:(e,t)=>e?.filter(e=>e.chainNamespace===t)||[],getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const n=e.find(e=>e.caipNetworkId===t);if(n)return n.name;const[r]=t.split(":");return Vx.CHAIN_NAME_MAP?.[r]||void 0}},qx=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var Wx=1e6,Zx=1e6,Kx="[big.js] ",Gx=Kx+"Invalid ",Yx=Gx+"decimal places",Jx=Gx+"rounding mode",Qx=Kx+"Division by zero",Xx={},eA=void 0,tA=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function nA(e,t,n,r){var i=e.c;if(n===eA&&(n=e.constructor.RM),0!==n&&1!==n&&2!==n&&3!==n)throw Error(Jx);if(t<1)r=3===n&&(r||!!i[0])||0===t&&(1===n&&i[0]>=5||2===n&&(i[0]>5||5===i[0]&&(r||i[1]!==eA))),i.length=1,r?(e.e=e.e-t+1,i[0]=1):i[0]=e.e=0;else if(t<i.length){if(r=1===n&&i[t]>=5||2===n&&(i[t]>5||5===i[t]&&(r||i[t+1]!==eA||1&i[t-1]))||3===n&&(r||!!i[0]),i.length=t,r)for(;++i[--t]>9;)if(i[t]=0,0===t){++e.e,i.unshift(1);break}for(t=i.length;!i[--t];)i.pop()}return e}function rA(e,t,n){var r=e.e,i=e.c.join(""),s=i.length;if(t)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>s)for(r-=s;r--;)i+="0";else r<s&&(i=i.slice(0,r)+"."+i.slice(r));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return e.s<0&&n?"-"+i:i}Xx.abs=function(){var e=new this.constructor(this);return e.s=1,e},Xx.cmp=function(e){var t,n=this,r=n.c,i=(e=new n.constructor(e)).c,s=n.s,o=e.s,a=n.e,c=e.e;if(!r[0]||!i[0])return r[0]?s:i[0]?-o:0;if(s!=o)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,s=-1;++s<o;)if(r[s]!=i[s])return r[s]>i[s]^t?1:-1;return a==c?0:a>c^t?1:-1},Xx.div=function(e){var t=this,n=t.constructor,r=t.c,i=(e=new n(e)).c,s=t.s==e.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>Wx)throw Error(Yx);if(!i[0])throw Error(Qx);if(!r[0])return e.s=s,e.c=[e.e=0],e;var a,c,l,d,h,u=i.slice(),p=a=i.length,f=r.length,g=r.slice(0,a),m=g.length,y=e,w=y.c=[],b=0,v=o+(y.e=t.e-e.e)+1;for(y.s=s,s=v<0?0:v,u.unshift(0);m++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(m=g.length))d=a>m?1:-1;else for(h=-1,d=0;++h<a;)if(i[h]!=g[h]){d=i[h]>g[h]?1:-1;break}if(!(d<0))break;for(c=m==a?i:u;m;){if(g[--m]<c[m]){for(h=m;h&&!g[--h];)g[h]=9;--g[h],g[m]+=10}g[m]-=c[m]}for(;!g[0];)g.shift()}w[b++]=d?l:++l,g[0]&&d?g[m]=r[p]||0:g=[r[p]]}while((p++<f||g[0]!==eA)&&s--);return w[0]||1==b||(w.shift(),y.e--,v--),b>v&&nA(y,v,n.RM,g[0]!==eA),y},Xx.eq=function(e){return 0===this.cmp(e)},Xx.gt=function(e){return this.cmp(e)>0},Xx.gte=function(e){return this.cmp(e)>-1},Xx.lt=function(e){return this.cmp(e)<0},Xx.lte=function(e){return this.cmp(e)<1},Xx.minus=Xx.sub=function(e){var t,n,r,i,s=this,o=s.constructor,a=s.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,s.plus(e);var l=s.c.slice(),d=s.e,h=e.c,u=e.e;if(!l[0]||!h[0])return h[0]?e.s=-c:l[0]?e=new o(s):e.s=1,e;if(a=d-u){for((i=a<0)?(a=-a,r=l):(u=d,r=h),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((i=l.length<h.length)?l:h).length,a=c=0;c<n;c++)if(l[c]!=h[c]){i=l[c]<h[c];break}if(i&&(r=l,l=h,h=r,e.s=-e.s),(c=(n=h.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;n>a;){if(l[--n]<h[n]){for(t=n;t&&!l[--t];)l[t]=9;--l[t],l[n]+=10}l[n]-=h[n]}for(;0===l[--c];)l.pop();for(;0===l[0];)l.shift(),--u;return l[0]||(e.s=1,l=[u=0]),e.c=l,e.e=u,e},Xx.mod=function(e){var t,n=this,r=n.constructor,i=n.s,s=(e=new r(e)).s;if(!e.c[0])throw Error(Qx);return n.s=e.s=1,t=1==e.cmp(n),n.s=i,e.s=s,t?new r(n):(i=r.DP,s=r.RM,r.DP=r.RM=0,n=n.div(e),r.DP=i,r.RM=s,this.minus(n.times(e)))},Xx.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},Xx.plus=Xx.add=function(e){var t,n,r,i=this,s=i.constructor;if(e=new s(e),i.s!=e.s)return e.s=-e.s,i.minus(e);var o=i.e,a=i.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new s(i):e.s=i.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,r=l):(t=-t,r=a),r.reverse();t--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),t=l.length,n=0;t;a[t]%=10)n=(a[--t]=a[t]+l[t]+n)/10|0;for(n&&(a.unshift(n),++c),t=a.length;0===a[--t];)a.pop();return e.c=a,e.e=c,e},Xx.pow=function(e){var t=this,n=new t.constructor("1"),r=n,i=e<0;if(e!==~~e||e<-1e6||e>Zx)throw Error(Gx+"exponent");for(i&&(e=-e);1&e&&(r=r.times(t)),e>>=1;)t=t.times(t);return i?n.div(r):r},Xx.prec=function(e,t){if(e!==~~e||e<1||e>Wx)throw Error(Gx+"precision");return nA(new this.constructor(this),e,t)},Xx.round=function(e,t){if(e===eA)e=0;else if(e!==~~e||e<-Wx||e>Wx)throw Error(Yx);return nA(new this.constructor(this),e+this.e+1,t)},Xx.sqrt=function(){var e,t,n,r=this,i=r.constructor,s=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(s<0)throw Error(Kx+"No square root");0===(s=Math.sqrt(+rA(r,!0,!0)))||s===1/0?((t=r.c.join("")).length+o&1||(t+="0"),o=((o+1)/2|0)-(o<0||1&o),e=new i(((s=Math.sqrt(t))==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):e=new i(s+""),o=e.e+(i.DP+=4);do{n=e,e=a.times(n.plus(r.div(n)))}while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return nA(e,(i.DP-=4)+e.e+1,i.RM)},Xx.times=Xx.mul=function(e){var t,n=this,r=n.constructor,i=n.c,s=(e=new r(e)).c,o=i.length,a=s.length,c=n.e,l=e.e;if(e.s=n.s==e.s?1:-1,!i[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=i,i=s,s=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+s[c]*i[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},Xx.toExponential=function(e,t){var n=this,r=n.c[0];if(e!==eA){if(e!==~~e||e<0||e>Wx)throw Error(Yx);for(n=nA(new n.constructor(n),++e,t);n.c.length<e;)n.c.push(0)}return rA(n,!0,!!r)},Xx.toFixed=function(e,t){var n=this,r=n.c[0];if(e!==eA){if(e!==~~e||e<0||e>Wx)throw Error(Yx);for(e=e+(n=nA(new n.constructor(n),e+n.e+1,t)).e+1;n.c.length<e;)n.c.push(0)}return rA(n,!1,!!r)},Xx[Symbol.for("nodejs.util.inspect.custom")]=Xx.toJSON=Xx.toString=function(){var e=this,t=e.constructor;return rA(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},Xx.toNumber=function(){var e=+rA(this,!0,!0);if(!0===this.constructor.strict&&!this.eq(e.toString()))throw Error(Kx+"Imprecise conversion");return e},Xx.toPrecision=function(e,t){var n=this,r=n.constructor,i=n.c[0];if(e!==eA){if(e!==~~e||e<1||e>Wx)throw Error(Gx+"precision");for(n=nA(new r(n),e,t);n.c.length<e;)n.c.push(0)}return rA(n,e<=n.e||n.e<=r.NE||n.e>=r.PE,!!i)},Xx.valueOf=function(){var e=this,t=e.constructor;if(!0===t.strict)throw Error(Kx+"valueOf disallowed");return rA(e,e.e<=t.NE||e.e>=t.PE,!0)};var iA=function e(){function t(n){var r=this;if(!(r instanceof t))return n===eA?e():new t(n);if(n instanceof t)r.s=n.s,r.e=n.e,r.c=n.c.slice();else{if("string"!=typeof n){if(!0===t.strict&&"bigint"!=typeof n)throw TypeError(Gx+"value");n=0===n&&1/n<0?"-0":String(n)}!function(e,t){var n,r,i;if(!tA.test(t))throw Error(Gx+"number");e.s="-"==t.charAt(0)?(t=t.slice(1),-1):1,(n=t.indexOf("."))>-1&&(t=t.replace(".",""));(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length);for(i=t.length,r=0;r<i&&"0"==t.charAt(r);)++r;if(r==i)e.c=[e.e=0];else{for(;i>0&&"0"==t.charAt(--i););for(e.e=n-r-1,e.c=[],n=0;r<=i;)e.c[n++]=+t.charAt(r++)}}(r,n)}r.constructor=t}return t.prototype=Xx,t.DP=20,t.RM=1,t.NE=-7,t.PE=21,t.strict=false,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}();const sA={bigNumber(e,t={safe:!1}){try{return new iA(e?e:0)}catch(e){if(t.safe)return new iA(0);throw e}},formatNumber(e,t){const{decimals:n,round:r=8,safe:i=!0}=t;return sA.bigNumber(e,{safe:i}).div(new iA(10).pow(n)).round(r)},multiply(e,t){if(void 0===e||void 0===t)return new iA(0);const n=new iA(e),r=new iA(t);return n.times(r)},toFixed:(e,t=2)=>void 0===e||""===e?new iA(0).toFixed(t):new iA(e).toFixed(t),formatNumberToLocalString:(e,t=2)=>void 0===e||""===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}),parseLocalStringToNumber(e){if(void 0===e||""===e)return 0;const t=e.replace(/,/gu,"");return new iA(t).toNumber()}},oA=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],aA=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],cA=e=>Vx.USDT_CONTRACT_ADDRESSES.includes(e)?aA:oA,lA={ConnectorExplorerIds:{[Vx.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Vx.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Vx.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Vx.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[Vx.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[Vx.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Vx.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Vx.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Vx.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Vx.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Vx.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Vx.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Vx.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Vx.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Vx.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Vx.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Vx.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Vx.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Vx.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"}},dA={validateCaipAddress(e){if(3!==e.split(":")?.length)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(3!==t.length)throw new Error(`Invalid CAIP-10 address: ${e}`);const[n,r,i]=t;if(!n||!r||!i)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:n,chainId:r,address:i}},parseCaipNetworkId(e){const t=e.split(":");if(2!==t.length)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[n,r]=t;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:n,chainId:r}}},hA={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if("object"==typeof e&&null!==e){const t=e,n="string"==typeof t.message,r="number"==typeof t.code;return n&&r}return!1}catch{return!1}},isUserRejectedMessage:e=>e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled"),isUserRejectedRequestError(e){if(hA.isRpcProviderError(e)){const t=e.code===hA.RPC_ERROR_CODE.USER_REJECTED_REQUEST,n=e.code===hA.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||n||hA.isUserRejectedMessage(e.message)}return e instanceof Error&&hA.isUserRejectedMessage(e.message)}};let uA=class extends Error{constructor(e,t){super(t.message,{cause:e}),this.name=hA.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=t.code}},pA=class extends uA{constructor(e){super(e,{code:hA.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=hA.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}};const fA="@appkit/active_caip_network_id",gA="@appkit/connected_social",mA="@appkit-wallet/SOCIAL_USERNAME",yA="@appkit/recent_wallets",wA="@appkit/recent_wallet",bA="WALLETCONNECT_DEEPLINK_CHOICE",vA="@appkit/active_namespace",EA="@appkit/connected_namespaces",xA="@appkit/connection_status",AA="@appkit/siwx-auth-token",kA="@appkit/siwx-nonce-token",IA="@appkit/social_provider",CA="@appkit/native_balance_cache",SA="@appkit/portfolio_cache",PA="@appkit/ens_cache",NA="@appkit/identity_cache",_A="@appkit/preferred_account_types",TA="@appkit/connections",OA="@appkit/disconnected_connector_ids",$A="@appkit/history_transactions_cache",RA="@appkit/token_price_cache",BA="@appkit/latest_version",MA="@appkit/ton_wallets_cache";function UA(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const LA={setItem(e,t){DA()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(DA())return localStorage.getItem(e)||void 0},removeItem(e){DA()&&localStorage.removeItem(e)},clear(){DA()&&localStorage.clear()}};function DA(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}function jA(e,t){const n=e?.["--apkt-accent"]??e?.["--w3m-accent"];return"light"===t?{"--w3m-accent":n||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":n||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const zA=Symbol(),HA=Object.getPrototypeOf,VA=new WeakMap,FA=e=>(e=>e&&(VA.has(e)?VA.get(e):HA(e)===Object.prototype||HA(e)===Array.prototype))(e)&&e[zA]||null,qA=(e,t=!0)=>{VA.set(e,t)},WA=e=>"object"==typeof e&&null!==e,ZA=(e,t)=>{const n=YA.get(e);if((null==n?void 0:n[0])===t)return n[1];const r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return qA(r,!0),YA.set(e,[t,r]),Reflect.ownKeys(e).forEach(t=>{if(Object.getOwnPropertyDescriptor(r,t))return;const n=Reflect.get(e,t),{enumerable:i}=Reflect.getOwnPropertyDescriptor(e,t),s={value:n,enumerable:i,configurable:!0};if(GA.has(n))qA(n,!1);else if(KA.has(n)){const[e,t]=KA.get(n);s.value=ZA(e,t())}Object.defineProperty(r,t,s)}),Object.preventExtensions(r)},KA=new WeakMap,GA=new WeakSet,YA=new WeakMap,JA=[1],QA=new WeakMap;let XA=Object.is,ek=(e,t)=>new Proxy(e,t),tk=e=>WA(e)&&!GA.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),nk=ZA,rk=(e,t,n,r)=>({deleteProperty(e,t){const i=Reflect.get(e,t);n(t);const s=Reflect.deleteProperty(e,t);return s&&r(["delete",[t],i]),s},set(i,s,o,a){const c=!e()&&Reflect.has(i,s),l=Reflect.get(i,s,a);if(c&&(XA(l,o)||QA.has(o)&&XA(l,QA.get(o))))return!0;n(s),WA(o)&&(o=FA(o)||o);const d=!KA.has(o)&&tk(o)?ik(o):o;return t(s,d),Reflect.set(i,s,d,a),r(["set",[s],o,l]),!0}});function ik(e={}){if(!WA(e))throw new Error("object required");const t=QA.get(e);if(t)return t;let n=JA[0];const r=new Set,i=(e,t=++JA[0])=>{n!==t&&(s=n=t,r.forEach(n=>n(e,t)))};let s=n;const o=e=>(t,n)=>{const r=[...t];r[1]=[e,...r[1]],i(r,n)},a=new Map;let c=!0;const l=rk(()=>c,(e,t)=>{const n=!GA.has(t)&&KA.get(t);if(n){if(a.has(e))throw new Error("prop listener already exists");if(r.size){const t=n[2](o(e));a.set(e,[n,t])}else a.set(e,[n])}},e=>{var t;const n=a.get(e);n&&(a.delete(e),null==(t=n[1])||t.call(n))},i),d=ek(e,l);QA.set(e,d);const h=[e,(e=JA[0])=>(s!==e&&(s=e,a.forEach(([t])=>{const r=t[1](e);r>n&&(n=r)})),n),e=>{r.add(e),1===r.size&&a.forEach(([e,t],n)=>{if(t)throw new Error("remove already exists");const r=e[2](o(n));a.set(n,[e,r])});return()=>{r.delete(e),0===r.size&&a.forEach(([e,t],n)=>{t&&(t(),a.set(n,[e]))})}}];return KA.set(d,h),Reflect.ownKeys(e).forEach(t=>{const n=Object.getOwnPropertyDescriptor(e,t);"value"in n&&n.writable&&(d[t]=e[t])}),c=!1,d}function sk(e,t,n){const r=KA.get(e);let i;r||console.warn("Please use proxy object");const s=[],o=r[2];let a=!1;const c=o(e=>{s.push(e),i||(i=Promise.resolve().then(()=>{i=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,c()}}function ok(e){const t=KA.get(e);t||console.warn("Please use proxy object");const[n,r]=t;return nk(n,r())}function ak(e){return GA.add(e),e}function ck(e,t,n,r){let i=e[t];return sk(e,()=>{const r=e[t];Object.is(i,r)||n(i=r)})}const{proxyStateMap:lk,snapCache:dk}={proxyStateMap:KA,refSet:GA,snapCache:YA,versionHolder:JA,proxyCache:QA},hk=e=>lk.has(e);const uk=("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",pk=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],fk={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:uk,SECURE_SITE_DASHBOARD:`${uk}/dashboard`,SECURE_SITE_FAVICON:`${uk}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD₮0"]},BALANCE_SUPPORTED_CHAINS:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[Vx.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[Vx.CHAIN.EVM,Vx.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[lA.ConnectorExplorerIds[Vx.CONNECTOR_ID.COINBASE],lA.ConnectorExplorerIds[Vx.CONNECTOR_ID.COINBASE_SDK],lA.ConnectorExplorerIds[Vx.CONNECTOR_ID.BASE_ACCOUNT],lA.ConnectorExplorerIds[Vx.SOLFLARE_CONNECTOR_NAME],lA.ConnectorExplorerIds[Vx.PHANTOM_CONNECTOR_NAME],lA.ConnectorExplorerIds[Vx.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},gk={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=gk.getActiveNamespace(),t=gk.getActiveCaipNetworkId(),n=t?t.split(":")[1]:void 0;return{namespace:e,caipNetworkId:t,chainId:n?isNaN(Number(n))?n:Number(n):void 0}},setWalletConnectDeepLink({name:e,href:t}){try{LA.setItem(bA,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=LA.getItem(bA);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{LA.removeItem(bA)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{LA.setItem(vA,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{LA.setItem(fA,e),gk.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return LA.getItem(fA)}catch{return void console.info("Unable to get active caip network id")}},deleteActiveCaipNetworkId(){try{LA.removeItem(fA)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=UA(e);LA.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=gk.getRecentWallets(),n=t.find(t=>t.id===e.id);n||(t.unshift(e),t.length>2&&t.pop(),LA.setItem(yA,JSON.stringify(t)),LA.setItem(wA,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=LA.getItem(yA);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=LA.getItem(wA);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{LA.removeItem(wA)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const n=UA(e);LA.setItem(n,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return LA.getItem(vA)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=UA(e);return LA.getItem(t)}catch(t){console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{LA.setItem(gA,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return LA.getItem(gA)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{LA.removeItem(gA)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return LA.getItem(mA)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){const e=LA.getItem(fA),t=e?.split(":")?.[1];return t},setConnectionStatus(e){try{LA.setItem(xA,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return LA.getItem(xA)}catch{return}},getConnectedNamespaces(){try{const e=LA.getItem(EA);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));LA.setItem(EA,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=gk.getConnectedNamespaces();t.includes(e)||(t.push(e),gk.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=gk.getConnectedNamespaces(),n=t.indexOf(e);n>-1&&(t.splice(n,1),gk.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return LA.getItem(IA)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{LA.setItem(IA,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{LA.removeItem(IA)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=LA.getItem(SA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=gk.getBalanceCache();LA.setItem(SA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const t=gk.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;gk.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=gk.getBalanceCache();t[e.caipAddress]=e,LA.setItem(SA,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=LA.getItem(CA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=gk.getBalanceCache();LA.setItem(CA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const t=gk.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",e),gk.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=gk.getNativeBalanceCache();t[e.caipAddress]=e,LA.setItem(CA,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=LA.getItem(PA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const t=gk.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;gk.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=gk.getEnsCache();t[e.address]=e,LA.setItem(PA,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=gk.getEnsCache();LA.setItem(PA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=LA.getItem(NA);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const t=gk.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;gk.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=gk.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},LA.setItem(NA,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=gk.getIdentityCache();LA.setItem(NA,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{const e=LA.getItem(MA),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;gk.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{const t=gk.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=(new Date).getTime(),t.wallets=e,LA.setItem(MA,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{LA.removeItem(MA)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{LA.removeItem(SA),LA.removeItem(CA),LA.removeItem(PA),LA.removeItem(NA),LA.removeItem($A)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{LA.setItem(_A,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=LA.getItem(_A);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const n=gk.getConnections(),r=n[t]??[],i=new Map;for(const e of r)i.set(e.connectorId,{...e});for(const t of e){const e=i.get(t.connectorId),n=t.connectorId===Vx.CONNECTOR_ID.AUTH;if(e&&!n){const n=new Set(e.accounts.map(e=>e.address.toLowerCase())),r=t.accounts.filter(e=>!n.has(e.address.toLowerCase()));e.accounts.push(...r)}else i.set(t.connectorId,{...t})}const s={...n,[t]:Array.from(i.values())};LA.setItem(TA,JSON.stringify(s))}catch(e){console.error("Unable to sync connections to storage",e)}},getConnections(){try{const e=LA.getItem(TA);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:n}){try{const r=gk.getConnections(),i=r[n]??[],s=new Map(i.map(e=>[e.connectorId,e])),o=s.get(e);if(o){0===o.accounts.filter(e=>e.address.toLowerCase()!==t.toLowerCase()).length?s.delete(e):s.set(e,{...o,accounts:o.accounts.filter(e=>e.address.toLowerCase()!==t.toLowerCase())})}LA.setItem(TA,JSON.stringify({...r,[n]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const e=LA.getItem(OA);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const n=gk.getDisconnectedConnectorIds(),r=n[t]??[];r.push(e),LA.setItem(OA,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{const n=gk.getDisconnectedConnectorIds();let r=n[t]??[];r=r.filter(t=>t.toLowerCase()!==e.toLowerCase()),LA.setItem(OA,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{const n=gk.getDisconnectedConnectorIds();return(n[t]??[]).some(t=>t.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{const e=LA.getItem($A);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{const n=gk.getTransactionsCache(),r=n[e]?.[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;gk.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:n,transactions:r}){try{const i=gk.getTransactionsCache();i[e]={...i[e],[t]:{timestamp:n,transactions:r}},LA.setItem($A,JSON.stringify(i))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:n,transactions:r})}},removeTransactionsCache({address:e,chainId:t}){try{const n=gk.getTransactionsCache(),r=n?.[e]||{},{[t]:i,...s}=r;LA.setItem($A,JSON.stringify({...n,[e]:s}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=LA.getItem(RA);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const t=gk.getTokenPriceCache()[e.join(",")];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tokenPrice))return t.tokenPrice;gk.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=gk.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},LA.setItem(RA,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=gk.getTokenPriceCache();LA.setItem(RA,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{const e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const e=LA.getItem(BA);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=gk.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,LA.setItem(BA,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},mk={getWindow(){if("undefined"!=typeof window)return window},isMobile(){return!!this.isClient()&&Boolean(window?.matchMedia&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent))},checkCaipNetwork:(e,t="")=>e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase()),isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return mk.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){if(!this.isClient())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("safari")},isClient:()=>"undefined"!=typeof window,isPairingExpired:e=>!e||e-Date.now()<=fk.TEN_SEC_MS,isAllowedRetry:(e,t=fk.ONE_SEC_MS)=>Date.now()-e>=t,copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch(e){return!1}},isSafeApp(){if(mk.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const n=new URL(e),r=new URL(t);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry:()=>Date.now()+fk.FOUR_MINUTES_MS,getNetworkId:e=>e?.split(":")[1],getPlainAddress:e=>e?.split(":")[2],wait:async e=>new Promise(t=>{setTimeout(t,e)}),debounce(e,t=500){let n;return(...r)=>{n&&clearTimeout(n),n=setTimeout(function(){e(...r)},t)}},isHttpUrl:e=>e.startsWith("http://")||e.startsWith("https://"),formatNativeUrl(e,t,n=null){if(mk.isHttpUrl(e))return this.formatUniversalUrl(e,t);let r=e,i=n;r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const s=encodeURIComponent(t);return{redirect:`${r}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:r}},formatUniversalUrl(e,t){if(!mk.isHttpUrl(e))return this.formatNativeUrl(e,t);let n=e;n.endsWith("/")||(n=`${n}/`);return{redirect:`${n}wc?uri=${encodeURIComponent(t)}`,href:n}},getOpenTargetForPlatform(e){return"popupWindow"===e?e:this.isTelegram()?gk.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,n){window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},returnOpenHref(e,t,n){return window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},isTelegram:()=>"undefined"!=typeof window&&(Boolean(window.TelegramWebviewProxy)||Boolean(window.Telegram)||Boolean(window.TelegramWebviewProxyProto)),isPWA(){if("undefined"==typeof window)return!1;const e=!(!window?.matchMedia||"function"!=typeof window.matchMedia)&&window.matchMedia("(display-mode: standalone)")?.matches,t=window?.navigator?.standalone;return Boolean(e||t)},async preloadImage(e){const t=new Promise((t,n)=>{const r=new Image;r.onload=t,r.onerror=n,r.crossOrigin="anonymous",r.src=e});return Promise.race([t,mk.wait(2e3)])},parseBalance(e,t){let n="0.000";if("string"==typeof e){const t=Number(e);if(!isNaN(t)){const e=(Math.floor(1e3*t)/1e3).toFixed(3);e&&(n=e)}}const[r,i]=n.split("."),s=r||"0",o=i||"000";return{formattedText:`${s}.${o}${t?` ${t}`:""}`,value:s,decimals:o,symbol:t}},getApiUrl:()=>Vx.W3M_API_URL,getBlockchainApiUrl:()=>Vx.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>Vx.PULSE_API_URL,getUUID:()=>crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),parseError:e=>"string"==typeof e?e:"string"==typeof e?.issues?.[0]?.message?e.issues[0].message:e instanceof Error?e.message:"Unknown error",sortRequestedNetworks(e,t=[]){const n={};return t&&e&&(e.forEach((e,t)=>{n[e]=t}),t.sort((e,t)=>{const r=n[e.id],i=n[t.id];return void 0!==r&&void 0!==i?r-i:void 0!==r?-1:void 0!==i?1:0})),t},calculateBalance(e){let t=0;for(const n of e)t+=n.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[n,r]=t.split(".");return{dollars:n,pennies:r}},isAddress(e,t="eip155"){switch(t){case"eip155":return!!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!(!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!/^(?:0x)?[0-9A-F]{40}$/iu.test(e));case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);case"bip122":{const t=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),n=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),r=/^bc1[a-z0-9]{39,87}$/u.test(e),i=/^bc1p[a-z0-9]{58}$/u.test(e);return t||n||r||i}default:return!1}},uniqueBy(e,t){const n=new Set;return e.filter(e=>{const r=e[t];return!n.has(r)&&(n.add(r),!0)})},generateSdkVersion:(e,t,n)=>`${t}-${0===e.length?fk.ADAPTER_TYPES.UNIVERSAL:e.map(e=>e.adapterType).join(",")}-${n}`,createAccount:(e,t,n,r,i)=>({namespace:e,address:t,type:n,publicKey:r,path:i}),isCaipAddress(e){if("string"!=typeof e)return!1;const t=e.split(":"),n=t[0];return 3===t.filter(Boolean).length&&n in Vx.CHAIN_NAME_MAP},getAccount:e=>e?"string"==typeof e?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,n="state=";if("auth.magic.link"===new URL(e).host){const r="provider_authorization_url=",i=e.substring(e.indexOf(r)+r.length),s=this.injectIntoUrl(decodeURIComponent(i),n,t);return e.replace(i,encodeURIComponent(s))}return this.injectIntoUrl(e,n,t)},injectIntoUrl(e,t,n){const r=e.indexOf(t);if(-1===r)throw new Error(`${t} parameter not found in the URL: ${e}`);const i=e.indexOf("&",r),s=t.length,o=-1!==i?i:e.length;return e.substring(0,r+s)+(e.substring(r+s,o)+n)+e.substring(i)},isNumber:e=>("number"==typeof e||"string"==typeof e)&&!isNaN(Number(e))};"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const yk="@appkit-wallet/",wk="SMART_ACCOUNT_ENABLED_NETWORKS",bk={EOA:"eoa",SMART_ACCOUNT:"smartAccount"},vk={set(e,t){Ek.isClient&&localStorage.setItem(`${yk}${e}`,t)},get:e=>Ek.isClient?localStorage.getItem(`${yk}${e}`):null,delete(e,t){Ek.isClient&&(t?localStorage.removeItem(e):localStorage.removeItem(`${yk}${e}`))}},Ek={isClient:"undefined"!=typeof window};let xk=class e extends Error{constructor(t,n={}){const r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath;super([t||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...r?[`Details: ${r}`]:[],"Version: abitype@1.2.3"].join("\n")),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,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),n.cause&&(this.cause=n.cause),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.shortMessage=t}};function Ak(e,t){const n=e.exec(t);return n?.groups}const kk=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Ik=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Ck=/^\(.+?\).*?$/,Sk=/^tuple(?<array>(\[(\d*)\])*)$/;function Pk(e){let t=e.type;if(Sk.test(e.type)&&"components"in e){t="(";const n=e.components.length;for(let r=0;r<n;r++){t+=Pk(e.components[r]),r<n-1&&(t+=", ")}const r=Ak(Sk,e.type);return t+=`)${r?.array||""}`,Pk({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function Nk(e){let t="";const n=e.length;for(let r=0;r<n;r++){t+=Pk(e[r]),r!==n-1&&(t+=", ")}return t}function _k(e){return"function"===e.type?`function ${e.name}(${Nk(e.inputs)})${e.stateMutability&&"nonpayable"!==e.stateMutability?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Nk(e.outputs)})`:""}`:"event"===e.type?`event ${e.name}(${Nk(e.inputs)})`:"error"===e.type?`error ${e.name}(${Nk(e.inputs)})`:"constructor"===e.type?`constructor(${Nk(e.inputs)})${"payable"===e.stateMutability?" payable":""}`:"fallback"===e.type?"fallback() external"+("payable"===e.stateMutability?" payable":""):"receive() external payable"}const Tk=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;const Ok=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;const $k=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;const Rk=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Bk(e){return Rk.test(e)}function Mk(e){return Ak(Rk,e)}const Uk=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;const Lk=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;const Dk=/^receive\(\) external payable$/;const jk=new Set(["memory","indexed","storage","calldata"]),zk=new Set(["indexed"]),Hk=new Set(["calldata","memory","storage"]);class Vk extends xk{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}let Fk=class extends xk{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},qk=class extends xk{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};class Wk extends xk{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}let Zk=class extends xk{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},Kk=class extends xk{constructor({param:e,name:t}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${t}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},Gk=class extends xk{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},Yk=class extends xk{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},Jk=class extends xk{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}},Qk=class extends xk{constructor({signature:e,type:t}){super(`Invalid ${t} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},Xk=class extends xk{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},eI=class extends xk{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}},tI=class extends xk{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}},nI=class extends xk{constructor({current:e,depth:t}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${t>0?"opening":"closing"} parentheses.`],details:`Depth "${t}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};const rI=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function iI(e,t={}){if(function(e){return $k.test(e)}(e))return function(e,t={}){const n=function(e){return Ak($k,e)}(e);if(!n)throw new Qk({signature:e,type:"function"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{modifiers:Hk,structs:t,type:"function"}));const o=[];if(n.returns){const e=lI(n.returns),r=e.length;for(let n=0;n<r;n++)o.push(cI(e[n],{modifiers:Hk,structs:t,type:"function"}))}return{name:n.name,type:"function",stateMutability:n.stateMutability??"nonpayable",inputs:i,outputs:o}}(e,t);if(function(e){return Ok.test(e)}(e))return function(e,t={}){const n=function(e){return Ak(Ok,e)}(e);if(!n)throw new Qk({signature:e,type:"event"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{modifiers:zk,structs:t,type:"event"}));return{name:n.name,type:"event",inputs:i}}(e,t);if(function(e){return Tk.test(e)}(e))return function(e,t={}){const n=function(e){return Ak(Tk,e)}(e);if(!n)throw new Qk({signature:e,type:"error"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{structs:t,type:"error"}));return{name:n.name,type:"error",inputs:i}}(e,t);if(function(e){return Uk.test(e)}(e))return function(e,t={}){const n=function(e){return Ak(Uk,e)}(e);if(!n)throw new Qk({signature:e,type:"constructor"});const r=lI(n.parameters),i=[],s=r.length;for(let e=0;e<s;e++)i.push(cI(r[e],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:n.stateMutability??"nonpayable",inputs:i}}(e,t);if(function(e){return Lk.test(e)}(e))return function(e){const t=function(e){return Ak(Lk,e)}(e);if(!t)throw new Qk({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}(e);if(function(e){return Dk.test(e)}(e))return{type:"receive",stateMutability:"payable"};throw new Xk({signature:e})}const sI=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,oI=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,aI=/^u?int$/;function cI(e,t){const n=function(e,t,n){let r="";if(n)for(const e of Object.entries(n)){if(!e)continue;let t="";for(const n of e[1])t+=`[${n.type}${n.name?`:${n.name}`:""}]`;r+=`(${e[0]}{${t}})`}return t?`${t}:${e}${r}`:`${e}${r}`}(e,t?.type,t?.structs);if(rI.has(n))return rI.get(n);const r=Ck.test(e),i=Ak(r?oI:sI,e);if(!i)throw new Zk({param:e});if(i.name&&function(e){return"address"===e||"bool"===e||"function"===e||"string"===e||"tuple"===e||kk.test(e)||Ik.test(e)||hI.test(e)}(i.name))throw new Kk({param:e,name:i.name});const s=i.name?{name:i.name}:{},o="indexed"===i.modifier?{indexed:!0}:{},a=t?.structs??{};let c,l={};if(r){c="tuple";const e=lI(i.type),t=[],n=e.length;for(let r=0;r<n;r++)t.push(cI(e[r],{structs:a}));l={components:t}}else if(i.type in a)c="tuple",l={components:a[i.type]};else if(aI.test(i.type))c=`${i.type}256`;else if("address payable"===i.type)c="address";else if(c=i.type,"struct"!==t?.type&&!dI(c))throw new qk({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new Gk({param:e,type:t?.type,modifier:i.modifier});if(Hk.has(i.modifier)&&!function(e,t){return t||"bytes"===e||"string"===e||"tuple"===e}(c,!!i.array))throw new Yk({param:e,type:t?.type,modifier:i.modifier})}const d={type:`${c}${i.array??""}`,...s,...o,...l};return rI.set(n,d),d}function lI(e,t=[],n="",r=0){const i=e.trim().length;for(let s=0;s<i;s++){const i=e[s],o=e.slice(s+1);switch(i){case",":return 0===r?lI(o,[...t,n.trim()]):lI(o,t,`${n}${i}`,r);case"(":return lI(o,t,`${n}${i}`,r+1);case")":return lI(o,t,`${n}${i}`,r-1);default:return lI(o,t,`${n}${i}`,r)}}if(""===n)return t;if(0!==r)throw new nI({current:n,depth:r});return t.push(n.trim()),t}function dI(e){return"address"===e||"bool"===e||"function"===e||"string"===e||kk.test(e)||Ik.test(e)}const hI=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function uI(e){const t={},n=e.length;for(let r=0;r<n;r++){const n=e[r];if(!Bk(n))continue;const i=Mk(n);if(!i)throw new Qk({signature:n,type:"struct"});const s=i.properties.split(";"),o=[],a=s.length;for(let e=0;e<a;e++){const t=s[e].trim();if(!t)continue;const n=cI(t,{type:"struct"});o.push(n)}if(!o.length)throw new eI({signature:n});t[i.name]=o}const r={},i=Object.entries(t),s=i.length;for(let e=0;e<s;e++){const[n,s]=i[e];r[n]=fI(s,t)}return r}const pI=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function fI(e=[],t={},n=new Set){const r=[],i=e.length;for(let s=0;s<i;s++){const i=e[s];if(Ck.test(i.type))r.push(i);else{const e=Ak(pI,i.type);if(!e?.type)throw new Jk({abiParameter:i});const{array:s,type:o}=e;if(o in t){if(n.has(o))throw new tI({type:o});r.push({...i,type:`tuple${s??""}`,components:fI(t[o],t,new Set([...n,o]))})}else{if(!dI(o))throw new Fk({type:o});r.push(i)}}}return r}function gI(e){const t=uI(e),n=[],r=e.length;for(let i=0;i<r;i++){const r=e[i];Bk(r)||n.push(iI(r,t))}return n}function mI(e){let t;if("string"==typeof e)t=iI(e);else{const n=uI(e),r=e.length;for(let i=0;i<r;i++){const r=e[i];if(!Bk(r)){t=iI(r,n);break}}}if(!t)throw new Vk({signature:e});return t}function yI(e){const t=[];if("string"==typeof e){const n=lI(e),r=n.length;for(let e=0;e<r;e++)t.push(cI(n[e],{modifiers:jk}))}else{const n=uI(e),r=e.length;for(let i=0;i<r;i++){const r=e[i];if(Bk(r))continue;const s=lI(r),o=s.length;for(let e=0;e<o;e++)t.push(cI(s[e],{modifiers:jk,structs:n}))}}if(0===t.length)throw new Wk({params:e});return t}function wI(e,t,n){const r=e[t.name];if("function"==typeof r)return r;const i=e[n];return"function"==typeof i?i:n=>t(e,n)}function bI(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new JI(e.type);return`${e.name}(${vI(e.inputs,{includeName:t})})`}function vI(e,{includeName:t=!1}={}){return e?e.map(e=>function(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${vI(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}(e,{includeName:t})).join(t?", ":","):""}function EI(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function xI(e){return EI(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const AI="2.47.10";let kI=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,II=`viem@${AI}`,CI=class e extends Error{constructor(t,n={}){const r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,s=kI?.({...n,docsPath:i});super([t||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...II?[`Version: ${II}`]:[]].join("\n"),n.cause?{cause:n.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=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=AI}walk(e){return SI(this,e)}};function SI(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?SI(e.cause,t):t?null:e}class PI extends CI{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join("\n"),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class NI extends CI{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join("\n"),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class _I extends CI{constructor({data:e,params:t,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join("\n"),{metaMessages:[`Params: (${vI(t,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=t,this.size=n}}class TI extends CI{constructor({cause:e}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:e})}}let OI=class extends CI{constructor({expectedLength:e,givenLength:t,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${t}`].join("\n"),{name:"AbiEncodingArrayLengthMismatchError"})}},$I=class extends CI{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${xI(t)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}},RI=class extends CI{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${t}`].join("\n"),{name:"AbiEncodingLengthMismatchError"})}};class BI extends CI{constructor(e,{docsPath:t}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join("\n"),{docsPath:t,name:"AbiErrorInputsNotFoundError"})}}class MI extends CI{constructor(e,{docsPath:t}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join("\n"),{docsPath:t,name:"AbiErrorNotFoundError"})}}class UI extends CI{constructor(e,{docsPath:t,cause:n}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${e}.`].join("\n"),{docsPath:t,name:"AbiErrorSignatureNotFoundError",cause:n}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class LI extends CI{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class DI extends CI{constructor(e,{docsPath:t}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${e}.`].join("\n"),{docsPath:t,name:"AbiEventSignatureNotFoundError"})}}class jI extends CI{constructor(e,{docsPath:t}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join("\n"),{docsPath:t,name:"AbiEventNotFoundError"})}}let zI=class extends CI{constructor(e,{docsPath:t}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join("\n"),{docsPath:t,name:"AbiFunctionNotFoundError"})}};class HI extends CI{constructor(e,{docsPath:t}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join("\n"),{docsPath:t,name:"AbiFunctionOutputsNotFoundError"})}}class VI extends CI{constructor(e,{docsPath:t}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${e}.`].join("\n"),{docsPath:t,name:"AbiFunctionSignatureNotFoundError"})}}let FI=class extends CI{constructor(e,t){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${bI(e.abiItem)}\`, and`,`\`${t.type}\` in \`${bI(t.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}},qI=class extends CI{constructor({expectedSize:e,givenSize:t}){super(`Expected bytes${e}, got bytes${t}.`,{name:"BytesSizeMismatchError"})}};class WI extends CI{constructor({abiItem:e,data:t,params:n,size:r}){super([`Data size of ${r} bytes is too small for non-indexed event parameters.`].join("\n"),{metaMessages:[`Params: (${vI(n,{includeName:!0})})`,`Data: ${t} (${r} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=t,this.params=n,this.size=r}}class ZI extends CI{constructor({abiItem:e,param:t}){super([`Expected a topic for indexed event parameter${t.name?` "${t.name}"`:""} on event "${bI(e,{includeName:!0})}".`].join("\n"),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}let KI=class extends CI{constructor(e,{docsPath:t}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join("\n"),{docsPath:t,name:"InvalidAbiEncodingType"})}};class GI extends CI{constructor(e,{docsPath:t}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join("\n"),{docsPath:t,name:"InvalidAbiDecodingType"})}}let YI=class extends CI{constructor(e){super([`Value "${e}" is not a valid array.`].join("\n"),{name:"InvalidArrayError"})}},JI=class extends CI{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join("\n"),{name:"InvalidDefinitionTypeError"})}};class QI extends CI{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let XI=class extends CI{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},eC=class extends CI{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};class tC extends CI{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${t} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function nC(e,{dir:t,size:n=32}={}){return"string"==typeof e?rC(e,{dir:t,size:n}):iC(e,{dir:t,size:n})}function rC(e,{dir:t,size:n=32}={}){if(null===n)return e;const r=e.replace("0x","");if(r.length>2*n)throw new eC({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r["right"===t?"padEnd":"padStart"](2*n,"0")}`}function iC(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new eC({size:e.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s="right"===t;r[s?i:n-i-1]=e[s?i:e.length-i-1]}return r}let sC=class extends CI{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${8*r}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},oC=class extends CI{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class aC extends CI{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let cC=class extends CI{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function lC(e,{dir:t="left"}={}){let n="string"==typeof e?e.replace("0x",""):e,r=0;for(let e=0;e<n.length-1&&"0"===n["left"===t?e:n.length-e-1].toString();e++)r++;return n="left"===t?n.slice(r):n.slice(0,n.length-r),"string"==typeof e?(1===n.length&&"right"===t&&(n=`${n}0`),`0x${n.length%2==1?`0${n}`:n}`):n}function dC(e,{size:t}){if(xI(e)>t)throw new cC({givenSize:xI(e),maxSize:t})}function hC(e,t={}){const{signed:n}=t;t.size&&dC(e,{size:t.size});const r=BigInt(e);if(!n)return r;const i=(e.length-2)/2;return r<=(1n<<8n*BigInt(i)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*i,"f")}`)-1n}function uC(e,t={}){let n=e;if(t.size&&(dC(n,{size:t.size}),n=lC(n)),"0x00"===lC(n))return!1;if("0x01"===lC(n))return!0;throw new aC(n)}function pC(e,t={}){const n=hC(e,t),r=Number(n);if(!Number.isSafeInteger(r))throw new sC({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${n}n`});return r}const fC=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function gC(e,t={}){return"number"==typeof e||"bigint"==typeof e?wC(e,t):"string"==typeof e?vC(e,t):"boolean"==typeof e?mC(e,t):yC(e,t)}function mC(e,t={}){const n=`0x${Number(e)}`;return"number"==typeof t.size?(dC(n,{size:t.size}),nC(n,{size:t.size})):n}function yC(e,t={}){let n="";for(let t=0;t<e.length;t++)n+=fC[e[t]];const r=`0x${n}`;return"number"==typeof t.size?(dC(r,{size:t.size}),nC(r,{dir:"right",size:t.size})):r}function wC(e,t={}){const{signed:n,size:r}=t,i=BigInt(e);let s;r?s=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&i>s||i<o){const t="bigint"==typeof e?"n":"";throw new sC({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}const a=`0x${(n&&i<0?(1n<<BigInt(8*r))+BigInt(i):i).toString(16)}`;return r?nC(a,{size:r}):a}const bC=new TextEncoder;function vC(e,t={}){return yC(bC.encode(e),t)}const EC=new TextEncoder;function xC(e,t={}){return"number"==typeof e||"bigint"==typeof e?SC(e,t):"boolean"==typeof e?AC(e,t):EI(e)?CC(e,t):PC(e,t)}function AC(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(dC(n,{size:t.size}),nC(n,{size:t.size})):n}const kC={zero:48,nine:57,A:65,F:70,a:97,f:102};function IC(e){return e>=kC.zero&&e<=kC.nine?e-kC.zero:e>=kC.A&&e<=kC.F?e-(kC.A-10):e>=kC.a&&e<=kC.f?e-(kC.a-10):void 0}function CC(e,t={}){let n=e;t.size&&(dC(n,{size:t.size}),n=nC(n,{dir:"right",size:t.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let e=0,t=0;e<i;e++){const n=IC(r.charCodeAt(t++)),i=IC(r.charCodeAt(t++));if(void 0===n||void 0===i)throw new CI(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);s[e]=16*n+i}return s}function SC(e,t){return CC(wC(e,t))}function PC(e,t={}){const n=EC.encode(e);return"number"==typeof t.size?(dC(n,{size:t.size}),nC(n,{dir:"right",size:t.size})):n}const NC=BigInt(2**32-1),_C=BigInt(32);function TC(e,t=!1){return t?{h:Number(e&NC),l:Number(e>>_C&NC)}:{h:0|Number(e>>_C&NC),l:0|Number(e&NC)}}const OC="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function $C(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function RC(e,...t){if(!
|
|
41
41
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
42
42
|
function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function BC(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function MC(e,t){RC(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function UC(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function LC(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function DC(e,t){return e<<32-t|e>>>t}function jC(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const zC=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=jC(e[t]);return e};function HC(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),RC(e),e}let VC=class{};function FC(e){const t=t=>e().update(HC(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function qC(e=32){if(OC&&"function"==typeof OC.getRandomValues)return OC.getRandomValues(new Uint8Array(e));if(OC&&"function"==typeof OC.randomBytes)return Uint8Array.from(OC.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const WC=BigInt(0),ZC=BigInt(1),KC=BigInt(2),GC=BigInt(7),YC=BigInt(256),JC=BigInt(113),QC=[],XC=[],eS=[];for(let e=0,t=ZC,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],QC.push(2*(5*r+n)),XC.push((e+1)*(e+2)/2%64);let i=WC;for(let e=0;e<7;e++)t=(t<<ZC^(t>>GC)*JC)%YC,t&KC&&(i^=ZC<<(ZC<<BigInt(e))-ZC);eS.push(i)}const tS=function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=TC(e[s],t);[r[s],i[s]]=[n,o]}return[r,i]}(eS,!0),nS=tS[0],rS=tS[1],iS=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),sS=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);let oS=class e extends VC{constructor(e,t,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,$C(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}clone(){return this._cloneInto()}keccak(){zC(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,s=n[i],o=n[i+1],a=iS(s,o,1)^n[r],c=sS(s,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=XC[n],s=iS(t,i,r),o=sS(t,i,r),a=QC[n];t=e[a],i=e[a+1],e[a]=s,e[a+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=nS[r],e[1]^=rS[r]}UC(n)}(this.state32,this.rounds),zC(this.state32),this.posOut=0,this.pos=0}update(e){BC(this),RC(e=HC(e));const{blockLen:t,state:n}=this,r=e.length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){BC(this,!1),RC(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return $C(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(MC(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,UC(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new e(n,r,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}};const aS=(()=>{return e=1,t=136,n=32,FC(()=>new oS(t,e,n));var e,t,n})();function cS(e,t){const n=t||"hex",r=aS(EI(e,{strict:!1})?xC(e):e);return"bytes"===n?r:gC(r)}function lS(e){return cS(xC(e))}const dS=e=>function(e){let t=!0,n="",r=0,i="",s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),"("===a&&r++,")"===a&&r--,t)if(0!==r)" "!==a?(i+=a,n+=a):","!==e[o-1]&&","!==n&&",("!==n&&(n="",t=!1);else if(" "===a&&["event","function",""].includes(i))i="";else if(i+=a,")"===a){s=!0;break}}if(!s)throw new CI("Unable to normalize signature.");return i}("string"==typeof e?e:_k(e));function hS(e){return lS(dS(e))}const uS=hS;let pS=class extends CI{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},fS=class 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)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=super.keys().next().value;void 0!==e&&super.delete(e)}return this}};const gS=new fS(8192);function mS(e,t){if(gS.has(`${e}.${t}`))return gS.get(`${e}.${t}`);const n=e.substring(2).toLowerCase(),r=cS(PC(n),"bytes"),i=n.split("");for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&i[e]&&(i[e]=i[e].toUpperCase()),(15&r[e>>1])>=8&&i[e+1]&&(i[e+1]=i[e+1].toUpperCase());const s=`0x${i.join("")}`;return gS.set(`${e}.${t}`,s),s}function yS(e,t){if(!vS(e,{strict:!1}))throw new pS({address:e});return mS(e,t)}const wS=/^0x[a-fA-F0-9]{40}$/,bS=new fS(8192);function vS(e,t){const{strict:n=!0}=t??{},r=`${e}.${n}`;if(bS.has(r))return bS.get(r);const i=!(!wS.test(e)||e.toLowerCase()!==e&&n&&mS(e)!==e);return bS.set(r,i),i}function ES(e){return"string"==typeof e[0]?AS(e):xS(e)}function xS(e){let t=0;for(const n of e)t+=n.length;const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}function AS(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}function kS(e,t,n,{strict:r}={}){return EI(e,{strict:!1})?PS(e,t,n,{strict:r}):SS(e,t,n,{strict:r})}function IS(e,t){if("number"==typeof t&&t>0&&t>xI(e)-1)throw new XI({offset:t,position:"start",size:xI(e)})}function CS(e,t,n){if("number"==typeof t&&"number"==typeof n&&xI(e)!==n-t)throw new XI({offset:n,position:"end",size:xI(e)})}function SS(e,t,n,{strict:r}={}){IS(e,t);const i=e.slice(t,n);return r&&CS(i,t,n),i}function PS(e,t,n,{strict:r}={}){IS(e,t);const i=`0x${e.replace("0x","").slice(2*(t??0),2*(n??e.length))}`;return r&&CS(i,t,n),i}const NS=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,_S=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function TS(e,t){if(e.length!==t.length)throw new RI({expectedLength:e.length,givenLength:t.length});const n=function({params:e,values:t}){const n=[];for(let r=0;r<e.length;r++)n.push(OS({param:e[r],value:t[r]}));return n}({params:e,values:t}),r=$S(n);return 0===r.length?"0x":r}function OS({param:e,value:t}){const n=RS(e.type);if(n){const[r,i]=n;return function(e,{length:t,param:n}){const r=null===t;if(!Array.isArray(e))throw new YI(e);if(!r&&e.length!==t)throw new OI({expectedLength:t,givenLength:e.length,type:`${n.type}[${t}]`});let i=!1;const s=[];for(let t=0;t<e.length;t++){const r=OS({param:n,value:e[t]});r.dynamic&&(i=!0),s.push(r)}if(r||i){const e=$S(s);if(r){const t=wC(s.length,{size:32});return{dynamic:!0,encoded:s.length>0?ES([t,e]):t}}if(i)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:ES(s.map(({encoded:e})=>e))}}(t,{length:r,param:{...e,type:i}})}if("tuple"===e.type)return function(e,{param:t}){let n=!1;const r=[];for(let i=0;i<t.components.length;i++){const s=t.components[i],o=OS({param:s,value:e[Array.isArray(e)?i:s.name]});r.push(o),o.dynamic&&(n=!0)}return{dynamic:n,encoded:n?$S(r):ES(r.map(({encoded:e})=>e))}}(t,{param:e});if("address"===e.type)return function(e){if(!vS(e))throw new pS({address:e});return{dynamic:!1,encoded:rC(e.toLowerCase())}}(t);if("bool"===e.type)return function(e){if("boolean"!=typeof e)throw new CI(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:rC(mC(e))}}(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,r="256"]=_S.exec(e.type)??[];return function(e,{signed:t,size:n=256}){if("number"==typeof n){const r=2n**(BigInt(n)-(t?1n:0n))-1n,i=t?-r-1n:0n;if(e>r||e<i)throw new sC({max:r.toString(),min:i.toString(),signed:t,size:n/8,value:e.toString()})}return{dynamic:!1,encoded:wC(e,{size:32,signed:t})}}(t,{signed:n,size:Number(r)})}if(e.type.startsWith("bytes"))return function(e,{param:t}){const[,n]=t.type.split("bytes"),r=xI(e);if(!n){let t=e;return r%32!=0&&(t=rC(t,{dir:"right",size:32*Math.ceil((e.length-2)/2/32)})),{dynamic:!0,encoded:ES([rC(wC(r,{size:32})),t])}}if(r!==Number.parseInt(n,10))throw new $I({expectedSize:Number.parseInt(n,10),value:e});return{dynamic:!1,encoded:rC(e,{dir:"right"})}}(t,{param:e});if("string"===e.type)return function(e){const t=vC(e),n=Math.ceil(xI(t)/32),r=[];for(let e=0;e<n;e++)r.push(rC(kS(t,32*e,32*(e+1)),{dir:"right"}));return{dynamic:!0,encoded:ES([rC(wC(xI(t),{size:32})),...r])}}(t);throw new KI(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function $S(e){let t=0;for(let n=0;n<e.length;n++){const{dynamic:r,encoded:i}=e[n];t+=r?32:xI(i)}const n=[],r=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(n.push(wC(t+i,{size:32})),r.push(a),i+=xI(a)):n.push(a)}return ES([...n,...r])}function RS(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const BS=e=>kS(hS(e),0,4);function MS(e){const{abi:t,args:n=[],name:r}=e,i=EI(r,{strict:!1}),s=t.filter(e=>i?"function"===e.type?BS(e)===r:"event"===e.type&&uS(e)===r:"name"in e&&e.name===r);if(0===s.length)return;if(1===s.length)return s[0];let o;for(const e of s){if(!("inputs"in e))continue;if(!n||0===n.length){if(!e.inputs||0===e.inputs.length)return e;continue}if(!e.inputs)continue;if(0===e.inputs.length)continue;if(e.inputs.length!==n.length)continue;const t=n.every((t,n)=>{const r="inputs"in e&&e.inputs[n];return!!r&&US(t,r)});if(t){if(o&&"inputs"in o&&o.inputs){const t=LS(e.inputs,o.inputs,n);if(t)throw new FI({abiItem:e,type:t[0]},{abiItem:o,type:t[1]})}o=e}}return o||s[0]}function US(e,t){const n=typeof e,r=t.type;switch(r){case"address":return vS(e,{strict:!1});case"bool":return"boolean"===n;case"function":case"string":return"string"===n;default:return"tuple"===r&&"components"in t?Object.values(t.components).every((t,r)=>"object"===n&&US(Object.values(e)[r],t)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(r)?"number"===n||"bigint"===n:/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(r)?"string"===n||e instanceof Uint8Array:!!/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(r)&&(Array.isArray(e)&&e.every(e=>US(e,{...t,type:r.replace(/(\[[0-9]{0,}\])$/,"")})))}}function LS(e,t,n){for(const r in e){const i=e[r],s=t[r];if("tuple"===i.type&&"tuple"===s.type&&"components"in i&&"components"in s)return LS(i.components,s.components,n[r]);const o=[i.type,s.type];if((()=>!(!o.includes("address")||!o.includes("bytes20"))||(o.includes("address")&&o.includes("string")||!(!o.includes("address")||!o.includes("bytes")))&&vS(n[r],{strict:!1}))())return o}}const DS="/docs/contract/encodeEventTopics";function jS(e){const{abi:t,eventName:n,args:r}=e;let i=t[0];if(n){const e=MS({abi:t,name:n});if(!e)throw new jI(n,{docsPath:DS});i=e}if("event"!==i.type)throw new jI(void 0,{docsPath:DS});const s=bI(i),o=uS(s);let a=[];if(r&&"inputs"in i){const e=i.inputs?.filter(e=>"indexed"in e&&e.indexed),t=Array.isArray(r)?r:Object.values(r).length>0?e?.map(e=>r[e.name])??[]:[];t.length>0&&(a=e?.map((e,n)=>Array.isArray(t[n])?t[n].map((r,i)=>zS({param:e,value:t[n][i]})):void 0!==t[n]&&null!==t[n]?zS({param:e,value:t[n]}):null)??[])}return[o,...a]}function zS({param:e,value:t}){if("string"===e.type||"bytes"===e.type)return cS(xC(t));if("tuple"===e.type||e.type.match(/^(.*)\[(\d+)?\]$/))throw new QI(e.type);return TS([e],[t])}function HS(e,{method:t}){const n={};return"fallback"===e.transport.type&&e.transport.onResponse?.(({method:e,response:r,status:i,transport:s})=>{"success"===i&&t===e&&(n[r]=s.request)}),t=>n[t]||e.request}async function VS(e,t){const{address:n,abi:r,args:i,eventName:s,fromBlock:o,strict:a,toBlock:c}=t,l=HS(e,{method:"eth_newFilter"}),d=s?jS({abi:r,args:i,eventName:s}):void 0,h=await e.request({method:"eth_newFilter",params:[{address:n,fromBlock:"bigint"==typeof o?wC(o):o,toBlock:"bigint"==typeof c?wC(c):c,topics:d}]});return{abi:r,args:i,eventName:s,id:h,request:l(h),strict:Boolean(a),type:"event"}}function FS(e){return"string"==typeof e?{address:e,type:"json-rpc"}:e}const qS="/docs/contract/encodeFunctionData";function WS(e){const{abi:t,args:n,functionName:r}=e;let i=t[0];if(r){const e=MS({abi:t,args:n,name:r});if(!e)throw new zI(r,{docsPath:qS});i=e}if("function"!==i.type)throw new zI(void 0,{docsPath:qS});return{abi:[i],functionName:BS(bI(i))}}function ZS(e){const{args:t}=e,{abi:n,functionName:r}=1===e.abi.length&&e.functionName?.startsWith("0x")?e:WS(e),i=n[0];return AS([r,("inputs"in i&&i.inputs?TS(i.inputs,t??[]):void 0)??"0x"])}const KS={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},GS={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},YS={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let JS=class extends CI{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},QS=class extends CI{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},XS=class extends CI{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const eP={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new XS({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new QS({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new JS({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new JS({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const n=this.inspectBytes(e);return this.position+=t??e,n},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function tP(e,{recursiveReadLimit:t=8192}={}){const n=Object.create(eP);return n.bytes=e,n.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}function nP(e,t={}){void 0!==t.size&&dC(e,{size:t.size});return hC(yC(e,t),t)}function rP(e,t={}){let n=e;if(void 0!==t.size&&(dC(n,{size:t.size}),n=lC(n)),n.length>1||n[0]>1)throw new oC(n);return Boolean(n[0])}function iP(e,t={}){void 0!==t.size&&dC(e,{size:t.size});return pC(yC(e,t),t)}function sP(e,t={}){let n=e;return void 0!==t.size&&(dC(n,{size:t.size}),n=lC(n,{dir:"right"})),(new TextDecoder).decode(n)}function oP(e,t){const n="string"==typeof t?CC(t):t,r=tP(n);if(0===xI(n)&&e.length>0)throw new TI;if(xI(t)&&xI(t)<32)throw new _I({data:"string"==typeof t?t:yC(t),params:e,size:xI(t)});let i=0;const s=[];for(let t=0;t<e.length;++t){const n=e[t];r.setPosition(i);const[o,a]=aP(r,n,{staticPosition:0});i+=a,s.push(o)}return s}function aP(e,t,{staticPosition:n}){const r=RS(t.type);if(r){const[i,s]=r;return function(e,t,{length:n,staticPosition:r}){if(!n){const n=r+iP(e.readBytes(lP)),i=n+cP;e.setPosition(n);const s=iP(e.readBytes(cP)),o=dP(t);let a=0;const c=[];for(let n=0;n<s;++n){e.setPosition(i+(o?32*n:a));const[r,s]=aP(e,t,{staticPosition:i});a+=s,c.push(r)}return e.setPosition(r+32),[c,32]}if(dP(t)){const i=r+iP(e.readBytes(lP)),s=[];for(let r=0;r<n;++r){e.setPosition(i+32*r);const[n]=aP(e,t,{staticPosition:i});s.push(n)}return e.setPosition(r+32),[s,32]}let i=0;const s=[];for(let o=0;o<n;++o){const[n,o]=aP(e,t,{staticPosition:r+i});i+=o,s.push(n)}return[s,i]}(e,{...t,type:s},{length:i,staticPosition:n})}if("tuple"===t.type)return function(e,t,{staticPosition:n}){const r=0===t.components.length||t.components.some(({name:e})=>!e),i=r?[]:{};let s=0;if(dP(t)){const o=n+iP(e.readBytes(lP));for(let n=0;n<t.components.length;++n){const a=t.components[n];e.setPosition(o+s);const[c,l]=aP(e,a,{staticPosition:o});s+=l,i[r?n:a?.name]=c}return e.setPosition(n+32),[i,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,l]=aP(e,a,{staticPosition:n});i[r?o:a?.name]=c,s+=l}return[i,s]}(e,t,{staticPosition:n});if("address"===t.type)return function(e){const t=e.readBytes(32);return[mS(yC(SS(t,-20))),32]}(e);if("bool"===t.type)return function(e){return[rP(e.readBytes(32),{size:32}),32]}(e);if(t.type.startsWith("bytes"))return function(e,t,{staticPosition:n}){const[r,i]=t.type.split("bytes");if(!i){const t=iP(e.readBytes(32));e.setPosition(n+t);const r=iP(e.readBytes(32));if(0===r)return e.setPosition(n+32),["0x",32];const i=e.readBytes(r);return e.setPosition(n+32),[yC(i),32]}const s=yC(e.readBytes(Number.parseInt(i,10),32));return[s,32]}(e,t,{staticPosition:n});if(t.type.startsWith("uint")||t.type.startsWith("int"))return function(e,t){const n=t.type.startsWith("int"),r=Number.parseInt(t.type.split("int")[1]||"256",10),i=e.readBytes(32);return[r>48?nP(i,{signed:n}):iP(i,{signed:n}),32]}(e,t);if("string"===t.type)return function(e,{staticPosition:t}){const n=iP(e.readBytes(32)),r=t+n;e.setPosition(r);const i=iP(e.readBytes(32));if(0===i)return e.setPosition(t+32),["",32];const s=e.readBytes(i,32),o=sP(lC(s));return e.setPosition(t+32),[o,32]}(e,{staticPosition:n});throw new GI(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const cP=32,lP=32;function dP(e){const{type:t}=e;if("string"===t)return!0;if("bytes"===t)return!0;if(t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(dP);const n=RS(e.type);return!(!n||!dP({...e,type:n[1]}))}function hP(e){const{abi:t,data:n,cause:r}=e,i=kS(n,0,4);if("0x"===i)throw new TI({cause:r});const s=[...t||[],GS,YS].find(e=>"error"===e.type&&i===BS(bI(e)));if(!s)throw new UI(i,{docsPath:"/docs/contract/decodeErrorResult",cause:r});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?oP(s.inputs,kS(n,4)):void 0,errorName:s.name}}const uP=(e,t,n)=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,n);function pP({abiItem:e,args:t,includeFunctionName:n=!0,includeName:r=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${n?e.name:""}(${e.inputs.map((e,n)=>`${r&&e.name?`${e.name}: `:""}${"object"==typeof t[n]?uP(t[n]):t[n]}`).join(", ")})`}const fP={gwei:9,wei:18},gP={ether:-9,wei:9};function mP(e,t){let n=e.toString();const r=n.startsWith("-");r&&(n=n.slice(1)),n=n.padStart(t,"0");let[i,s]=[n.slice(0,n.length-t),n.slice(n.length-t)];return s=s.replace(/(0+)$/,""),`${r?"-":""}${i||"0"}${s?`.${s}`:""}`}function yP(e,t="wei"){return mP(e,fP[t])}function wP(e,t="wei"){return mP(e,gP[t])}class bP extends CI{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class vP extends CI{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function EP(e){return e.reduce((e,{slot:t,value:n})=>`${e} ${t}: ${n}\n`,"")}function xP(e){const t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),n=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(n+1)} ${t}`).join("\n")}class AP extends CI{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",xP(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class kP extends CI{constructor(e,{account:t,docsPath:n,chain:r,data:i,gas:s,gasPrice:o,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:l,to:d,value:h}){const u=xP({chain:r&&`${r?.name} (id: ${r?.id})`,from:t?.address,to:d,value:void 0!==h&&`${yP(h)} ${r?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:void 0!==o&&`${wP(o)} gwei`,maxFeePerGas:void 0!==a&&`${wP(a)} gwei`,maxPriorityFeePerGas:void 0!==c&&`${wP(c)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",u].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class IP extends CI{constructor({blockHash:e,blockNumber:t,blockTag:n,hash:r,index:i}){let s="Transaction";n&&void 0!==i&&(s=`Transaction at block time "${n}" at index "${i}"`),e&&void 0!==i&&(s=`Transaction at block hash "${e}" at index "${i}"`),t&&void 0!==i&&(s=`Transaction at block number "${t}" at index "${i}"`),r&&(s=`Transaction with hash "${r}"`),super(`${s} could not be found.`,{name:"TransactionNotFoundError"})}}class CP extends CI{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class SP extends CI{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class PP extends CI{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}class NP extends CI{constructor(e,{account:t,docsPath:n,chain:r,data:i,gas:s,gasPrice:o,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:l,to:d,value:h,stateOverride:u}){const p=t?FS(t):void 0;let f=xP({from:p?.address,to:d,value:void 0!==h&&`${yP(h)} ${r?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:void 0!==o&&`${wP(o)} gwei`,maxFeePerGas:void 0!==a&&`${wP(a)} gwei`,maxPriorityFeePerGas:void 0!==c&&`${wP(c)} gwei`,nonce:l});u&&(f+=`\n${function(e){return e.reduce((e,{address:t,...n})=>{let r=`${e} ${t}:\n`;return n.nonce&&(r+=` nonce: ${n.nonce}\n`),n.balance&&(r+=` balance: ${n.balance}\n`),n.code&&(r+=` code: ${n.code}\n`),n.state&&(r+=" state:\n",r+=EP(n.state)),n.stateDiff&&(r+=" stateDiff:\n",r+=EP(n.stateDiff)),r}," State Override:\n").slice(0,-1)}(u)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",f].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class _P extends CI{constructor(e,{abi:t,args:n,contractAddress:r,docsPath:i,functionName:s,sender:o}){const a=MS({abi:t,args:n,name:s}),c=a?pP({abiItem:a,args:n,includeFunctionName:!1,includeName:!1}):void 0,l=xP({address:r&&r,function:a?bI(a,{includeName:!0}):void 0,args:c&&"()"!==c&&`${[...Array(s?.length??0).keys()].map(()=>" ").join("")}${c}`,sender:o});super(e.shortMessage||`An unknown error occurred while executing the contract function "${s}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],l&&"Contract Call:",l].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=t,this.args=n,this.cause=e,this.contractAddress=r,this.functionName=s,this.sender=o}}class TP extends CI{constructor({abi:e,data:t,functionName:n,message:r,cause:i}){let s,o,a,c,l;if(t&&"0x"!==t)try{o=hP({abi:e,data:t,cause:i});const{abiItem:n,errorName:r,args:s}=o;if("Error"===r)c=s[0];else if("Panic"===r){const[e]=s;c=KS[e]}else{const e=n?bI(n,{includeName:!0}):void 0,t=n&&s?pP({abiItem:n,args:s,includeFunctionName:!1,includeName:!1}):void 0;a=[e?`Error: ${e}`:"",t&&"()"!==t?` ${[...Array(r?.length??0).keys()].map(()=>" ").join("")}${t}`:""]}}catch(e){s=e}else r&&(c=r);s instanceof UI&&(l=s.signature,a=[`Unable to decode signature "${l}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${l}.`]),super(c&&"execution reverted"!==c||l?[`The contract function "${n}" reverted with the following ${l?"signature":"reason"}:`,c||l].join("\n"):`The contract function "${n}" reverted.`,{cause:s??i,metaMessages:a,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.raw=t,this.reason=c,this.signature=l}}class OP extends CI{constructor({functionName:e,cause:t}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:t})}}class $P extends CI{constructor({factory:e}){super("Deployment for counterfactual contract call failed"+(e?` for factory "${e}".`:""),{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class RP extends CI{constructor({data:e,message:t}){super(t||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}class BP extends CI{constructor({body:e,cause:t,details:n,headers:r,status:i,url:s}){super("HTTP request failed.",{cause:t,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${s}`,e&&`Request body: ${uP(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=r,this.status=i,this.url=s}}class MP extends CI{constructor({body:e,error:t,url:n}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${n}`,`Request body: ${uP(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t.code,this.data=t.data,this.url=n}}class UP extends CI{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${t}`,`Request body: ${uP(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}}class LP extends CI{constructor(e,{code:t,docsPath:n,metaMessages:r,name:i,shortMessage:s}){super(s,{cause:e,docsPath:n,metaMessages:r||e?.metaMessages,name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof MP?e.code:t??-1}}class DP extends LP{constructor(e,t){super(e,t),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class jP extends LP{constructor(e){super(e,{code:jP.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(jP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class zP extends LP{constructor(e){super(e,{code:zP.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(zP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class HP extends LP{constructor(e,{method:t}={}){super(e,{code:HP.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(HP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class VP extends LP{constructor(e){super(e,{code:VP.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(VP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class FP extends LP{constructor(e){super(e,{code:FP.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(FP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class qP extends LP{constructor(e){super(e,{code:qP.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(qP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class WP extends LP{constructor(e){super(e,{code:WP.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(WP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class ZP extends LP{constructor(e){super(e,{code:ZP.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(ZP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class KP extends LP{constructor(e){super(e,{code:KP.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(KP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class GP extends LP{constructor(e,{method:t}={}){super(e,{code:GP.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(GP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class YP extends LP{constructor(e){super(e,{code:YP.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(YP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class JP extends LP{constructor(e){super(e,{code:JP.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(JP,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class QP extends DP{constructor(e){super(e,{code:QP.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(QP,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class XP extends DP{constructor(e){super(e,{code:XP.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(XP,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class eN extends DP{constructor(e,{method:t}={}){super(e,{code:eN.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(eN,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class tN extends DP{constructor(e){super(e,{code:tN.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(tN,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class nN extends DP{constructor(e){super(e,{code:nN.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(nN,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class rN extends DP{constructor(e){super(e,{code:rN.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(rN,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class iN extends DP{constructor(e){super(e,{code:iN.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(iN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class sN extends DP{constructor(e){super(e,{code:sN.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(sN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class oN extends DP{constructor(e){super(e,{code:oN.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(oN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class aN extends DP{constructor(e){super(e,{code:aN.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(aN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class cN extends DP{constructor(e){super(e,{code:cN.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(cN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class lN extends DP{constructor(e){super(e,{code:lN.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(lN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class dN extends DP{constructor(e){super(e,{code:dN.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(dN,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class hN extends DP{constructor(e){super(e,{code:hN.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(hN,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});class uN extends LP{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const pN=3;function fN(e,{abi:t,address:n,args:r,docsPath:i,functionName:s,sender:o}){const a=e instanceof RP?e:e instanceof CI?e.walk(e=>"data"in e)||e.walk():{},{code:c,data:l,details:d,message:h,shortMessage:u}=a,p=e instanceof TI?new OP({functionName:s,cause:e}):[pN,FP.code].includes(c)&&(l||d||h||u)||c===qP.code&&"execution reverted"===d&&l?new TP({abi:t,data:"object"==typeof l?l.data:l,functionName:s,message:a instanceof MP?d:u??h,cause:e}):e;return new _P(p,{abi:t,args:r,contractAddress:n,docsPath:i,functionName:s,sender:o})}async function gN({hash:e,signature:t}){const n=EI(e)?e:gC(e),{secp256k1:r}=await Promise.resolve().then(function(){return eM}),i=(()=>{if("object"==typeof t&&"r"in t&&"s"in t){const{r:e,s:n,v:i,yParity:s}=t,o=mN(Number(s??i));return new r.Signature(hC(e),hC(n)).addRecoveryBit(o)}const e=EI(t)?t:gC(t);if(65!==xI(e))throw new Error("invalid signature length");const n=mN(pC(`0x${e.slice(130)}`));return r.Signature.fromCompact(e.substring(2,130)).addRecoveryBit(n)})();return`0x${i.recoverPublicKey(n.substring(2)).toHex(!1)}`}function mN(e){if(0===e||1===e)return e;if(27===e)return 0;if(28===e)return 1;throw new Error("Invalid yParityOrV value")}async function yN({hash:e,signature:t}){return mS(`0x${cS(`0x${(await gN({hash:e,signature:t})).substring(4)}`).substring(26)}`)}function wN(e,t="hex"){const n=bN(e),r=tP(new Uint8Array(n.length));return n.encode(r),"hex"===t?yC(r.bytes):r.bytes}function bN(e){return Array.isArray(e)?function(e){const t=e.reduce((e,t)=>e+t.length,0),n=vN(t);return{length:t<=55?1+t:1+n+t,encode(r){t<=55?r.pushByte(192+t):(r.pushByte(247+n),1===n?r.pushUint8(t):2===n?r.pushUint16(t):3===n?r.pushUint24(t):r.pushUint32(t));for(const{encode:t}of e)t(r)}}}(e.map(e=>bN(e))):function(e){const t="string"==typeof e?CC(e):e,n=vN(t.length),r=1===t.length&&t[0]<128?1:t.length<=55?1+t.length:1+n+t.length;return{length:r,encode(e){1===t.length&&t[0]<128?e.pushBytes(t):t.length<=55?(e.pushByte(128+t.length),e.pushBytes(t)):(e.pushByte(183+n),1===n?e.pushUint8(t.length):2===n?e.pushUint16(t.length):3===n?e.pushUint24(t.length):e.pushUint32(t.length),e.pushBytes(t))}}}(e)}function vN(e){if(e<256)return 1;if(e<65536)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new CI("Length is too large.")}function EN(e){const{chainId:t,nonce:n,to:r}=e,i=e.contractAddress??e.address,s=cS(AS(["0x05",wN([t?wC(t):"0x",i,n?wC(n):"0x"])]));return"bytes"===r?CC(s):s}async function xN(e){const{authorization:t,signature:n}=e;return yN({hash:EN(t),signature:n??t})}class AN extends CI{constructor(e,{account:t,docsPath:n,chain:r,data:i,gas:s,gasPrice:o,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:l,to:d,value:h}){const u=xP({from:t?.address,to:d,value:void 0!==h&&`${yP(h)} ${r?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:void 0!==o&&`${wP(o)} gwei`,maxFeePerGas:void 0!==a&&`${wP(a)} gwei`,maxPriorityFeePerGas:void 0!==c&&`${wP(c)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",u].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class kN extends CI{constructor({cause:e,message:t}={}){const n=t?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(kN,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(kN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class IN extends CI{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${wP(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(IN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class CN extends CI{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${wP(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(CN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class SN extends CI{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(SN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class PN extends CI{constructor({cause:e,nonce:t}={}){super([`Nonce provided for the transaction ${t?`(${t}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join("\n"),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(PN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class NN extends CI{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(NN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class _N extends CI{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join("\n"),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(_N,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class TN extends CI{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(TN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class ON extends CI{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(ON,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class $N extends CI{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty($N,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class RN extends CI{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${wP(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${wP(n)} gwei`:""}).`].join("\n"),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(RN,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class BN extends CI{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function MN(e,t){const n=(e.details||"").toLowerCase(),r=e instanceof CI?e.walk(e=>e?.code===kN.code):e;return r instanceof CI?new kN({cause:e,message:r.details}):kN.nodeMessage.test(n)?new kN({cause:e,message:e.details}):IN.nodeMessage.test(n)?new IN({cause:e,maxFeePerGas:t?.maxFeePerGas}):CN.nodeMessage.test(n)?new CN({cause:e,maxFeePerGas:t?.maxFeePerGas}):SN.nodeMessage.test(n)?new SN({cause:e,nonce:t?.nonce}):PN.nodeMessage.test(n)?new PN({cause:e,nonce:t?.nonce}):NN.nodeMessage.test(n)?new NN({cause:e,nonce:t?.nonce}):_N.nodeMessage.test(n)?new _N({cause:e}):TN.nodeMessage.test(n)?new TN({cause:e,gas:t?.gas}):ON.nodeMessage.test(n)?new ON({cause:e,gas:t?.gas}):$N.nodeMessage.test(n)?new $N({cause:e}):RN.nodeMessage.test(n)?new RN({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new BN({cause:e})}function UN(e,{format:t}){if(!t)return{};const n={};return function t(r){const i=Object.keys(r);for(const s of i)s in e&&(n[s]=e[s]),r[s]&&"object"==typeof r[s]&&!Array.isArray(r[s])&&t(r[s])}(t(e||{})),n}const LN={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function DN(e,t){const n={};return void 0!==e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?wC(BigInt(e.r)):e.r,s:e.s?wC(BigInt(e.s)):e.s,chainId:wC(e.chainId),nonce:wC(e.nonce),...void 0!==e.yParity?{yParity:wC(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:wC(e.v)}:{}}))),void 0!==e.accessList&&(n.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(n.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?n.blobs=e.blobs.map(e=>yC(e)):n.blobs=e.blobs),void 0!==e.data&&(n.data=e.data),e.account&&(n.from=e.account.address),void 0!==e.from&&(n.from=e.from),void 0!==e.gas&&(n.gas=wC(e.gas)),void 0!==e.gasPrice&&(n.gasPrice=wC(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=wC(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(n.maxFeePerGas=wC(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=wC(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(n.nonce=wC(e.nonce)),void 0!==e.to&&(n.to=e.to),void 0!==e.type&&(n.type=LN[e.type]),void 0!==e.value&&(n.value=wC(e.value)),n}function jN(e){if(e&&0!==e.length)return e.reduce((e,{slot:t,value:n})=>{if(66!==t.length)throw new tC({size:t.length,targetSize:66,type:"hex"});if(66!==n.length)throw new tC({size:n.length,targetSize:66,type:"hex"});return e[t]=n,e},{})}function zN(e){const{balance:t,nonce:n,state:r,stateDiff:i,code:s}=e,o={};if(void 0!==s&&(o.code=s),void 0!==t&&(o.balance=wC(t)),void 0!==n&&(o.nonce=wC(n)),void 0!==r&&(o.state=jN(r)),void 0!==i){if(o.state)throw new vP;o.stateDiff=jN(i)}return o}function HN(e){if(!e)return;const t={};for(const{address:n,...r}of e){if(!vS(n,{strict:!1}))throw new pS({address:n});if(t[n])throw new bP({address:n});t[n]=zN(r)}return t}const VN=2n**256n-1n;function FN(e){const{account:t,maxFeePerGas:n,maxPriorityFeePerGas:r,to:i}=e,s=t?FS(t):void 0;if(s&&!vS(s.address))throw new pS({address:s.address});if(i&&!vS(i))throw new pS({address:i});if(n&&n>VN)throw new IN({maxFeePerGas:n});if(r&&n&&r>n)throw new RN({maxFeePerGas:n,maxPriorityFeePerGas:r})}class qN extends CI{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class WN extends CI{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class ZN extends CI{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${wP(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class KN extends CI{constructor({blockHash:e,blockNumber:t}){let n="Block";e&&(n=`Block at hash "${e}"`),t&&(n=`Block at number "${t}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const GN={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function YN(e,t){const n={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?pC(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?pC(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?GN[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))),n.yParity=(()=>{if(e.yParity)return Number(e.yParity);if("bigint"==typeof n.v){if(0n===n.v||27n===n.v)return 0;if(1n===n.v||28n===n.v)return 1;if(n.v>=35n)return n.v%2n==0n?1:0}})(),"legacy"===n.type&&(delete n.accessList,delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas,delete n.yParity),"eip2930"===n.type&&(delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas),"eip1559"===n.type&&delete n.maxFeePerBlobGas,n}function JN(e,t){const n=(e.transactions??[]).map(e=>"string"==typeof e?e:YN(e));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:n,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function QN(e,{blockHash:t,blockNumber:n,blockTag:r=e.experimental_blockTag??"latest",includeTransactions:i}={}){const s=i??!1,o=void 0!==n?wC(n):void 0;let a=null;if(a=t?await e.request({method:"eth_getBlockByHash",params:[t,s]},{dedupe:!0}):await e.request({method:"eth_getBlockByNumber",params:[o||r,s]},{dedupe:Boolean(o)}),!a)throw new KN({blockHash:t,blockNumber:n});return(e.chain?.formatters?.block?.format||JN)(a,"getBlock")}async function XN(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function e_(e,t){const{block:n,chain:r=e.chain,request:i}=t||{};try{const t=r?.fees?.maxPriorityFeePerGas??r?.fees?.defaultPriorityFee;if("function"==typeof t){const r=n||await wI(e,QN,"getBlock")({}),s=await t({block:r,client:e,request:i});if(null===s)throw new Error;return s}if(void 0!==t)return t;return hC(await e.request({method:"eth_maxPriorityFeePerGas"}))}catch{const[t,r]=await Promise.all([n?Promise.resolve(n):wI(e,QN,"getBlock")({}),wI(e,XN,"getGasPrice")({})]);if("bigint"!=typeof t.baseFeePerGas)throw new WN;const i=r-t.baseFeePerGas;return i<0n?0n:i}}async function t_(e,t){const{block:n,chain:r=e.chain,request:i,type:s="eip1559"}=t||{},o=await(async()=>"function"==typeof r?.fees?.baseFeeMultiplier?r.fees.baseFeeMultiplier({block:n,client:e,request:i}):r?.fees?.baseFeeMultiplier??1.2)();if(o<1)throw new qN;const a=10**(o.toString().split(".")[1]?.length??0),c=e=>e*BigInt(Math.ceil(o*a))/BigInt(a),l=n||await wI(e,QN,"getBlock")({});if("function"==typeof r?.fees?.estimateFeesPerGas){const t=await r.fees.estimateFeesPerGas({block:n,client:e,multiply:c,request:i,type:s});if(null!==t)return t}if("eip1559"===s){if("bigint"!=typeof l.baseFeePerGas)throw new WN;const t="bigint"==typeof i?.maxPriorityFeePerGas?i.maxPriorityFeePerGas:await e_(e,{block:l,chain:r,request:i}),n=c(l.baseFeePerGas);return{maxFeePerGas:i?.maxFeePerGas??n+t,maxPriorityFeePerGas:t}}return{gasPrice:i?.gasPrice??c(await wI(e,XN,"getGasPrice")({}))}}async function n_(e,{address:t,blockTag:n="latest",blockNumber:r}){return pC(await e.request({method:"eth_getTransactionCount",params:[t,"bigint"==typeof r?wC(r):n]},{dedupe:Boolean(r)}))}function r_(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),r="string"==typeof e.blobs[0]?e.blobs.map(e=>CC(e)):e.blobs,i=[];for(const e of r)i.push(Uint8Array.from(t.blobToKzgCommitment(e)));return"bytes"===n?i:i.map(e=>yC(e))}function i_(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),r="string"==typeof e.blobs[0]?e.blobs.map(e=>CC(e)):e.blobs,i="string"==typeof e.commitments[0]?e.commitments.map(e=>CC(e)):e.commitments,s=[];for(let e=0;e<r.length;e++){const n=r[e],o=i[e];s.push(Uint8Array.from(t.computeBlobKzgProof(n,o)))}return"bytes"===n?s:s.map(e=>yC(e))}function s_(e,t,n){return e&t^~e&n}function o_(e,t,n){return e&t^e&n^t&n}let a_=class extends VC{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=LC(this.buffer)}update(e){BC(this),RC(e=HC(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=LC(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){BC(this),MC(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,UC(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const o=LC(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const c_=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l_=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),d_=new Uint32Array(64);let h_=class extends a_{constructor(e=32){super(64,e,8,!1),this.A=0|c_[0],this.B=0|c_[1],this.C=0|c_[2],this.D=0|c_[3],this.E=0|c_[4],this.F=0|c_[5],this.G=0|c_[6],this.H=0|c_[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)d_[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=d_[e-15],n=d_[e-2],r=DC(t,7)^DC(t,18)^t>>>3,i=DC(n,17)^DC(n,19)^n>>>10;d_[e]=i+d_[e-7]+r+d_[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(DC(o,6)^DC(o,11)^DC(o,25))+s_(o,a,c)+l_[e]+d_[e]|0,d=(DC(n,2)^DC(n,13)^DC(n,22))+o_(n,r,i)|0;l=c,c=a,a=o,o=s+t|0,s=i,i=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,s,o,a,c,l)}roundClean(){UC(d_)}destroy(){this.set(0,0,0,0,0,0,0,0),UC(this.buffer)}};const u_=FC(()=>new h_),p_=u_;function f_(e,t){return p_(EI(e,{strict:!1})?xC(e):e)}function g_(e){const{commitment:t,version:n=1}=e,r=e.to??("string"==typeof t?"hex":"bytes"),i=f_(t);return i.set([n],0),"bytes"===r?i:yC(i)}function m_(e){const{commitments:t,version:n}=e,r=e.to,i=[];for(const e of t)i.push(g_({commitment:e,to:r,version:n}));return i}const y_=4096,w_=131072,b_=761855;class v_ extends CI{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class E_ extends CI{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}function x_(e){const t="string"==typeof e.data?CC(e.data):e.data,n=xI(t);if(!n)throw new E_;if(n>b_)throw new v_({maxSize:b_,size:n});const r=[];let i=!0,s=0;for(;i;){const e=tP(new Uint8Array(w_));let n=0;for(;n<y_;){const r=t.slice(s,s+31);if(e.pushByte(0),e.pushBytes(r),r.length<31){e.pushByte(128),i=!1;break}n++,s+=31}r.push(e)}return r.map(e=>yC(e.bytes))}function A_(e){const{data:t,kzg:n,to:r}=e,i=e.blobs??x_({data:t}),s=e.commitments??r_({blobs:i,kzg:n,to:r}),o=e.proofs??i_({blobs:i,commitments:s,kzg:n,to:r}),a=[];for(let e=0;e<i.length;e++)a.push({blob:i[e],commitment:s[e],proof:o[e]});return a}function k_(e){if(e.type)return e.type;if(void 0!==e.authorizationList)return"eip7702";if(void 0!==e.blobs||void 0!==e.blobVersionedHashes||void 0!==e.maxFeePerBlobGas||void 0!==e.sidecars)return"eip4844";if(void 0!==e.maxFeePerGas||void 0!==e.maxPriorityFeePerGas)return"eip1559";if(void 0!==e.gasPrice)return void 0!==e.accessList?"eip2930":"legacy";throw new AP({transaction:e})}async function I_(e){return pC(await e.request({method:"eth_chainId"},{dedupe:!0}))}async function C_(e,t){const{account:n=e.account,accessList:r,authorizationList:i,chain:s=e.chain,blobVersionedHashes:o,blobs:a,data:c,gas:l,gasPrice:d,maxFeePerBlobGas:h,maxFeePerGas:u,maxPriorityFeePerGas:p,nonce:f,nonceManager:g,to:m,type:y,value:w,...b}=t,v=await(async()=>{if(!n)return f;if(!g)return f;if(void 0!==f)return f;const t=FS(n),r=s?s.id:await wI(e,I_,"getChainId")({});return await g.consume({address:t.address,chainId:r,client:e})})();FN(t);const E=s?.formatters?.transactionRequest?.format,x=(E||DN)({...UN(b,{format:E}),account:n?FS(n):void 0,accessList:r,authorizationList:i,blobs:a,blobVersionedHashes:o,data:c,gas:l,gasPrice:d,maxFeePerBlobGas:h,maxFeePerGas:u,maxPriorityFeePerGas:p,nonce:v,to:m,type:y,value:w},"fillTransaction");try{const n=await e.request({method:"eth_fillTransaction",params:[x]}),r=(s?.formatters?.transaction?.format||YN)(n.tx);delete r.blockHash,delete r.blockNumber,delete r.r,delete r.s,delete r.transactionIndex,delete r.v,delete r.yParity,r.data=r.input,r.gas&&(r.gas=t.gas??r.gas),r.gasPrice&&(r.gasPrice=t.gasPrice??r.gasPrice),r.maxFeePerBlobGas&&(r.maxFeePerBlobGas=t.maxFeePerBlobGas??r.maxFeePerBlobGas),r.maxFeePerGas&&(r.maxFeePerGas=t.maxFeePerGas??r.maxFeePerGas),r.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=t.maxPriorityFeePerGas??r.maxPriorityFeePerGas),r.nonce&&(r.nonce=t.nonce??r.nonce);const i=await(async()=>{if("function"==typeof s?.fees?.baseFeeMultiplier){const n=await wI(e,QN,"getBlock")({});return s.fees.baseFeeMultiplier({block:n,client:e,request:t})}return s?.fees?.baseFeeMultiplier??1.2})();if(i<1)throw new qN;const o=10**(i.toString().split(".")[1]?.length??0),a=e=>e*BigInt(Math.ceil(i*o))/BigInt(o);return r.maxFeePerGas&&!t.maxFeePerGas&&(r.maxFeePerGas=a(r.maxFeePerGas)),r.gasPrice&&!t.gasPrice&&(r.gasPrice=a(r.gasPrice)),{raw:n.raw,transaction:{from:x.from,...r}}}catch(n){throw function(e,{docsPath:t,...n}){const r=(()=>{const t=MN(e,n);return t instanceof BN?e:t})();return new kP(r,{docsPath:t,...n})}(n,{...t,chain:e.chain})}}const S_=["blobVersionedHashes","chainId","fees","gas","nonce","type"],P_=new Map,N_=new fS(128);async function __(e,t){let n=t;n.account??=e.account,n.parameters??=S_;const{account:r,chain:i=e.chain,nonceManager:s,parameters:o}=n,a="function"==typeof i?.prepareTransactionRequest?{fn:i.prepareTransactionRequest,runAt:["beforeFillTransaction"]}:Array.isArray(i?.prepareTransactionRequest)?{fn:i.prepareTransactionRequest[0],runAt:i.prepareTransactionRequest[1].runAt}:void 0;let c;async function l(){if(c)return c;if(void 0!==n.chainId)return n.chainId;if(i)return i.id;const t=await wI(e,I_,"getChainId")({});return c=t,c}const d=r?FS(r):r;let h=n.nonce;if(o.includes("nonce")&&void 0===h&&d&&s){const t=await l();h=await s.consume({address:d.address,chainId:t,client:e})}a?.fn&&a.runAt?.includes("beforeFillTransaction")&&(n=await a.fn({...n,chain:i},{phase:"beforeFillTransaction"}),h??=n.nonce);const u=(()=>{if((o.includes("blobVersionedHashes")||o.includes("sidecars"))&&n.kzg&&n.blobs)return!1;if(!1===N_.get(e.uid))return!1;return!!["fees","gas"].some(e=>o.includes(e))&&(!(!o.includes("chainId")||"number"==typeof n.chainId)||(!(!o.includes("nonce")||"number"==typeof h)||(!(!o.includes("fees")||"bigint"==typeof n.gasPrice||"bigint"==typeof n.maxFeePerGas&&"bigint"==typeof n.maxPriorityFeePerGas)||!(!o.includes("gas")||"bigint"==typeof n.gas))))})()?await wI(e,C_,"fillTransaction")({...n,nonce:h}).then(t=>{const{chainId:r,from:i,gas:s,gasPrice:o,nonce:a,maxFeePerBlobGas:c,maxFeePerGas:l,maxPriorityFeePerGas:d,type:h,...u}=t.transaction;return N_.set(e.uid,!0),{...n,...i?{from:i}:{},...h&&!n.type?{type:h}:{},...void 0!==r?{chainId:r}:{},...void 0!==s?{gas:s}:{},...void 0!==o?{gasPrice:o}:{},...void 0!==a?{nonce:a}:{},...void 0!==c&&"legacy"!==n.type&&"eip2930"!==n.type?{maxFeePerBlobGas:c}:{},...void 0!==l&&"legacy"!==n.type&&"eip2930"!==n.type?{maxFeePerGas:l}:{},...void 0!==d&&"legacy"!==n.type&&"eip2930"!==n.type?{maxPriorityFeePerGas:d}:{},..."nonceKey"in u&&void 0!==u.nonceKey?{nonceKey:u.nonceKey}:{},..."keyAuthorization"in u&&void 0!==u.keyAuthorization&&null!==u.keyAuthorization&&!("keyAuthorization"in n)?{keyAuthorization:u.keyAuthorization}:{}}}).catch(t=>{const r=t;if("TransactionExecutionError"!==r.name)return n;const i=r.walk?.(e=>"ExecutionRevertedError"===e.name);if(i)throw t;const s=r.walk?.(e=>{const t=e;return"MethodNotFoundRpcError"===t.name||"MethodNotSupportedRpcError"===t.name||t.message?.includes("eth_fillTransaction is not available")});return s&&N_.set(e.uid,!1),n}):n;h??=u.nonce,n={...u,...d?{from:d?.address}:{},...h?{nonce:h}:{}};const{blobs:p,gas:f,kzg:g,type:m}=n;let y;async function w(){return y||(y=await wI(e,QN,"getBlock")({blockTag:"latest"}),y)}if(a?.fn&&a.runAt?.includes("beforeFillParameters")&&(n=await a.fn({...n,chain:i},{phase:"beforeFillParameters"})),o.includes("nonce")&&void 0===h&&d&&!s&&(n.nonce=await wI(e,n_,"getTransactionCount")({address:d.address,blockTag:"pending"})),(o.includes("blobVersionedHashes")||o.includes("sidecars"))&&p&&g){const e=r_({blobs:p,kzg:g});if(o.includes("blobVersionedHashes")){const t=m_({commitments:e,to:"hex"});n.blobVersionedHashes=t}if(o.includes("sidecars")){const t=A_({blobs:p,commitments:e,proofs:i_({blobs:p,commitments:e,kzg:g}),to:"hex"});n.sidecars=t}}if(o.includes("chainId")&&(n.chainId=await l()),(o.includes("fees")||o.includes("type"))&&void 0===m)try{n.type=k_(n)}catch{let t=P_.get(e.uid);if(void 0===t){const n=await w();t="bigint"==typeof n?.baseFeePerGas,P_.set(e.uid,t)}n.type=t?"eip1559":"legacy"}if(o.includes("fees"))if("legacy"!==n.type&&"eip2930"!==n.type){if(void 0===n.maxFeePerGas||void 0===n.maxPriorityFeePerGas){const t=await w(),{maxFeePerGas:r,maxPriorityFeePerGas:s}=await t_(e,{block:t,chain:i,request:n});if(void 0===n.maxPriorityFeePerGas&&n.maxFeePerGas&&n.maxFeePerGas<s)throw new ZN({maxPriorityFeePerGas:s});n.maxPriorityFeePerGas=s,n.maxFeePerGas=r}}else{if(void 0!==n.maxFeePerGas||void 0!==n.maxPriorityFeePerGas)throw new WN;if(void 0===n.gasPrice){const t=await w(),{gasPrice:r}=await t_(e,{block:t,chain:i,request:n,type:"legacy"});n.gasPrice=r}}return o.includes("gas")&&void 0===f&&(n.gas=await wI(e,T_,"estimateGas")({...n,account:d,prepare:"local"===d?.type?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(n=await a.fn({...n,chain:i},{phase:"afterFillParameters"})),FN(n),delete n.parameters,n}async function T_(e,t){const{account:n=e.account,prepare:r=!0}=t,i=n?FS(n):void 0,s=Array.isArray(r)?r:"local"!==i?.type?["blobVersionedHashes"]:void 0;try{const n=await(async()=>t.to?t.to:t.authorizationList&&t.authorizationList.length>0?await xN({authorization:t.authorizationList[0]}).catch(()=>{throw new CI("`to` is required. Could not infer from `authorizationList`")}):void 0)(),{accessList:o,authorizationList:a,blobs:c,blobVersionedHashes:l,blockNumber:d,blockTag:h,data:u,gas:p,gasPrice:f,maxFeePerBlobGas:g,maxFeePerGas:m,maxPriorityFeePerGas:y,nonce:w,value:b,stateOverride:v,...E}=r?await __(e,{...t,parameters:s,to:n}):t;if(p&&t.gas!==p)return p;const x=("bigint"==typeof d?wC(d):void 0)||h,A=HN(v);FN(t);const k=e.chain?.formatters?.transactionRequest?.format,I=(k||DN)({...UN(E,{format:k}),account:i,accessList:o,authorizationList:a,blobs:c,blobVersionedHashes:l,data:u,gasPrice:f,maxFeePerBlobGas:g,maxFeePerGas:m,maxPriorityFeePerGas:y,nonce:w,to:n,value:b},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:A?[I,x??e.experimental_blockTag??"latest",A]:x?[I,x]:[I]}))}catch(n){throw function(e,{docsPath:t,...n}){const r=(()=>{const t=MN(e,n);return t instanceof BN?e:t})();return new AN(r,{docsPath:t,...n})}(n,{...t,account:i,chain:e.chain})}}function O_(e,t){if(!vS(e,{strict:!1}))throw new pS({address:e});if(!vS(t,{strict:!1}))throw new pS({address:t});return e.toLowerCase()===t.toLowerCase()}function $_(e,{args:t,eventName:n}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):null===e.blockTimestamp?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...n?{args:t,eventName:n}:{}}}const R_="/docs/contract/decodeEventLog";function B_(e){const{abi:t,data:n,strict:r,topics:i}=e,s=r??!0,[o,...a]=i;if(!o)throw new LI({docsPath:R_});const c=t.find(e=>"event"===e.type&&o===uS(bI(e)));if(!c||!("name"in c)||"event"!==c.type)throw new DI(o,{docsPath:R_});const{name:l,inputs:d}=c,h=d?.some(e=>!("name"in e&&e.name)),u=h?[]:{},p=d.map((e,t)=>[e,t]).filter(([e])=>"indexed"in e&&e.indexed),f=[];for(let e=0;e<p.length;e++){const[t,n]=p[e],r=a[e];if(r)u[h?n:t.name||n]=M_({param:t,value:r});else{if(s)throw new ZI({abiItem:c,param:t});f.push([t,n])}}const g=d.filter(e=>!("indexed"in e&&e.indexed)),m=s?g:[...f.map(([e])=>e),...g];if(m.length>0)if(n&&"0x"!==n)try{const e=oP(m,n);if(e){let t=0;if(!s)for(const[n,r]of f)u[h?r:n.name||r]=e[t++];if(h)for(let n=0;n<d.length;n++)void 0===u[n]&&t<e.length&&(u[n]=e[t++]);else for(let n=0;n<g.length;n++)u[g[n].name]=e[t++]}}catch(e){if(s){if(e instanceof _I||e instanceof QS)throw new WI({abiItem:c,data:n,params:m,size:xI(n)});throw e}}else if(s)throw new WI({abiItem:c,data:"0x",params:m,size:0});return{eventName:l,args:Object.values(u).length>0?u:void 0}}function M_({param:e,value:t}){if("string"===e.type||"bytes"===e.type||"tuple"===e.type||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(oP([e],t)||[])[0]}function U_(e){const{abi:t,args:n,logs:r,strict:i=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),o=t.filter(e=>"event"===e.type).map(e=>({abi:e,selector:uS(e)}));return r.map(e=>{const t="string"==typeof e.blockNumber?$_(e):e,r=o.filter(e=>t.topics[0]===e.selector);if(0===r.length)return null;let a,c;for(const e of r)try{a=B_({...t,abi:[e.abi],strict:!0}),c=e;break}catch{}if(!a&&!i){c=r[0];try{a=B_({data:t.data,topics:t.topics,abi:[c.abi],strict:!1})}catch{const e=c.abi.inputs?.some(e=>!("name"in e&&e.name));return{...t,args:e?[]:{},eventName:c.abi.name}}}return a&&c?s&&!s.includes(a.eventName)?null:function(e){const{args:t,inputs:n,matchArgs:r}=e;if(!r)return!0;if(!t)return!1;function i(e,t,n){try{return"address"===e.type?O_(t,n):"string"===e.type||"bytes"===e.type?cS(xC(t))===n:t===n}catch{return!1}}if(Array.isArray(t)&&Array.isArray(r))return r.every((e,r)=>{if(null==e)return!0;const s=n[r];if(!s)return!1;return(Array.isArray(e)?e:[e]).some(e=>i(s,e,t[r]))});return"object"==typeof t&&!Array.isArray(t)&&"object"==typeof r&&!Array.isArray(r)&&Object.entries(r).every(([e,r])=>{if(null==r)return!0;const s=n.find(t=>t.name===e);if(!s)return!1;return(Array.isArray(r)?r:[r]).some(n=>i(s,n,t[e]))})}({args:a.args,inputs:c.abi.inputs,matchArgs:n})?{...a,...t}:null:null}).filter(Boolean)}async function L_(e,{address:t,blockHash:n,fromBlock:r,toBlock:i,event:s,events:o,args:a,strict:c}={}){const l=c??!1,d=o??(s?[s]:void 0);let h,u=[];if(d){const e=d.flatMap(e=>jS({abi:[e],eventName:e.name,args:o?void 0:a}));u=[e],s&&(u=u[0])}h=n?await e.request({method:"eth_getLogs",params:[{address:t,topics:u,blockHash:n}]}):await e.request({method:"eth_getLogs",params:[{address:t,topics:u,fromBlock:"bigint"==typeof r?wC(r):r,toBlock:"bigint"==typeof i?wC(i):i}]});const p=h.map(e=>$_(e));return d?U_({abi:d,args:a,logs:p,strict:l}):p}async function D_(e,t){const{abi:n,address:r,args:i,blockHash:s,eventName:o,fromBlock:a,toBlock:c,strict:l}=t,d=o?MS({abi:n,name:o}):void 0,h=d?void 0:n.filter(e=>"event"===e.type);return wI(e,L_,"getLogs")({address:r,args:i,blockHash:s,event:d,events:h,fromBlock:a,toBlock:c,strict:l})}const j_="/docs/contract/decodeFunctionResult";function z_(e){const{abi:t,args:n,functionName:r,data:i}=e;let s=t[0];if(r){const e=MS({abi:t,args:n,name:r});if(!e)throw new zI(r,{docsPath:j_});s=e}if("function"!==s.type)throw new zI(void 0,{docsPath:j_});if(!s.outputs)throw new HI(s.name,{docsPath:j_});const o=oP(s.outputs,i);return o&&o.length>1?o:o&&1===o.length?o[0]:void 0}
|
|
43
43
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const H_=BigInt(0),V_=BigInt(1);function F_(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function q_(e){if(!F_(e))throw new Error("Uint8Array expected")}function W_(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Z_(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function K_(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?H_:BigInt("0x"+e)}const G_="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,Y_=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function J_(e){if(q_(e),G_)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Y_[e[n]];return t}const Q_=48,X_=57,eT=65,tT=70,nT=97,rT=102;function iT(e){return e>=Q_&&e<=X_?e-Q_:e>=eT&&e<=tT?e-(eT-10):e>=nT&&e<=rT?e-(nT-10):void 0}function sT(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(G_)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=iT(e.charCodeAt(i)),s=iT(e.charCodeAt(i+1));if(void 0===n||void 0===s){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+s}return r}function oT(e){return K_(J_(e))}function aT(e){return q_(e),K_(J_(Uint8Array.from(e).reverse()))}function cT(e,t){return sT(e.toString(16).padStart(2*t,"0"))}function lT(e,t){return cT(e,t).reverse()}function dT(e,t,n){let r;if("string"==typeof t)try{r=sT(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!F_(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function hT(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];q_(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}const uT=e=>"bigint"==typeof e&&H_<=e;function pT(e,t,n){return uT(e)&&uT(t)&&uT(n)&&t<=e&&e<n}function fT(e,t,n,r){if(!pT(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const gT=e=>(V_<<BigInt(e))-V_,mT=e=>new Uint8Array(e),yT=e=>Uint8Array.from(e);const wT={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||F_(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function bT(e,t,n={}){const r=(t,n,r)=>{const i=wT[n];if("function"!=typeof i)throw new Error("invalid validator function");const s=e[t];if(!(r&&void 0===s||i(s,e)))throw new Error("param "+String(t)+" is invalid. Expected "+n+", got "+s)};for(const[e,n]of Object.entries(t))r(e,n,!1);for(const[e,t]of Object.entries(n))r(e,t,!0);return e}function vT(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}let ET=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){const r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&"string"==typeof n.cause.details?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,s=n.docsOrigin??e.prototype.docsOrigin,o=`${s}${i??""}`,a=Boolean(n.version??e.prototype.showVersion),c=n.version??e.prototype.version,l=[t||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||i||a?["",r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(e=>"string"==typeof e).join("\n");super(l,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{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,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=n.cause,this.details=r,this.docs=o,this.docsOrigin=s,this.docsPath=i,this.shortMessage=t,this.showVersion=a,this.version=c}walk(e){return xT(this,e)}};function xT(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&e.cause?xT(e.cause,t):t?null:e}function AT(e,t){if(jT(e)>t)throw new KT({givenSize:jT(e),maxSize:t})}Object.defineProperty(ET,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:"ox@0.1.1"}}),ET.setStaticOptions(ET.defaultStaticOptions);const kT=48,IT=57,CT=65,ST=70,PT=97,NT=102;function _T(e){return e>=kT&&e<=IT?e-kT:e>=CT&&e<=ST?e-(CT-10):e>=PT&&e<=NT?e-(PT-10):void 0}function TT(e,t={}){const{dir:n="left"}=t;let r=e,i=0;for(let e=0;e<r.length-1&&"0"===r["left"===n?e:r.length-e-1].toString();e++)i++;return r="left"===n?r.slice(i):r.slice(0,r.length-i),r}function OT(e,t){if(oO(e)>t)throw new pO({givenSize:oO(e),maxSize:t})}function $T(e,t={}){const{dir:n,size:r=32}=t;if(0===r)return e;const i=e.replace("0x","");if(i.length>2*r)throw new gO({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i["right"===n?"padEnd":"padStart"](2*r,"0")}`}function RT(e,t,n){return JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString()+"#__bigint":t,n)}const BT=new TextDecoder,MT=new TextEncoder;function UT(e){return e instanceof Uint8Array?e:"string"==typeof e?LT(e):function(e){return e instanceof Uint8Array?e:new Uint8Array(e)}(e)}function LT(e,t={}){const{size:n}=t;let r=e;n&&(OT(e,n),r=iO(e,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let e=0,t=0;e<s;e++){const n=_T(i.charCodeAt(t++)),r=_T(i.charCodeAt(t++));if(void 0===n||void 0===r)throw new ET(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=n<<4|r}return o}function DT(e,t={}){const{size:n}=t,r=MT.encode(e);return"number"==typeof n?(AT(r,n),function(e,t){return function(e,t={}){const{dir:n,size:r=32}=t;if(0===r)return e;if(e.length>r)throw new GT({size:e.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let t=0;t<r;t++){const s="right"===n;i[s?t:r-t-1]=e[s?t:e.length-t-1]}return i}(e,{dir:"right",size:t})}(r,n)):r}function jT(e){return e.length}function zT(e,t,n,r={}){const{strict:i}=r;return e.slice(t,n)}function HT(e,t={}){const{size:n}=t;void 0!==n&&AT(e,n);return aO(eO(e,t),t)}function VT(e,t={}){const{size:n}=t;let r=e;if(void 0!==n&&(AT(r,n),r=WT(r)),r.length>1||r[0]>1)throw new ZT(r);return Boolean(r[0])}function FT(e,t={}){const{size:n}=t;void 0!==n&&AT(e,n);return cO(eO(e,t),t)}function qT(e,t={}){const{size:n}=t;let r=e;return void 0!==n&&(AT(r,n),r=TT(r,{dir:"right"})),BT.decode(r)}function WT(e){return TT(e,{dir:"left"})}class ZT extends ET{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let KT=class extends ET{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},GT=class extends ET{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const YT=new TextEncoder,JT=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function QT(...e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}function XT(e,t={}){const n=`0x${Number(e)}`;return"number"==typeof t.size?(OT(n,t.size),rO(n,t.size)):n}function eO(e,t={}){let n="";for(let t=0;t<e.length;t++)n+=JT[e[t]];const r=`0x${n}`;return"number"==typeof t.size?(OT(r,t.size),iO(r,t.size)):r}function tO(e,t={}){const{signed:n,size:r}=t,i=BigInt(e);let s;r?s=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&i>s||i<o){const t="bigint"==typeof e?"n":"";throw new dO({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}const a=`0x${(n&&i<0?BigInt.asUintN(8*r,BigInt(i)):i).toString(16)}`;return r?rO(a,r):a}function nO(e,t={}){return eO(YT.encode(e),t)}function rO(e,t){return $T(e,{dir:"left",size:t})}function iO(e,t){return $T(e,{dir:"right",size:t})}function sO(e,t,n,r={}){const{strict:i}=r;!function(e,t){if("number"==typeof t&&t>0&&t>oO(e)-1)throw new fO({offset:t,position:"start",size:oO(e)})}(e,t);const s=`0x${e.replace("0x","").slice(2*(t??0),2*(n??e.length))}`;return i&&function(e,t,n){if("number"==typeof t&&"number"==typeof n&&oO(e)!==n-t)throw new fO({offset:n,position:"end",size:oO(e)})}(s,t,n),s}function oO(e){return Math.ceil((e.length-2)/2)}function aO(e,t={}){const{signed:n}=t;t.size&&OT(e,t.size);const r=BigInt(e);if(!n)return r;const i=(e.length-2)/2,s=(1n<<8n*BigInt(i))-1n;return r<=s>>1n?r:r-s-1n}function cO(e,t={}){const{signed:n,size:r}=t;return Number(n||r?aO(e,t):e)}function lO(e,t={}){const{strict:n=!1}=t;try{return function(e,t={}){const{strict:n=!1}=t;if(!e)throw new hO(e);if("string"!=typeof e)throw new hO(e);if(n&&!/^0x[0-9a-fA-F]*$/.test(e))throw new uO(e);if(!e.startsWith("0x"))throw new uO(e)}(e,{strict:n}),!0}catch{return!1}}let dO=class extends ET{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number \`${i}\` is not in safe${r?` ${8*r}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},hO=class extends ET{constructor(e){super(`Value \`${"object"==typeof e?RT(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},uO=class extends ET{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},pO=class extends ET{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},fO=class extends ET{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},gO=class extends ET{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};function mO(e){return{address:e.address,amount:tO(e.amount),index:tO(e.index),validatorIndex:tO(e.validatorIndex)}}function yO(e){return{..."bigint"==typeof e.baseFeePerGas&&{baseFeePerGas:tO(e.baseFeePerGas)},..."bigint"==typeof e.blobBaseFee&&{blobBaseFee:tO(e.blobBaseFee)},..."string"==typeof e.feeRecipient&&{feeRecipient:e.feeRecipient},..."bigint"==typeof e.gasLimit&&{gasLimit:tO(e.gasLimit)},..."bigint"==typeof e.number&&{number:tO(e.number)},..."bigint"==typeof e.prevRandao&&{prevRandao:tO(e.prevRandao)},..."bigint"==typeof e.time&&{time:tO(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(mO)}}}const wO=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],bO=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],vO=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],EO=[...vO,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],xO=[...vO,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],AO=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],kO=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],IO=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],CO=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],SO=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],PO="0x82ad56cb",NO="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",_O="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",TO="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",OO="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class $O extends CI{constructor({blockNumber:e,chain:t,contract:n}){super(`Chain "${t.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class RO extends CI{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}const BO="/docs/contract/encodeDeployData";function MO(e){const{abi:t,args:n,bytecode:r}=e;if(!n||0===n.length)return r;const i=t.find(e=>"type"in e&&"constructor"===e.type);if(!i)throw new PI({docsPath:BO});if(!("inputs"in i))throw new NI({docsPath:BO});if(!i.inputs||0===i.inputs.length)throw new NI({docsPath:BO});return AS([r,TS(i.inputs,n)])}function UO({blockNumber:e,chain:t,contract:n}){const r=t?.contracts?.[n];if(!r)throw new $O({chain:t,contract:{name:n}});if(e&&r.blockCreated&&r.blockCreated>e)throw new $O({blockNumber:e,chain:t,contract:{name:n,blockCreated:r.blockCreated}});return r.address}function LO(e,{docsPath:t,...n}){const r=(()=>{const t=MN(e,n);return t instanceof BN?e:t})();return new NP(r,{docsPath:t,...n})}function DO(){let e=()=>{},t=()=>{};return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}const jO=new Map;function zO({fn:e,id:t,shouldSplitBatch:n,wait:r=0,sort:i}){const s=async()=>{const t=a();o();const n=t.map(({args:e})=>e);0!==n.length&&e(n).then(e=>{i&&Array.isArray(e)&&e.sort(i);for(let n=0;n<t.length;n++){const{resolve:r}=t[n];r?.([e[n],e])}}).catch(e=>{for(let n=0;n<t.length;n++){const{reject:r}=t[n];r?.(e)}})},o=()=>jO.delete(t),a=()=>jO.get(t)||[],c=e=>jO.set(t,[...a(),e]);return{flush:o,async schedule(e){const{promise:t,resolve:i,reject:o}=DO(),l=n?.([...a().map(({args:e})=>e),e]);l&&s();return a().length>0?(c({args:e,resolve:i,reject:o}),t):(c({args:e,resolve:i,reject:o}),setTimeout(s,r),t)}}}async function HO(e,t){const{account:n=e.account,authorizationList:r,batch:i=Boolean(e.batch?.multicall),blockNumber:s,blockTag:o=e.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:l,code:d,data:h,factory:u,factoryData:p,gas:f,gasPrice:g,maxFeePerBlobGas:m,maxFeePerGas:y,maxPriorityFeePerGas:w,nonce:b,to:v,value:E,stateOverride:x,...A}=t,k=n?FS(n):void 0;if(d&&(u||p))throw new CI("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(d&&v)throw new CI("Cannot provide both `code` & `to` as parameters.");const I=d&&h,C=u&&p&&v&&h,S=I||C,P=I?VO({code:d,data:h}):C?function(e){const{data:t,factory:n,factoryData:r,to:i}=e;return MO({abi:gI(["constructor(address, bytes, address, bytes)"]),bytecode:_O,args:[i,t,n,r]})}({data:h,factory:u,factoryData:p,to:v}):h;try{FN(t);const n=("bigint"==typeof s?wC(s):void 0)||o,d=l?yO(l):void 0,h=HN(x),u=e.chain?.formatters?.transactionRequest?.format,p=(u||DN)({...UN(A,{format:u}),accessList:a,account:k,authorizationList:r,blobs:c,data:P,gas:f,gasPrice:g,maxFeePerBlobGas:m,maxFeePerGas:y,maxPriorityFeePerGas:w,nonce:b,to:S?void 0:v,value:E},"call");if(i&&function({request:e}){const{data:t,to:n,...r}=e;return!!t&&(!t.startsWith(PO)&&(!!n&&!(Object.values(r).filter(e=>void 0!==e).length>0)))}({request:p})&&!h&&!d)try{return await async function(e,t){const{batchSize:n=1024,deployless:r=!1,wait:i=0}="object"==typeof e.batch?.multicall?e.batch.multicall:{},{blockNumber:s,blockTag:o=e.experimental_blockTag??"latest",data:a,to:c}=t,l=(()=>{if(r)return null;if(t.multicallAddress)return t.multicallAddress;if(e.chain)return UO({blockNumber:s,chain:e.chain,contract:"multicall3"});throw new RO})(),d="bigint"==typeof s?wC(s):void 0,h=d||o,{schedule:u}=zO({id:`${e.uid}.${h}`,wait:i,shouldSplitBatch(e){const t=e.reduce((e,{data:t})=>e+(t.length-2),0);return t>2*n},fn:async t=>{const n=t.map(e=>({allowFailure:!0,callData:e.data,target:e.to})),r=ZS({abi:wO,args:[n],functionName:"aggregate3"}),i=await e.request({method:"eth_call",params:[{...null===l?{data:VO({code:OO,data:r})}:{to:l,data:r}},h]});return z_({abi:wO,args:[n],functionName:"aggregate3",data:i||"0x"})}}),[{returnData:p,success:f}]=await u({data:a,to:c});if(!f)throw new RP({data:p});return"0x"===p?{data:void 0}:{data:p}}(e,{...p,blockNumber:s,blockTag:o})}catch(e){if(!(e instanceof RO||e instanceof $O))throw e}const I=(()=>{const e=[p,n];return h&&d?[...e,h,d]:h?[...e,h]:d?[...e,{},d]:e})(),C=await e.request({method:"eth_call",params:I});return"0x"===C?{data:void 0}:{data:C}}catch(n){const r=function(e){if(!(e instanceof CI))return;const t=e.walk();return"object"==typeof t?.data?t.data?.data:t.data}(n),{offchainLookup:i,offchainLookupSignature:s}=await Promise.resolve().then(function(){return X$});if(!1!==e.ccipRead&&r?.slice(0,10)===s&&v)return{data:await i(e,{data:r,to:v})};if(S&&"0x101bb98d"===r?.slice(0,10))throw new $P({factory:u});throw LO(n,{...t,account:k,chain:e.chain})}}function VO(e){const{code:t,data:n}=e;return MO({abi:gI(["constructor(bytes, bytes)"]),bytecode:NO,args:[t,n]})}async function FO(e,t){const{abi:n,address:r,args:i,functionName:s,...o}=t,a=ZS({abi:n,args:i,functionName:s});try{const{data:t}=await wI(e,HO,"call")({...o,data:a,to:r});return z_({abi:n,args:i,functionName:s,data:t||"0x"})}catch(e){throw fN(e,{abi:n,address:r,args:i,docsPath:"/docs/contract/readContract",functionName:s})}}const qO=new Map,WO=new Map;let ZO=0;function KO(e,t,n){const r=++ZO,i=()=>qO.get(e)||[],s=()=>{const t=i();if(!t.some(e=>e.id===r))return;const n=WO.get(e);if(1===t.length&&n){const e=n();e instanceof Promise&&e.catch(()=>{})}(()=>{const t=i();qO.set(e,t.filter(e=>e.id!==r))})()},o=i();if(qO.set(e,[...o,{id:r,fns:t}]),o&&o.length>0)return s;const a={};for(const e in t)a[e]=(...t)=>{const n=i();if(0!==n.length)for(const r of n)r.fns[e]?.(...t)};const c=n(a);return"function"==typeof c&&WO.set(e,c),s}async function GO(e){return new Promise(t=>setTimeout(t,e))}function YO(e,{emitOnBegin:t,initialWaitTime:n,interval:r}){let i=!0;const s=()=>i=!1;return(async()=>{let o;t&&(o=await e({unpoll:s}));const a=await(n?.(o))??r;await GO(a);const c=async()=>{i&&(await e({unpoll:s}),await GO(r),c())};c()})(),s}const JO=new Map,QO=new Map;async function XO(e,{cacheKey:t,cacheTime:n=Number.POSITIVE_INFINITY}){const r=function(e){const t=(e,t)=>({clear:()=>t.delete(e),get:()=>t.get(e),set:n=>t.set(e,n)}),n=t(e,JO),r=t(e,QO);return{clear:()=>{n.clear(),r.clear()},promise:n,response:r}}(t),i=r.response.get();if(i&&n>0){if(Date.now()-i.created.getTime()<n)return i.data}let s=r.promise.get();s||(s=e(),r.promise.set(s));try{const e=await s;return r.response.set({created:new Date,data:e}),e}finally{r.promise.clear()}}async function e$(e,{cacheTime:t=e.cacheTime}={}){const n=await XO(()=>e.request({method:"eth_blockNumber"}),{cacheKey:(r=e.uid,`blockNumber.${r}`),cacheTime:t});var r;return BigInt(n)}async function t$(e,{filter:t}){const n="strict"in t&&t.strict,r=await t.request({method:"eth_getFilterChanges",params:[t.id]});if("string"==typeof r[0])return r;const i=r.map(e=>$_(e));return"abi"in t&&t.abi?U_({abi:t.abi,logs:i,strict:n}):i}async function n$(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function r$(e,{delay:t=100,retryCount:n=2,shouldRetry:r=()=>!0}={}){return new Promise((i,s)=>{const o=async({count:a=0}={})=>{try{const t=await e();i(t)}catch(e){if(a<n&&await r({count:a,error:e}))return(async({error:e})=>{const n="function"==typeof t?t({count:a,error:e}):t;n&&await GO(n),o({count:a+1})})({error:e});s(e)}};o()})}const i$={"0x0":"reverted","0x1":"success"};function s$(e,t){const n={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(e=>$_(e)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?pC(e.transactionIndex):null,status:e.status?i$[e.status]:null,type:e.type?GN[e.type]||e.type:null};return e.blobGasPrice&&(n.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(n.blobGasUsed=BigInt(e.blobGasUsed)),n}let o$,a$=256;function c$(e=11){if(!o$||a$+e>512){o$="",a$=0;for(let e=0;e<256;e++)o$+=(256+256*Math.random()|0).toString(16).substring(1)}return o$.substring(a$,a$+++e)}function l$(e){const{batch:t,chain:n,ccipRead:r,dataSuffix:i,key:s="base",name:o="Base Client",type:a="base"}=e,c=e.experimental_blockTag??("number"==typeof n?.experimental_preconfirmationTime?"pending":void 0),l=n?.blockTime??12e3,d=Math.min(Math.max(Math.floor(l/2),500),4e3),h=e.pollingInterval??d,u=e.cacheTime??h,p=e.account?FS(e.account):void 0,{config:f,request:g,value:m}=e.transport({account:p,chain:n,pollingInterval:h}),y={account:p,batch:t,cacheTime:u,ccipRead:r,chain:n,dataSuffix:i,key:s,name:o,pollingInterval:h,request:g,transport:{...f,...m},type:a,uid:c$(),...c?{experimental_blockTag:c}:{}};return Object.assign(y,{extend:function e(t){return n=>{const r=n(t);for(const e in y)delete r[e];const i={...t,...r};return Object.assign(i,{extend:e(i)})}}(y)})}function d$(e){if(!(e instanceof CI))return!1;const t=e.walk(e=>e instanceof TP);return t instanceof TP&&("HttpError"===t.data?.errorName||("ResolverError"===t.data?.errorName||("ResolverNotContract"===t.data?.errorName||("ResolverNotFound"===t.data?.errorName||("ReverseAddressMismatch"===t.data?.errorName||"UnsupportedResolverProfile"===t.data?.errorName)))))}function h$(e){const{abi:t,data:n}=e,r=kS(n,0,4),i=t.find(e=>"function"===e.type&&r===BS(bI(e)));if(!i)throw new VI(r,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:i.name,args:"inputs"in i&&i.inputs&&i.inputs.length>0?oP(i.inputs,kS(n,4)):void 0}}const u$="/docs/contract/encodeErrorResult";function p$(e){const{abi:t,errorName:n,args:r}=e;let i=t[0];if(n){const e=MS({abi:t,args:r,name:n});if(!e)throw new MI(n,{docsPath:u$});i=e}if("error"!==i.type)throw new MI(void 0,{docsPath:u$});const s=bI(i),o=BS(s);let a="0x";if(r&&r.length>0){if(!i.inputs)throw new BI(i.name,{docsPath:u$});a=TS(i.inputs,r)}return AS([o,a])}const f$="/docs/contract/encodeFunctionResult";function g$(e){const{abi:t,functionName:n,result:r}=e;let i=t[0];if(n){const e=MS({abi:t,name:n});if(!e)throw new zI(n,{docsPath:f$});i=e}if("function"!==i.type)throw new zI(void 0,{docsPath:f$});if(!i.outputs)throw new HI(i.name,{docsPath:f$});const s=(()=>{if(0===i.outputs.length)return[];if(1===i.outputs.length)return[r];if(Array.isArray(r))return r;throw new YI(r)})();return TS(i.outputs,s)}const m$="x-batch-gateway:true";async function y$(e){const{data:t,ccipRequest:n}=e,{args:[r]}=h$({abi:bO,data:t}),i=[],s=[];return await Promise.all(r.map(async(e,t)=>{try{s[t]=e.urls.includes(m$)?await y$({data:e.data,ccipRequest:n}):await n(e),i[t]=!1}catch(e){i[t]=!0,s[t]="HttpRequestError"===(r=e).name&&r.status?p$({abi:bO,errorName:"HttpError",args:[r.status,r.shortMessage]}):p$({abi:[GS],errorName:"Error",args:["shortMessage"in r?r.shortMessage:r.message]})}var r})),g$({abi:bO,functionName:"query",result:[i,s]})}function w$(e){if(66!==e.length)return null;if(0!==e.indexOf("["))return null;if(65!==e.indexOf("]"))return null;const t=`0x${e.slice(1,65)}`;return EI(t)?t:null}function b$(e){let t=new Uint8Array(32).fill(0);if(!e)return yC(t);const n=e.split(".");for(let e=n.length-1;e>=0;e-=1){const r=w$(n[e]),i=r?xC(r):cS(PC(n[e]),"bytes");t=cS(ES([t,i]),"bytes")}return yC(t)}function v$(e){return`[${e.slice(2)}]`}function E$(e){const t=new Uint8Array(32).fill(0);return e?w$(e)||cS(PC(e)):yC(t)}function x$(e){const t=e.replace(/^\.|\.$/gm,"");if(0===t.length)return new Uint8Array(1);const n=new Uint8Array(PC(t).byteLength+2);let r=0;const i=t.split(".");for(let e=0;e<i.length;e++){let t=PC(i[e]);t.byteLength>255&&(t=PC(v$(E$(i[e])))),n[r]=t.length,n.set(t,r+1),r+=t.length+1}return n.byteLength!==r+1?n.slice(0,r+1):n}class A$ extends CI{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class k$ extends CI{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class I$ extends CI{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class C$ extends CI{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const S$=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,P$=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,N$=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,_$=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;function T$(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function O$({uri:e,gatewayUrls:t}){const n=N$.test(e);if(n)return{uri:e,isOnChain:!0,isEncoded:n};const r=T$(t?.ipfs,"https://ipfs.io"),i=T$(t?.arweave,"https://arweave.net"),s=e.match(S$),{protocol:o,subpath:a,target:c,subtarget:l=""}=s?.groups||{},d="ipns:/"===o||"ipns/"===a,h="ipfs:/"===o||"ipfs/"===a||P$.test(e);if(e.startsWith("http")&&!d&&!h){let n=e;return t?.arweave&&(n=e.replace(/https:\/\/arweave.net/g,t?.arweave)),{uri:n,isOnChain:!1,isEncoded:!1}}if((d||h)&&c)return{uri:`${r}/${d?"ipns":"ipfs"}/${c}${l}`,isOnChain:!1,isEncoded:!1};if("ar:/"===o&&c)return{uri:`${i}/${c}${l||""}`,isOnChain:!1,isEncoded:!1};let u=e.replace(_$,"");if(u.startsWith("<svg")&&(u=`data:image/svg+xml;base64,${btoa(u)}`),u.startsWith("data:")||u.startsWith("{"))return{uri:u,isOnChain:!0,isEncoded:!1};throw new I$({uri:e})}function $$(e){if("object"!=typeof e||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new A$({data:e});return e.image||e.image_url||e.image_data}async function R$({gatewayUrls:e,uri:t}){const{uri:n,isOnChain:r}=O$({uri:t,gatewayUrls:e});if(r)return n;const i=await async function(e){try{const t=await fetch(e,{method:"HEAD"});if(200===t.status){const e=t.headers.get("content-type");return e?.startsWith("image/")}return!1}catch(t){return("object"!=typeof t||void 0===t.response)&&!!Object.hasOwn(globalThis,"Image")&&new Promise(t=>{const n=new Image;n.onload=()=>{t(!0)},n.onerror=()=>{t(!1)},n.src=e})}}(n);if(i)return n;throw new I$({uri:t})}async function B$(e,{gatewayUrls:t,record:n}){return/eip155:/i.test(n)?async function(e,{gatewayUrls:t,record:n}){const r=function(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[n,r,i]=t.split("/"),[s,o]=n.split(":"),[a,c]=r.split(":");if(!s||"eip155"!==s.toLowerCase())throw new k$({reason:"Only EIP-155 supported"});if(!o)throw new k$({reason:"Chain ID not found"});if(!c)throw new k$({reason:"Contract address not found"});if(!i)throw new k$({reason:"Token ID not found"});if(!a)throw new k$({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:i}}(n),i=await async function(e,{nft:t}){if("erc721"===t.namespace)return FO(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if("erc1155"===t.namespace)return FO(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new C$({namespace:t.namespace})}(e,{nft:r}),{uri:s,isOnChain:o,isEncoded:a}=O$({uri:i,gatewayUrls:t});if(o&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){const e=a?atob(s.replace("data:application/json;base64,","")):s;return R$({uri:$$(JSON.parse(e)),gatewayUrls:t})}let c=r.tokenID;"erc1155"===r.namespace&&(c=c.replace("0x","").padStart(64,"0"));return async function({gatewayUrls:e,uri:t}){try{const n=await fetch(t).then(e=>e.json());return await R$({gatewayUrls:e,uri:$$(n)})}catch{throw new I$({uri:t})}}({gatewayUrls:t,uri:s.replace(/(?:0x)?{id}/,c)})}(e,{gatewayUrls:t,record:n}):R$({uri:n,gatewayUrls:t})}async function M$(e,t){const{blockNumber:n,blockTag:r,key:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,l=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return UO({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(e=>s.endsWith(e)))return null;try{const t={address:l,abi:EO,args:[gC(x$(s)),ZS({abi:AO,functionName:"text",args:[b$(s),i]}),o??[m$]],functionName:"resolveWithGateways",blockNumber:n,blockTag:r},a=wI(e,FO,"readContract"),c=await a(t);if("0x"===c[0])return null;const d=z_({abi:AO,functionName:"text",data:c[0]});return""===d?null:d}catch(e){if(a)throw e;if(d$(e))return null;throw e}}async function U$(e,t){const{account:n=e.account,blockNumber:r,blockTag:i="latest",blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:d,maxPriorityFeePerGas:h,to:u,value:p,...f}=t,g=n?FS(n):void 0;try{FN(t);const n=("bigint"==typeof r?wC(r):void 0)||i,m=e.chain?.formatters?.transactionRequest?.format,y=(m||DN)({...UN(f,{format:m}),account:g,blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:d,maxPriorityFeePerGas:h,to:u,value:p},"createAccessList"),w=await e.request({method:"eth_createAccessList",params:[y,n]});return{accessList:w.accessList,gasUsed:BigInt(w.gasUsed)}}catch(n){throw LO(n,{...t,account:g,chain:e.chain})}}async function L$(e,{address:t,args:n,event:r,events:i,fromBlock:s,strict:o,toBlock:a}={}){const c=i??(r?[r]:void 0),l=HS(e,{method:"eth_newFilter"});let d=[];if(c){const e=c.flatMap(e=>jS({abi:[e],eventName:e.name,args:n}));d=[e],r&&(d=d[0])}const h=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:"bigint"==typeof s?wC(s):s,toBlock:"bigint"==typeof a?wC(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:n,eventName:r?r.name:void 0,fromBlock:s,id:h,request:l(h),strict:Boolean(o),toBlock:a,type:"event"}}async function D$(e){const t=HS(e,{method:"eth_newPendingTransactionFilter"}),n=await e.request({method:"eth_newPendingTransactionFilter"});return{id:n,request:t(n),type:"transaction"}}async function j$(e,{address:t,blockNumber:n,blockTag:r="latest"}){const i=void 0!==n?wC(n):void 0,s=await e.request({method:"eth_getCode",params:[t,i||r]},{dedupe:Boolean(i)});if("0x"!==s)return s}class z$ extends CI{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}const H$=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];async function V$(e,{blockCount:t,blockNumber:n,blockTag:r="latest",rewardPercentiles:i}){const s="bigint"==typeof n?wC(n):void 0;return function(e){return{baseFeePerGas:e.baseFeePerGas.map(e=>BigInt(e)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map(e=>e.map(e=>BigInt(e)))}}(await e.request({method:"eth_feeHistory",params:[wC(t),s||r,i]},{dedupe:Boolean(s)}))}const F$=new fS(8192);function q$(e,t={}){return async(n,r={})=>{const{dedupe:i=!1,methods:s,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...r},{method:l}=n;if(s?.exclude?.includes(l))throw new GP(new Error("method not supported"),{method:l});if(s?.include&&!s.include.includes(l))throw new GP(new Error("method not supported"),{method:l});return function(e,{enabled:t=!0,id:n}){if(!t||!n)return e();if(F$.get(n))return F$.get(n);const r=e().finally(()=>F$.delete(n));return F$.set(n,r),r}(()=>r$(async()=>{try{return await e(n)}catch(e){const t=e;switch(t.code){case jP.code:throw new jP(t);case zP.code:throw new zP(t);case HP.code:throw new HP(t,{method:n.method});case VP.code:throw new VP(t);case FP.code:throw new FP(t);case qP.code:throw new qP(t);case WP.code:throw new WP(t);case ZP.code:throw new ZP(t);case KP.code:throw new KP(t);case GP.code:throw new GP(t,{method:n.method});case YP.code:throw new YP(t);case JP.code:throw new JP(t);case QP.code:throw new QP(t);case XP.code:throw new XP(t);case eN.code:throw new eN(t);case tN.code:throw new tN(t);case nN.code:throw new nN(t);case rN.code:throw new rN(t);case iN.code:throw new iN(t);case sN.code:throw new sN(t);case oN.code:throw new oN(t);case aN.code:throw new aN(t);case cN.code:throw new cN(t);case lN.code:throw new lN(t);case dN.code:throw new dN(t);case 5e3:throw new QP(t);case hN.code:throw new hN(t);default:if(e instanceof CI)throw e;throw new uN(t)}}},{delay:({count:e,error:t})=>{if(t&&t instanceof BP){const e=t?.headers?.get("Retry-After");if(e?.match(/\d/))return 1e3*Number.parseInt(e,10)}return(1<<e)*o},retryCount:a,shouldRetry:({error:e})=>function(e){if("code"in e&&"number"==typeof e.code)return-1===e.code||(e.code===YP.code||e.code===FP.code);if(e instanceof BP&&e.status)return 403===e.status||(408===e.status||(413===e.status||(429===e.status||(500===e.status||(502===e.status||(503===e.status||504===e.status))))));return!0}(e)}),{enabled:i,id:i?vC(`${c}.${uP(n)}`):void 0})}}class W$ extends CI{constructor({callbackSelector:e,cause:t,data:n,extraData:r,sender:i,urls:s}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",s&&[" Gateway URL(s):",...s.map(e=>` ${e}`)],` Sender: ${i}`,` Data: ${n}`,` Callback selector: ${e}`,` Extra data: ${r}`].flat(),name:"OffchainLookupError"})}}class Z$ extends CI{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${t}`,`Response: ${uP(e)}`],name:"OffchainLookupResponseMalformedError"})}}class K$ extends CI{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}const G$="0x556f1830",Y$={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function J$(e,{blockNumber:t,blockTag:n,data:r,to:i}){const{args:s}=hP({data:r,abi:[Y$]}),[o,a,c,l,d]=s,{ccipRead:h}=e,u=h&&"function"==typeof h?.request?h.request:Q$;try{if(!O_(i,o))throw new K$({sender:o,to:i});const r=a.includes(m$)?await y$({data:c,ccipRequest:u}):await u({data:c,sender:o,urls:a}),{data:s}=await HO(e,{blockNumber:t,blockTag:n,data:ES([l,TS([{type:"bytes"},{type:"bytes"}],[r,d])]),to:i});return s}catch(e){throw new W$({callbackSelector:l,cause:e,data:r,extraData:d,sender:o,urls:a})}}async function Q$({data:e,sender:t,urls:n}){let r=new Error("An unknown error occurred.");for(let i=0;i<n.length;i++){const s=n[i],o=s.includes("{data}")?"GET":"POST",a="POST"===o?{data:e,sender:t}:void 0,c="POST"===o?{"Content-Type":"application/json"}:{};try{const n=await fetch(s.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(a),headers:c,method:o});let i;if(i=n.headers.get("Content-Type")?.startsWith("application/json")?(await n.json()).data:await n.text(),!n.ok){r=new BP({body:a,details:i?.error?uP(i.error):n.statusText,headers:n.headers,status:n.status,url:s});continue}if(!EI(i)){r=new Z$({result:i,url:s});continue}return i}catch(e){r=new BP({body:a,details:e.message,url:s})}}throw r}var X$=Object.freeze({__proto__:null,ccipRequest:Q$,offchainLookup:J$,offchainLookupAbiItem:Y$,offchainLookupSignature:G$});function eR(e,{errorInstance:t=new Error("timed out"),timeout:n,signal:r}){return new Promise((i,s)=>{(async()=>{let o;try{const t=new AbortController;n>0&&(o=setTimeout(()=>{r&&t.abort()},n)),i(await e({signal:t?.signal||null}))}catch(e){"AbortError"===e?.name&&s(t),s(e)}finally{clearTimeout(o)}})()})}function tR(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const nR=tR();function rR(e,t={}){const{url:n,headers:r}=function(e){try{const t=new URL(e),n=(()=>{if(t.username){const e=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(e)}`}}}})();return{url:t.toString(),...n}}catch{return{url:e}}}(e);return{async request(e){const{body:i,fetchFn:s=t.fetchFn??fetch,onRequest:o=t.onRequest,onResponse:a=t.onResponse,timeout:c=t.timeout??1e4}=e,l={...t.fetchOptions??{},...e.fetchOptions??{}},{headers:d,method:h,signal:u}=l;try{const e=await eR(async({signal:e})=>{const t={...l,body:Array.isArray(i)?uP(i.map(e=>({jsonrpc:"2.0",id:e.id??nR.take(),...e}))):uP({jsonrpc:"2.0",id:i.id??nR.take(),...i}),headers:{...r,"Content-Type":"application/json",...d},method:h||"POST",signal:u||(c>0?e:null)},a=new Request(n,t),p=await(o?.(a,t))??{...t,url:n};return await s(p.url??n,p)},{errorInstance:new UP({body:i,url:n}),timeout:c,signal:!0});let t;if(a&&await a(e),e.headers.get("Content-Type")?.startsWith("application/json"))t=await e.json();else{t=await e.text();try{t=JSON.parse(t||"{}")}catch(n){if(e.ok)throw n;t={error:t}}}if(!e.ok){if("number"==typeof t.error?.code&&"string"==typeof t.error?.message)return t;throw new BP({body:i,details:uP(t.error)||e.statusText,headers:e.headers,status:e.status,url:n})}return t}catch(e){if(e instanceof BP)throw e;if(e instanceof UP)throw e;throw new BP({body:i,cause:e,url:n})}}}}const iR="Ethereum Signed Message:\n";function sR(e){const t="string"==typeof e?vC(e):"string"==typeof e.raw?e.raw:yC(e.raw);return ES([vC(`${iR}${xI(t)}`),t])}function oR(e,t){return cS(sR(e),t)}class aR extends CI{constructor({domain:e}){super(`Invalid domain "${uP(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class cR extends CI{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class lR extends CI{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function dR(e){const{domain:t,message:n,primaryType:r,types:i}=e,s=(e,t)=>{for(const n of e){const{name:e,type:r}=n,o=t[e],a=r.match(_S);if(a&&("number"==typeof o||"bigint"==typeof o)){const[e,t,n]=a;wC(o,{signed:"int"===t,size:Number.parseInt(n,10)/8})}if("address"===r&&"string"==typeof o&&!vS(o))throw new pS({address:o});const c=r.match(NS);if(c){const[e,t]=c;if(t&&xI(o)!==Number.parseInt(t,10))throw new qI({expectedSize:Number.parseInt(t,10),givenSize:xI(o)})}const l=i[r];l&&(uR(r),s(l,o))}};if(i.EIP712Domain&&t){if("object"!=typeof t)throw new aR({domain:t});s(i.EIP712Domain,t)}if("EIP712Domain"!==r){if(!i[r])throw new cR({primaryType:r,types:i});s(i[r],n)}}function hR({domain:e}){return["string"==typeof e?.name&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},("number"==typeof e?.chainId||"bigint"==typeof e?.chainId)&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function uR(e){if("address"===e||"bool"===e||"string"===e||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new lR({type:e})}function pR(e){const{domain:t={},message:n,primaryType:r}=e,i={EIP712Domain:hR({domain:t}),...e.types};dR({domain:t,message:n,primaryType:r,types:i});const s=["0x1901"];return t&&s.push(fR({domain:t,types:i})),"EIP712Domain"!==r&&s.push(gR({data:n,primaryType:r,types:i})),cS(ES(s))}function fR({domain:e,types:t}){return gR({data:e,primaryType:"EIP712Domain",types:t})}function gR({data:e,primaryType:t,types:n}){return cS(mR({data:e,primaryType:t,types:n}))}function mR({data:e,primaryType:t,types:n}){const r=[{type:"bytes32"}],i=[yR({primaryType:t,types:n})];for(const s of n[t]){const[t,o]=bR({types:n,name:s.name,type:s.type,value:e[s.name]});r.push(t),i.push(o)}return TS(r,i)}function yR({primaryType:e,types:t}){const n=gC(function({primaryType:e,types:t}){let n="";const r=wR({primaryType:e,types:t});r.delete(e);const i=[e,...Array.from(r).sort()];for(const e of i)n+=`${e}(${t[e].map(({name:e,type:t})=>`${t} ${e}`).join(",")})`;return n}({primaryType:e,types:t}));return cS(n)}function wR({primaryType:e,types:t},n=new Set){const r=e.match(/^\w*/u),i=r?.[0];if(n.has(i)||void 0===t[i])return n;n.add(i);for(const e of t[i])wR({primaryType:e.type,types:t},n);return n}function bR({types:e,name:t,type:n,value:r}){if(void 0!==e[n])return[{type:"bytes32"},cS(mR({data:r,primaryType:n,types:e}))];if("bytes"===n)return[{type:"bytes32"},cS(r)];if("string"===n)return[{type:"bytes32"},cS(gC(r))];if(n.lastIndexOf("]")===n.length-1){const i=n.slice(0,n.lastIndexOf("[")),s=r.map(n=>bR({name:t,type:i,types:e,value:n}));return[{type:"bytes32"},cS(TS(s.map(([e])=>e),s.map(([,e])=>e)))]}return[{type:n},r]}let vR=class 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)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}};const ER={checksum:new vR(8192)}.checksum;let xR=class extends VC{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");$C(e.outputLen),$C(e.blockLen)}(e);const n=HC(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),UC(i)}update(e){return BC(this),this.iHash.update(e),this}digestInto(e){BC(this),RC(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:n,finished:r,destroyed:i,blockLen:s,outputLen:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const AR=(e,t,n)=>new xR(e,t).update(n).digest();function kR(e,t={}){const{as:n=("string"==typeof e?"Hex":"Bytes")}=t,r=aS(UT(e));return"Bytes"===n?r:eO(r)}AR.create=(e,t)=>new xR(e,t);const IR=/^0x[a-fA-F0-9]{40}$/;function CR(e,t={}){const{strict:n=!0}=t;if(!IR.test(e))throw new NR({address:e,cause:new _R});if(n){if(e.toLowerCase()===e)return;if(SR(e)!==e)throw new NR({address:e,cause:new TR})}}function SR(e){if(ER.has(e))return ER.get(e);CR(e,{strict:!1});const t=e.substring(2).toLowerCase(),n=kR(DT(t),{as:"Bytes"}),r=t.split("");for(let e=0;e<40;e+=2)n[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&n[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());const i=`0x${r.join("")}`;return ER.set(e,i),i}function PR(e,t={}){const{strict:n=!0}=t??{};try{return CR(e,{strict:n}),!0}catch{return!1}}let NR=class extends ET{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},_R=class extends ET{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},TR=class extends ET{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}};const OR=/^(.*)\[([0-9]*)\]$/,$R=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,RR=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,BR=2n**256n-1n;function MR(e,t,n){const{checksumAddress:r,staticPosition:i}=n,s=zR(t.type);if(s){const[n,o]=s;return function(e,t,n){const{checksumAddress:r,length:i,staticPosition:s}=n;if(!i){const n=s+FT(e.readBytes(LR)),i=n+UR;e.setPosition(n);const o=FT(e.readBytes(UR)),a=HR(t);let c=0;const l=[];for(let n=0;n<o;++n){e.setPosition(i+(a?32*n:c));const[s,o]=MR(e,t,{checksumAddress:r,staticPosition:i});c+=o,l.push(s)}return e.setPosition(s+32),[l,32]}if(HR(t)){const n=s+FT(e.readBytes(LR)),o=[];for(let s=0;s<i;++s){e.setPosition(n+32*s);const[i]=MR(e,t,{checksumAddress:r,staticPosition:n});o.push(i)}return e.setPosition(s+32),[o,32]}let o=0;const a=[];for(let n=0;n<i;++n){const[n,i]=MR(e,t,{checksumAddress:r,staticPosition:s+o});o+=i,a.push(n)}return[a,o]}(e,{...t,type:o},{checksumAddress:r,length:n,staticPosition:i})}if("tuple"===t.type)return function(e,t,n){const{checksumAddress:r,staticPosition:i}=n,s=0===t.components.length||t.components.some(({name:e})=>!e),o=s?[]:{};let a=0;if(HR(t)){const n=i+FT(e.readBytes(LR));for(let i=0;i<t.components.length;++i){const c=t.components[i];e.setPosition(n+a);const[l,d]=MR(e,c,{checksumAddress:r,staticPosition:n});a+=d,o[s?i:c?.name]=l}return e.setPosition(i+32),[o,32]}for(let n=0;n<t.components.length;++n){const c=t.components[n],[l,d]=MR(e,c,{checksumAddress:r,staticPosition:i});o[s?n:c?.name]=l,a+=d}return[o,a]}(e,t,{checksumAddress:r,staticPosition:i});if("address"===t.type)return function(e,t={}){const{checksum:n=!1}=t,r=e.readBytes(32),i=e=>n?SR(e):e;return[i(eO(zT(r,-20))),32]}(e,{checksum:r});if("bool"===t.type)return function(e){return[VT(e.readBytes(32),{size:32}),32]}(e);if(t.type.startsWith("bytes"))return function(e,t,{staticPosition:n}){const[r,i]=t.type.split("bytes");if(!i){const t=FT(e.readBytes(32));e.setPosition(n+t);const r=FT(e.readBytes(32));if(0===r)return e.setPosition(n+32),["0x",32];const i=e.readBytes(r);return e.setPosition(n+32),[eO(i),32]}const s=eO(e.readBytes(Number.parseInt(i,10),32));return[s,32]}(e,t,{staticPosition:i});if(t.type.startsWith("uint")||t.type.startsWith("int"))return function(e,t){const n=t.type.startsWith("int"),r=Number.parseInt(t.type.split("int")[1]||"256",10),i=e.readBytes(32);return[r>48?HT(i,{signed:n}):FT(i,{signed:n}),32]}(e,t);if("string"===t.type)return function(e,{staticPosition:t}){const n=FT(e.readBytes(32)),r=t+n;e.setPosition(r);const i=FT(e.readBytes(32));if(0===i)return e.setPosition(t+32),["",32];const s=e.readBytes(i,32),o=qT(WT(s));return e.setPosition(t+32),[o,32]}(e,{staticPosition:i});throw new rB(t.type)}const UR=32,LR=32;function DR({checksumAddress:e=!1,parameter:t,value:n}){const r=t,i=zR(r.type);if(i){const[t,s]=i;return function(e,t){const{checksumAddress:n,length:r,parameter:i}=t,s=null===r;if(!Array.isArray(e))throw new nB(e);if(!s&&e.length!==r)throw new XR({expectedLength:r,givenLength:e.length,type:`${i.type}[${r}]`});let o=!1;const a=[];for(let t=0;t<e.length;t++){const r=DR({checksumAddress:n,parameter:i,value:e[t]});r.dynamic&&(o=!0),a.push(r)}if(s||o){const e=jR(a);if(s){const t=tO(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?QT(t,e):t}}if(o)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:QT(...a.map(({encoded:e})=>e))}}(n,{checksumAddress:e,length:t,parameter:{...r,type:s}})}if("tuple"===r.type)return function(e,t){const{checksumAddress:n,parameter:r}=t;let i=!1;const s=[];for(let t=0;t<r.components.length;t++){const o=r.components[t],a=DR({checksumAddress:n,parameter:o,value:e[Array.isArray(e)?t:o.name]});s.push(a),a.dynamic&&(i=!0)}return{dynamic:i,encoded:i?jR(s):QT(...s.map(({encoded:e})=>e))}}(n,{checksumAddress:e,parameter:r});if("address"===r.type)return function(e,t){const{checksum:n=!1}=t;return CR(e,{strict:n}),{dynamic:!1,encoded:rO(e.toLowerCase())}}(n,{checksum:e});if("bool"===r.type)return function(e){if("boolean"!=typeof e)throw new ET(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:rO(XT(e))}}(n);if(r.type.startsWith("uint")||r.type.startsWith("int")){const e=r.type.startsWith("int"),[,,t="256"]=RR.exec(r.type)??[];return function(e,{signed:t,size:n}){if("number"==typeof n){const r=2n**(BigInt(n)-(t?1n:0n))-1n,i=t?-r-1n:0n;if(e>r||e<i)throw new dO({max:r.toString(),min:i.toString(),signed:t,size:n/8,value:e.toString()})}return{dynamic:!1,encoded:tO(e,{size:32,signed:t})}}(n,{signed:e,size:Number(t)})}if(r.type.startsWith("bytes"))return function(e,{type:t}){const[,n]=t.split("bytes"),r=oO(e);if(!n){let t=e;return r%32!=0&&(t=iO(t,32*Math.ceil((e.length-2)/2/32))),{dynamic:!0,encoded:QT(rO(tO(r,{size:32})),t)}}if(r!==Number.parseInt(n,10))throw new eB({expectedSize:Number.parseInt(n,10),value:e});return{dynamic:!1,encoded:iO(e)}}(n,{type:r.type});if("string"===r.type)return function(e){const t=nO(e),n=Math.ceil(oO(t)/32),r=[];for(let e=0;e<n;e++)r.push(iO(sO(t,32*e,32*(e+1))));return{dynamic:!0,encoded:QT(iO(tO(oO(t),{size:32})),...r)}}(n);throw new rB(r.type)}function jR(e){let t=0;for(let n=0;n<e.length;n++){const{dynamic:r,encoded:i}=e[n];t+=r?32:oO(i)}const n=[],r=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(n.push(tO(t+i,{size:32})),r.push(a),i+=oO(a)):n.push(a)}return QT(...n,...r)}function zR(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function HR(e){const{type:t}=e;if("string"===t)return!0;if("bytes"===t)return!0;if(t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(HR);const n=zR(e.type);return!(!n||!HR({...e,type:n[1]}))}const VR={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new WR({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new qR({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new FR({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new FR({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const n=this.inspectBytes(e);return this.position+=t??e,n},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};class FR extends ET{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class qR extends ET{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class WR extends ET{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function ZR(e,t,n={}){const{as:r="Array",checksumAddress:i=!1}=n,s="string"==typeof t?LT(t):t,o=function(e,{recursiveReadLimit:t=8192}={}){const n=Object.create(VR);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}(s);if(0===jT(s)&&e.length>0)throw new QR;if(jT(s)&&jT(s)<32)throw new JR({data:"string"==typeof t?t:eO(t),parameters:e,size:jT(s)});let a=0;const c="Array"===r?[]:{};for(let t=0;t<e.length;++t){const n=e[t];o.setPosition(a);const[s,l]=MR(o,n,{checksumAddress:i,staticPosition:0});a+=l,"Array"===r?c.push(s):c[n.name??t]=s}return c}function KR(e,t,n){const{checksumAddress:r=!1}={};if(e.length!==t.length)throw new tB({expectedLength:e.length,givenLength:t.length});const i=function({checksumAddress:e,parameters:t,values:n}){const r=[];for(let i=0;i<t.length;i++)r.push(DR({checksumAddress:e,parameter:t[i],value:n[i]}));return r}({checksumAddress:r,parameters:e,values:t}),s=jR(i);return 0===s.length?"0x":s}function GR(e,t){if(e.length!==t.length)throw new tB({expectedLength:e.length,givenLength:t.length});const n=[];for(let r=0;r<e.length;r++){const i=e[r],s=t[r];n.push(GR.encode(i,s))}return QT(...n)}function YR(e){return Array.isArray(e)&&"string"==typeof e[0]||"string"==typeof e?yI(e):e}!function(e){e.encode=function e(t,n,r=!1){if("address"===t){const e=n;return CR(e),rO(e.toLowerCase(),r?32:0)}if("string"===t)return nO(n);if("bytes"===t)return n;if("bool"===t)return rO(XT(n),r?32:1);const i=t.match(RR);if(i){const[e,t,s="256"]=i,o=Number.parseInt(s,10)/8;return tO(n,{size:r?32:o,signed:"int"===t})}const s=t.match($R);if(s){const[e,t]=s;if(Number.parseInt(t,10)!==(n.length-2)/2)throw new eB({expectedSize:Number.parseInt(t,10),value:n});return iO(n,r?32:0)}const o=t.match(OR);if(o&&Array.isArray(n)){const[t,r]=o,i=[];for(let t=0;t<n.length;t++)i.push(e(r,n[t],!0));return 0===i.length?"0x":QT(...i)}throw new rB(t)}}(GR||(GR={}));class JR extends ET{constructor({data:e,parameters:t,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Nk(t)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class QR extends ET{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class XR extends ET{constructor({expectedLength:e,givenLength:t,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class eB extends ET{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${oO(t)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class tB extends ET{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join("\n")),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}let nB=class extends ET{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}};class rB extends ET{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}
|