@walletconnect/ethereum-provider 2.20.0 → 2.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -36,7 +36,7 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(yR(r)).toStr
36
36
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
37
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
38
  PERFORMANCE OF THIS SOFTWARE.
39
- ***************************************************************************** */var ww=function(t,e){return ww=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},ww(t,e)};function UL(t,e){ww(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var mw=function(){return mw=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},mw.apply(this,arguments)};function LL(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function FL(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function ML(t,e){return function(r,n){e(r,n,t)}}function jL(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function zL(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(d){o(d)}}function c(u){try{l(n.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function qL(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function HL(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function WL(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function bw(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function n6(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function VL(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(n6(arguments[e]));return t}function KL(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Ru(t){return this instanceof Ru?(this.v=t,this):new Ru(t)}function GL(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(f){return new Promise(function(g,w){s.push([h,f,g,w])>1||a(h,f)})})}function a(h,f){try{c(n[h](f))}catch(g){d(s[0][3],g)}}function c(h){h.value instanceof Ru?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function ZL(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Ru(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function YL(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof bw=="function"?bw(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function JL(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function XL(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function QL(t){return t&&t.__esModule?t:{default:t}}function eF(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function tF(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rF=Object.freeze({__proto__:null,__extends:UL,get __assign(){return mw},__rest:LL,__decorate:FL,__param:ML,__metadata:jL,__awaiter:zL,__generator:qL,__createBinding:HL,__exportStar:WL,__values:bw,__read:n6,__spread:VL,__spreadArrays:KL,__await:Ru,__asyncGenerator:GL,__asyncDelegator:ZL,__asyncValues:YL,__makeTemplateObject:JL,__importStar:XL,__importDefault:QL,__classPrivateFieldGet:eF,__classPrivateFieldSet:tF}),nF=h2(rF),ts={},i6;function iF(){if(i6)return ts;i6=1,Object.defineProperty(ts,"__esModule",{value:!0}),ts.isBrowserCryptoAvailable=ts.getSubtleCrypto=ts.getBrowerCrypto=void 0;function t(){return zt?.crypto||zt?.msCrypto||{}}ts.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}ts.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return ts.isBrowserCryptoAvailable=r,ts}var rs={},s6;function sF(){if(s6)return rs;s6=1,Object.defineProperty(rs,"__esModule",{value:!0}),rs.isBrowser=rs.isNode=rs.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}rs.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}rs.isNode=e;function r(){return!t()&&!e()}return rs.isBrowser=r,rs}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=nF;e.__exportStar(iF(),t),e.__exportStar(sF(),t)})(r6);function Zt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function un(t=6){return BigInt(Zt(t))}function Nr(t,e,r){return{id:r||Zt(),jsonrpc:"2.0",method:t,params:e}}function Zs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function bc(t,e,r){return{id:t,jsonrpc:"2.0",error:oF(e,r)}}function oF(t,e){return typeof t>"u"?e6(X4):(typeof t=="string"&&(t=Object.assign(Object.assign({},e6(gw)),{message:t})),typeof e<"u"&&(t.data=e),DL(t.code)&&(t=BL(t.code)),t)}class aF{}class cF extends aF{constructor(){super()}}class lF extends cF{constructor(e){super()}}const uF="^https?:",dF="^wss?:";function hF(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function o6(t,e){const r=hF(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function a6(t){return o6(t,uF)}function c6(t){return o6(t,dF)}function pF(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function l6(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function yc(t){return l6(t)&&"method"in t}function jo(t){return l6(t)&&(Dt(t)||Et(t))}function Dt(t){return"result"in t}function Et(t){return"error"in t}class bt extends lF{constructor(e){super(e),this.events=new nt.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Nr(e.method,e.params||[],e.id||un().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Et(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),jo(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const fF=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),gF=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",u6=t=>t.split("?")[0],d6=10,wF=fF();class h6{constructor(e){if(this.url=e,this.events=new nt.exports.EventEmitter,this.registering=!1,!c6(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(wi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!c6(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=r6.isReactNative()?void 0:{rejectUnauthorized:!pF(e)},s=new wF(e,[],i);gF()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Wi(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=bc(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return t6(e,u6(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>d6&&this.events.setMaxListeners(d6)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${u6(this.url)}`));return this.events.emit("register_error",r),r}}var mF=Object.defineProperty,p6=Object.getOwnPropertySymbols,bF=Object.prototype.hasOwnProperty,yF=Object.prototype.propertyIsEnumerable,f6=(t,e,r)=>e in t?mF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e)=>{for(var r in e||(e={}))bF.call(e,r)&&f6(t,r,e[r]);if(p6)for(var r of p6(e))yF.call(e,r)&&f6(t,r,e[r]);return t};const g6="wc",w6=2,zp="core",Ci=`${g6}@2:${zp}:`,vF={name:zp,logger:"error"},EF={database:":memory:"},CF="crypto",m6="client_ed25519_seed",xF=z.ONE_DAY,$F="keychain",_F="0.3",IF="messages",SF="0.3",b6=z.SIX_HOURS,AF="publisher",y6="irn",PF="error",v6="wss://relay.walletconnect.org",OF="relayer",Yt={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},NF="_subscription",On={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},TF=.1,yw="2.19.2",gt={link_mode:"link_mode",relay:"relay"},qp={inbound:"inbound",outbound:"outbound"},kF="0.3",RF="WALLETCONNECT_CLIENT_ID",E6="WALLETCONNECT_LINK_MODE_APPS",dn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},DF="subscription",BF="0.3",UF="pairing",LF="0.3",Du={wc_pairingDelete:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:z.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:z.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:z.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:z.ONE_DAY,prompt:!1,tag:0},res:{ttl:z.ONE_DAY,prompt:!1,tag:0}}},zo={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Qn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},FF="history",MF="0.3",jF="expirer",Nn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},zF="0.3",qF="verify-api",HF="https://verify.walletconnect.com",C6="https://verify.walletconnect.org",Bu=C6,WF=`${Bu}/v3`,VF=[HF,C6],KF="echo",GF="https://echo.walletconnect.com",xi={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},ns={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},ei={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},qo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ho={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Uu={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},ZF=.1,YF="event-client",JF=86400,XF="https://pulse.walletconnect.org/batch";function QF(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,p=0,b=0,m=g.length;b!==m&&g[b]===0;)b++,w++;for(var E=(m-b)*u+1>>>0,C=new Uint8Array(E);b!==m;){for(var P=g[b],S=0,I=E-1;(P!==0||S<p)&&I!==-1;I--,S++)P+=256*C[I]>>>0,C[I]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");p=S,b++}for(var N=E-p;N!==E&&C[N]===0;)N++;for(var $=c.repeat(w);N<E;++N)$+=t.charAt(C[N]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var p=0,b=0;g[w]===c;)p++,w++;for(var m=(g.length-w)*l+1>>>0,E=new Uint8Array(m);g[w];){var C=r[g.charCodeAt(w)];if(C===255)return;for(var P=0,S=m-1;(C!==0||P<b)&&S!==-1;S--,P++)C+=a*E[S]>>>0,E[S]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");b=P,w++}if(g[w]!==" "){for(var I=m-b;I!==m&&E[I]===0;)I++;for(var N=new Uint8Array(p+(m-I)),$=p;I!==m;)N[$++]=E[I++];return N}}}function f(g){var w=h(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var eM=QF,tM=eM;const x6=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},rM=t=>new TextEncoder().encode(t),nM=t=>new TextDecoder().decode(t);class iM{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class sM{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return $6(this,e)}}class oM{constructor(e){this.decoders=e}or(e){return $6(this,e)}decode(e){const r=e[0],n=this.decoders[r];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 $6=(t,e)=>new oM(Tr(Tr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class aM{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new iM(e,r,n),this.decoder=new sM(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Hp=({name:t,prefix:e,encode:r,decode:n})=>new aM(t,e,r,n),Lu=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=tM(r,e);return Hp({prefix:t,name:e,encode:n,decode:s=>x6(i(s))})},cM=(t,e,r,n)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},lM=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},dr=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Hp({prefix:e,name:t,encode(i){return lM(i,n,r)},decode(i){return cM(i,n,r,t)}}),uM=Hp({prefix:"\0",name:"identity",encode:t=>nM(t),decode:t=>rM(t)});var dM=Object.freeze({__proto__:null,identity:uM});const hM=dr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pM=Object.freeze({__proto__:null,base2:hM});const fM=dr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gM=Object.freeze({__proto__:null,base8:fM});const wM=Lu({prefix:"9",name:"base10",alphabet:"0123456789"});var mM=Object.freeze({__proto__:null,base10:wM});const bM=dr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yM=dr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vM=Object.freeze({__proto__:null,base16:bM,base16upper:yM});const EM=dr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),CM=dr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xM=dr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$M=dr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_M=dr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),IM=dr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),SM=dr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),AM=dr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PM=dr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var OM=Object.freeze({__proto__:null,base32:EM,base32upper:CM,base32pad:xM,base32padupper:$M,base32hex:_M,base32hexupper:IM,base32hexpad:SM,base32hexpadupper:AM,base32z:PM});const NM=Lu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),TM=Lu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var kM=Object.freeze({__proto__:null,base36:NM,base36upper:TM});const RM=Lu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),DM=Lu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var BM=Object.freeze({__proto__:null,base58btc:RM,base58flickr:DM});const UM=dr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),LM=dr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),FM=dr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),MM=dr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jM=Object.freeze({__proto__:null,base64:UM,base64pad:LM,base64url:FM,base64urlpad:MM});const _6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),zM=_6.reduce((t,e,r)=>(t[r]=e,t),[]),qM=_6.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function HM(t){return t.reduce((e,r)=>(e+=zM[r],e),"")}function WM(t){const e=[];for(const r of t){const n=qM[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const VM=Hp({prefix:"\u{1F680}",name:"base256emoji",encode:HM,decode:WM});var KM=Object.freeze({__proto__:null,base256emoji:VM}),GM=S6,I6=128,ZM=127,YM=~ZM,JM=Math.pow(2,31);function S6(t,e,r){e=e||[],r=r||0;for(var n=r;t>=JM;)e[r++]=t&255|I6,t/=128;for(;t&YM;)e[r++]=t&255|I6,t>>>=7;return e[r]=t|0,S6.bytes=r-n+1,e}var XM=vw,QM=128,A6=127;function vw(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw vw.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&A6)<<i:(o&A6)*Math.pow(2,i),i+=7}while(o>=QM);return vw.bytes=s-n,r}var ej=Math.pow(2,7),tj=Math.pow(2,14),rj=Math.pow(2,21),nj=Math.pow(2,28),ij=Math.pow(2,35),sj=Math.pow(2,42),oj=Math.pow(2,49),aj=Math.pow(2,56),cj=Math.pow(2,63),lj=function(t){return t<ej?1:t<tj?2:t<rj?3:t<nj?4:t<ij?5:t<sj?6:t<oj?7:t<aj?8:t<cj?9:10},uj={encode:GM,decode:XM,encodingLength:lj},P6=uj;const O6=(t,e,r=0)=>(P6.encode(t,e,r),e),N6=t=>P6.encodingLength(t),Ew=(t,e)=>{const r=e.byteLength,n=N6(t),i=n+N6(r),s=new Uint8Array(i+r);return O6(t,s,0),O6(r,s,n),s.set(e,i),new dj(t,r,e,s)};class dj{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const T6=({name:t,code:e,encode:r})=>new hj(t,e,r);class hj{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ew(this.code,r):r.then(n=>Ew(this.code,n))}else throw Error("Unknown type, must be binary type")}}const k6=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),pj=T6({name:"sha2-256",code:18,encode:k6("SHA-256")}),fj=T6({name:"sha2-512",code:19,encode:k6("SHA-512")});var gj=Object.freeze({__proto__:null,sha256:pj,sha512:fj});const R6=0,wj="identity",D6=x6;var mj=Object.freeze({__proto__:null,identity:{code:R6,name:wj,encode:D6,digest:t=>Ew(R6,D6(t))}});new TextEncoder,new TextDecoder;const B6=Tr(Tr(Tr(Tr(Tr(Tr(Tr(Tr(Tr(Tr({},dM),pM),gM),mM),vM),OM),kM),BM),jM),KM);Tr(Tr({},gj),mj);function bj(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function U6(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const L6=U6("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cw=U6("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=bj(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yj=Tr({utf8:L6,"utf-8":L6,hex:B6.base16,latin1:Cw,ascii:Cw,binary:Cw},B6);function vj(t,e="utf8"){const r=yj[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var Ej=Object.defineProperty,Cj=(t,e,r)=>e in t?Ej(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$i=(t,e,r)=>Cj(t,typeof e!="symbol"?e+"":e,r);class xj{constructor(e,r){this.core=e,this.logger=r,$i(this,"keychain",new Map),$i(this,"name",$F),$i(this,"version",_F),$i(this,"initialized",!1),$i(this,"storagePrefix",Ci),$i(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),$i(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),$i(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),$i(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=J("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),$i(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=We(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ag(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $j=Object.defineProperty,_j=(t,e,r)=>e in t?$j(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hr=(t,e,r)=>_j(t,typeof e!="symbol"?e+"":e,r);class Ij{constructor(e,r,n){this.core=e,this.logger=r,hr(this,"name",CF),hr(this,"keychain"),hr(this,"randomSessionIdentifier",nw()),hr(this,"initialized",!1),hr(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),hr(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),hr(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=gp(i);return xg(s.publicKey)}),hr(this,"generateKeyPair",()=>{this.isInitialized();const i=lB();return this.setPrivateKey(i.publicKey,i.privateKey)}),hr(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=gp(s),a=this.randomSessionIdentifier;return await F3(a,i,xF,o)}),hr(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=uB(a,s);return this.setSymKey(c,o)}),hr(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Pp(i);return await this.keychain.set(o,i),o}),hr(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),hr(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),hr(this,"encode",async(i,s,o)=>{this.isInitialized();const a=x4(o),c=wi(s);if(_4(a))return pB(c,o?.encoding);if($4(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return dB({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),hr(this,"decode",async(i,s,o)=>{this.isInitialized();const a=gB(s,o);if(_4(a)){const c=fB(s,o?.encoding);return Wi(c)}if($4(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=hB({symKey:c,encoded:s,encoding:o?.encoding});return Wi(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),hr(this,"getPayloadType",(i,s=Yn)=>{const o=$u({encoded:i,encoding:s});return Fo(o.type)}),hr(this,"getPayloadSenderPublicKey",(i,s=Yn)=>{const o=$u({encoded:i,encoding:s});return o.senderPublicKey?tt(o.senderPublicKey,Or):void 0}),this.core=e,this.logger=We(r,this.name),this.keychain=n||new xj(this.core,this.logger)}get context(){return it(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(m6)}catch{e=nw(),await this.keychain.set(m6,e)}return vj(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Sj=Object.defineProperty,Aj=Object.defineProperties,Pj=Object.getOwnPropertyDescriptors,F6=Object.getOwnPropertySymbols,Oj=Object.prototype.hasOwnProperty,Nj=Object.prototype.propertyIsEnumerable,xw=(t,e,r)=>e in t?Sj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tj=(t,e)=>{for(var r in e||(e={}))Oj.call(e,r)&&xw(t,r,e[r]);if(F6)for(var r of F6(e))Nj.call(e,r)&&xw(t,r,e[r]);return t},kj=(t,e)=>Aj(t,Pj(e)),hn=(t,e,r)=>xw(t,typeof e!="symbol"?e+"":e,r);class Rj extends mL{constructor(e,r){super(e,r),this.logger=e,this.core=r,hn(this,"messages",new Map),hn(this,"messagesWithoutClientAck",new Map),hn(this,"name",IF),hn(this,"version",SF),hn(this,"initialized",!1),hn(this,"storagePrefix",Ci),hn(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),hn(this,"set",async(n,i,s)=>{this.isInitialized();const o=vi(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===qp.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,kj(Tj({},c),{[o]:i}))}return await this.persist(),o}),hn(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),hn(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),hn(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=vi(i);return typeof s[o]<"u"}),hn(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=vi(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),hn(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=We(e,this.name),this.core=r}get context(){return it(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,Ag(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ag(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pg(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Pg(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Dj=Object.defineProperty,Bj=Object.defineProperties,Uj=Object.getOwnPropertyDescriptors,M6=Object.getOwnPropertySymbols,Lj=Object.prototype.hasOwnProperty,Fj=Object.prototype.propertyIsEnumerable,$w=(t,e,r)=>e in t?Dj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wp=(t,e)=>{for(var r in e||(e={}))Lj.call(e,r)&&$w(t,r,e[r]);if(M6)for(var r of M6(e))Fj.call(e,r)&&$w(t,r,e[r]);return t},_w=(t,e)=>Bj(t,Uj(e)),ti=(t,e,r)=>$w(t,typeof e!="symbol"?e+"":e,r);class Mj extends bL{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ti(this,"events",new nt.exports.EventEmitter),ti(this,"name",AF),ti(this,"queue",new Map),ti(this,"publishTimeout",z.toMiliseconds(z.ONE_MINUTE)),ti(this,"initialPublishTimeout",z.toMiliseconds(z.ONE_SECOND*15)),ti(this,"needsTransportRestart",!1),ti(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||b6,c=Op(s),l=s?.prompt||!1,u=s?.tag||0,d=s?.id||un().toString(),h={topic:n,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}},f=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const g=new Promise(async w=>{const p=({id:m})=>{h.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Yt.publish,p),w(h))};this.relayer.events.on(Yt.publish,p);const b=qs(new Promise((m,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}).then(m).catch(C=>{this.logger.warn(C,C?.message),E(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await b,this.events.removeListener(Yt.publish,p)}catch(m){this.queue.set(d,_w(Wp({},h),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}}),await qs(g,this.publishTimeout,f)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(d)}}),ti(this,"on",(n,i)=>{this.events.on(n,i)}),ti(this,"once",(n,i)=>{this.events.once(n,i)}),ti(this,"off",(n,i)=>{this.events.off(n,i)}),ti(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=We(r,this.name),this.registerEventListeners()}get context(){return it(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=b6,prompt:l,tag:u,id:d,attestation:h,tvf:f}=e,g={method:_u(Op().protocol).publish,params:Wp({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:h},f),id:d};ur((r=g.params)==null?void 0:r.prompt)&&((n=g.params)==null||delete n.prompt),ur((i=g.params)==null?void 0:i.tag)&&((s=g.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const w=await this.relayer.request(g);return this.relayer.events.emit(Yt.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,_w(Wp({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(_w(Wp({},e),{topic:i,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Xn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Yt.connection_stalled);return}this.checkQueue()}),this.relayer.on(Yt.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var jj=Object.defineProperty,zj=(t,e,r)=>e in t?jj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vc=(t,e,r)=>zj(t,typeof e!="symbol"?e+"":e,r);class qj{constructor(){vc(this,"map",new Map),vc(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),vc(this,"get",e=>this.map.get(e)||[]),vc(this,"exists",(e,r)=>this.get(e).includes(r)),vc(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),vc(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Hj=Object.defineProperty,Wj=Object.defineProperties,Vj=Object.getOwnPropertyDescriptors,j6=Object.getOwnPropertySymbols,Kj=Object.prototype.hasOwnProperty,Gj=Object.prototype.propertyIsEnumerable,Iw=(t,e,r)=>e in t?Hj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e)=>{for(var r in e||(e={}))Kj.call(e,r)&&Iw(t,r,e[r]);if(j6)for(var r of j6(e))Gj.call(e,r)&&Iw(t,r,e[r]);return t},Sw=(t,e)=>Wj(t,Vj(e)),st=(t,e,r)=>Iw(t,typeof e!="symbol"?e+"":e,r);class Zj extends EL{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,st(this,"subscriptions",new Map),st(this,"topicMap",new qj),st(this,"events",new nt.exports.EventEmitter),st(this,"name",DF),st(this,"version",BF),st(this,"pending",new Map),st(this,"cached",[]),st(this,"initialized",!1),st(this,"storagePrefix",Ci),st(this,"subscribeTimeout",z.toMiliseconds(z.ONE_MINUTE)),st(this,"initialSubscribeTimeout",z.toMiliseconds(z.ONE_SECOND*15)),st(this,"clientId"),st(this,"batchSubscribeTopicsLimit",500),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),st(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Op(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),st(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),st(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),st(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),st(this,"on",(n,i)=>{this.events.on(n,i)}),st(this,"once",(n,i)=>{this.events.once(n,i)}),st(this,"off",(n,i)=>{this.events.off(n,i)}),st(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),st(this,"start",async()=>{await this.onConnect()}),st(this,"stop",async()=>{await this.onDisconnect()}),st(this,"restart",async()=>{await this.restore(),await this.onRestart()}),st(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),st(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Xn.pulse,async()=>{await this.checkPending()}),this.events.on(dn.created,async n=>{const i=dn.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(dn.deleted,async n=>{const i=dn.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=We(r,this.name),this.clientId=""}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Op(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=Ze("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i;(!n||n?.transportType===gt.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:_u(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===gt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},z.toMiliseconds(z.ONE_SECOND)),a;const c=new Promise(async u=>{const d=h=>{h.topic===e&&(this.events.removeListener(dn.created,d),u(h.id))};this.events.on(dn.created,d);try{const h=await qs(new Promise((f,g)=>{this.relayer.request(s).catch(w=>{this.logger.warn(w,w?.message),g(w)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(dn.created,d),u(h)}catch{}}),l=await qs(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Yt.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:_u(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await qs(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Yt.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:_u(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await qs(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Yt.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:_u(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Sw(Fu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Fu({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,Fu({},r)),this.topicMap.set(r.topic,e),this.events.emit(dn.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(dn.deleted,Sw(Fu({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(dn.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(dn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Sw(Fu({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await Xk(z.toMiliseconds(z.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=J("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 vi(e+await this.getClientId())}}var Yj=Object.defineProperty,z6=Object.getOwnPropertySymbols,Jj=Object.prototype.hasOwnProperty,Xj=Object.prototype.propertyIsEnumerable,Aw=(t,e,r)=>e in t?Yj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,q6=(t,e)=>{for(var r in e||(e={}))Jj.call(e,r)&&Aw(t,r,e[r]);if(z6)for(var r of z6(e))Xj.call(e,r)&&Aw(t,r,e[r]);return t},Ue=(t,e,r)=>Aw(t,typeof e!="symbol"?e+"":e,r);class Qj extends yL{constructor(e){super(e),Ue(this,"protocol","wc"),Ue(this,"version",2),Ue(this,"core"),Ue(this,"logger"),Ue(this,"events",new nt.exports.EventEmitter),Ue(this,"provider"),Ue(this,"messages"),Ue(this,"subscriber"),Ue(this,"publisher"),Ue(this,"name",OF),Ue(this,"transportExplicitlyClosed",!1),Ue(this,"initialized",!1),Ue(this,"connectionAttemptInProgress",!1),Ue(this,"relayUrl"),Ue(this,"projectId"),Ue(this,"packageName"),Ue(this,"bundleId"),Ue(this,"hasExperiencedNetworkDisruption",!1),Ue(this,"pingTimeout"),Ue(this,"heartBeatTimeout",z.toMiliseconds(z.THIRTY_SECONDS+z.FIVE_SECONDS)),Ue(this,"reconnectTimeout"),Ue(this,"connectPromise"),Ue(this,"reconnectInProgress",!1),Ue(this,"requestsInFlight",[]),Ue(this,"connectTimeout",z.toMiliseconds(z.ONE_SECOND*15)),Ue(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||un().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),Ue(this,"resetPingTimeout",()=>{mp()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Ue(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Yt.connect)}),Ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ue(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Yt.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ue(this,"registerProviderListeners",()=>{this.provider.on(On.payload,this.onPayloadHandler),this.provider.on(On.connect,this.onConnectHandler),this.provider.on(On.disconnect,this.onDisconnectHandler),this.provider.on(On.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?We(e.logger,this.name):ln(es({level:e.logger||PF})),this.messages=new Rj(this.logger,e.core),this.subscriber=new Zj(this,this.logger),this.publisher=new Mj(this,this.logger),this.relayUrl=e?.relayUrl||v6,this.projectId=e.projectId,Bk()?this.packageName=h5():Uk()&&(this.bundleId=h5()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return it(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:gt.relay},qp.outbound)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(dn.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(dn.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,q6({internal:{throwOnFailedPublish:o}},r)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await qs(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(e).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await D4())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=Rt(z.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Yt.message,e),await this.recordMessageEvent(e,qp.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(On.disconnect,s),await qs(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(On.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(On.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(On.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,z.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(mp())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new bt(new h6(zk({sdkVersion:yw,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),yc(e)){if(!e.method.endsWith(NF))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:gt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(q6({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else jo(e)&&this.events.emit(Yt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,qp.inbound),this.events.emit(Yt.message,e))}async acknowledgePayload(e){const r=Zs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(On.payload,this.onPayloadHandler),this.provider.off(On.connect,this.onConnectHandler),this.provider.off(On.disconnect,this.onDisconnectHandler),this.provider.off(On.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await D4();eU(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Yt.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},z.toMiliseconds(TF)))))}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function ez(){}function H6(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function W6(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function V6(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const tz="[object RegExp]",rz="[object String]",nz="[object Number]",iz="[object Boolean]",K6="[object Arguments]",sz="[object Symbol]",oz="[object Date]",az="[object Map]",cz="[object Set]",lz="[object Array]",uz="[object Function]",dz="[object ArrayBuffer]",Pw="[object Object]",hz="[object Error]",pz="[object DataView]",fz="[object Uint8Array]",gz="[object Uint8ClampedArray]",wz="[object Uint16Array]",mz="[object Uint32Array]",bz="[object BigUint64Array]",yz="[object Int8Array]",vz="[object Int16Array]",Ez="[object Int32Array]",Cz="[object BigInt64Array]",xz="[object Float32Array]",$z="[object Float64Array]";function _z(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Iz(t,e,r){return Mu(t,e,void 0,void 0,void 0,void 0,r)}function Mu(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return ju(t,e,s,o)}return ju(t,e,s,o)}function ju(t,e,r,n){if(Object.is(t,e))return!0;let i=V6(t),s=V6(e);if(i===K6&&(i=Pw),s===K6&&(s=Pw),i!==s)return!1;switch(i){case rz:return t.toString()===e.toString();case nz:{const c=t.valueOf(),l=e.valueOf();return _z(c,l)}case iz:case oz:case sz:return Object.is(t.valueOf(),e.valueOf());case tz:return t.source===e.source&&t.flags===e.flags;case uz:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case az:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Mu(l,e.get(c),c,t,e,r,n))return!1;return!0}case cz:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(f=>Mu(d,f,void 0,t,e,r,n));if(h===-1)return!1;l.splice(h,1)}return!0}case lz:case fz:case gz:case wz:case mz:case bz:case yz:case vz:case Ez:case Cz:case xz:case $z:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Mu(t[c],e[c],c,t,e,r,n))return!1;return!0}case dz:return t.byteLength!==e.byteLength?!1:ju(new Uint8Array(t),new Uint8Array(e),r,n);case pz:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ju(new Uint8Array(t),new Uint8Array(e),r,n);case hz:return t.name===e.name&&t.message===e.message;case Pw:{if(!(ju(t.constructor,e.constructor,r,n)||H6(t)&&H6(e)))return!1;const c=[...Object.keys(t),...W6(t)],l=[...Object.keys(e),...W6(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=t[d];if(!Object.hasOwn(e,d))return!1;const f=e[d];if(!Mu(h,f,d,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function Sz(t,e){return Iz(t,e,ez)}var Az=Object.defineProperty,G6=Object.getOwnPropertySymbols,Pz=Object.prototype.hasOwnProperty,Oz=Object.prototype.propertyIsEnumerable,Ow=(t,e,r)=>e in t?Az(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z6=(t,e)=>{for(var r in e||(e={}))Pz.call(e,r)&&Ow(t,r,e[r]);if(G6)for(var r of G6(e))Oz.call(e,r)&&Ow(t,r,e[r]);return t},Vr=(t,e,r)=>Ow(t,typeof e!="symbol"?e+"":e,r);class Wo extends vL{constructor(e,r,n,i=Ci,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,Vr(this,"map",new Map),Vr(this,"version",kF),Vr(this,"cached",[]),Vr(this,"initialized",!1),Vr(this,"getKey"),Vr(this,"storagePrefix",Ci),Vr(this,"recentlyDeleted",[]),Vr(this,"recentlyDeletedLimit",200),Vr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ur(o)?this.map.set(this.getKey(o),o):NB(o)?this.map.set(o.id,o):TB(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Vr(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Vr(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Vr(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Sz(a[c],o[c]))):this.values)),Vr(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Z6(Z6({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Vr(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=We(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=J("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Nz=Object.defineProperty,Tz=(t,e,r)=>e in t?Nz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pe=(t,e,r)=>Tz(t,typeof e!="symbol"?e+"":e,r);class kz{constructor(e,r){this.core=e,this.logger=r,Pe(this,"name",UF),Pe(this,"version",LF),Pe(this,"events",new nt.exports),Pe(this,"pairings"),Pe(this,"initialized",!1),Pe(this,"storagePrefix",Ci),Pe(this,"ignoredPayloadTypes",[Qi]),Pe(this,"registeredMethods",[]),Pe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Pe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Pe(this,"create",async n=>{this.isInitialized();const i=nw(),s=await this.core.crypto.setSymKey(i),o=Rt(z.FIVE_MINUTES),a={protocol:y6},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},l=S4({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(zo.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:l}}),Pe(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[xi.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=I4(n.uri);i.props.properties.topic=s,i.addTrace(xi.pairing_uri_validation_success),i.addTrace(xi.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(xi.existing_pairing),u.active)throw i.setError(ns.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(xi.pairing_not_expired)}const d=c||Rt(z.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(xi.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(zo.create,h),i.addTrace(xi.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(xi.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(ns.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(ns.subscribe_pairing_topic_failure),f}return i.addTrace(xi.subscribe_pairing_topic_success),h}),Pe(this,"activate",async({topic:n})=>{this.isInitialized();const i=Rt(z.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Pe(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ro();this.events.once(He("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),Pe(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Pe(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Pe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Pe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Ze("USER_DISCONNECTED")),await this.deletePairing(i))}),Pe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return S4({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Pe(this,"sendRequest",async(n,i,s)=>{const o=Nr(i,s),a=await this.core.crypto.encode(n,o),c=Du[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Pe(this,"sendResult",async(n,i,s)=>{const o=Zs(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=Du[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),Pe(this,"sendError",async(n,i,s)=>{const o=bc(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=Du[c]?Du[c].res:Du.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),Pe(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ze("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Pe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>Hs(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Pe(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Pe(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Pe(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(zo.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Pe(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{Dt(i)?this.events.emit(He("pairing_ping",s),{}):Et(i)&&this.events.emit(He("pairing_ping",s),{error:i.error})},500)}),Pe(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(zo.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Pe(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Ze("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Pe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Ze("WC_METHOD_UNSUPPORTED",n))}),Pe(this,"isValidPair",(n,i)=>{var s;if(!Hr(n)){const{message:a}=J("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(ns.malformed_pairing_uri),new Error(a)}if(!OB(n.uri)){const{message:a}=J("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(ns.malformed_pairing_uri),new Error(a)}const o=I4(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=J("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(ns.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=J("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(ns.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&z.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(ns.pairing_expired);const{message:a}=J("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Pe(this,"isValidPing",async n=>{if(!Hr(n)){const{message:s}=J("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Pe(this,"isValidDisconnect",async n=>{if(!Hr(n)){const{message:s}=J("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Pe(this,"isValidPairingTopic",async n=>{if(!Pt(n,!1)){const{message:i}=J("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=J("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Hs(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=J("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=We(r,this.name),this.pairings=new Wo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return it(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Yt.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==gt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);yc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):jo(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Nn.expired,async e=>{const{topic:r}=w5(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(zo.expire,{topic:r}))})}}var Rz=Object.defineProperty,Dz=(t,e,r)=>e in t?Rz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pr=(t,e,r)=>Dz(t,typeof e!="symbol"?e+"":e,r);class Bz extends wL{constructor(e,r){super(e,r),this.core=e,this.logger=r,pr(this,"records",new Map),pr(this,"events",new nt.exports.EventEmitter),pr(this,"name",FF),pr(this,"version",MF),pr(this,"cached",[]),pr(this,"initialized",!1),pr(this,"storagePrefix",Ci),pr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),pr(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:Rt(z.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Qn.created,o)}),pr(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Et(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Qn.updated,i))}),pr(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),pr(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Qn.deleted,s)}}),this.persist()}),pr(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),pr(this,"on",(n,i)=>{this.events.on(n,i)}),pr(this,"once",(n,i)=>{this.events.once(n,i)}),pr(this,"off",(n,i)=>{this.events.off(n,i)}),pr(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=We(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:Nr(r.request.method,r.request.params,r.id),chainId:r.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 r=this.records.get(e);if(!r){const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Qn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Qn.created,e=>{const r=Qn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Qn.updated,e=>{const r=Qn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Qn.deleted,e=>{const r=Qn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Xn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{z.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Qn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Uz=Object.defineProperty,Lz=(t,e,r)=>e in t?Uz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_r=(t,e,r)=>Lz(t,typeof e!="symbol"?e+"":e,r);class Fz extends CL{constructor(e,r){super(e,r),this.core=e,this.logger=r,_r(this,"expirations",new Map),_r(this,"events",new nt.exports.EventEmitter),_r(this,"name",jF),_r(this,"version",zF),_r(this,"cached",[]),_r(this,"initialized",!1),_r(this,"storagePrefix",Ci),_r(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),_r(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),_r(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Nn.created,{target:s,expiration:o})}),_r(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),_r(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Nn.deleted,{target:i,expiration:s})}}),_r(this,"on",(n,i)=>{this.events.on(n,i)}),_r(this,"once",(n,i)=>{this.events.once(n,i)}),_r(this,"off",(n,i)=>{this.events.off(n,i)}),_r(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=We(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return qk(e);if(typeof e=="number")return Hk(e);const{message:r}=J("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Nn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;z.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Nn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Xn.pulse,()=>this.checkExpirations()),this.events.on(Nn.created,e=>{const r=Nn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Nn.expired,e=>{const r=Nn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Nn.deleted,e=>{const r=Nn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mz=Object.defineProperty,jz=(t,e,r)=>e in t?Mz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ot=(t,e,r)=>jz(t,typeof e!="symbol"?e+"":e,r);class zz extends xL{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,Ot(this,"name",qF),Ot(this,"abortController"),Ot(this,"isDevEnv"),Ot(this,"verifyUrlV3",WF),Ot(this,"storagePrefix",Ci),Ot(this,"version",w6),Ot(this,"publicKey"),Ot(this,"fetchPromise"),Ot(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&z.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ot(this,"register",async i=>{if(!du()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=Mi(),u=this.startAbortTimer(z.ONE_SECOND*5),d=await new Promise((h,f)=>{const g=()=>{window.removeEventListener("message",p),l.body.removeChild(w),f("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const p=b=>{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.data);if(m.type==="verify_attestation"){if(tc(m.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",p),h(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};l.body.appendChild(w),window.addEventListener("message",p,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),Ot(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(tc(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),Ot(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(z.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Ot(this,"getVerifyUrl",i=>{let s=i||Bu;return VF.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Bu}`),s=Bu),s}),Ot(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(z.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),Ot(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ot(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ot(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Ot(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ot(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),Ot(this,"validateAttestation",(i,s)=>{const o=mB(i,s.publicKey),a={hasExpired:z.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=We(r,this.name),this.abortController=new AbortController,this.isDevEnv=Og(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return it(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),z.toMiliseconds(e))}}var qz=Object.defineProperty,Hz=(t,e,r)=>e in t?qz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y6=(t,e,r)=>Hz(t,typeof e!="symbol"?e+"":e,r);class Wz extends $L{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Y6(this,"context",KF),Y6(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${GF}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=We(r,this.context)}}var Vz=Object.defineProperty,J6=Object.getOwnPropertySymbols,Kz=Object.prototype.hasOwnProperty,Gz=Object.prototype.propertyIsEnumerable,Nw=(t,e,r)=>e in t?Vz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zu=(t,e)=>{for(var r in e||(e={}))Kz.call(e,r)&&Nw(t,r,e[r]);if(J6)for(var r of J6(e))Gz.call(e,r)&&Nw(t,r,e[r]);return t},Jt=(t,e,r)=>Nw(t,typeof e!="symbol"?e+"":e,r);class Zz extends _L{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Jt(this,"context",YF),Jt(this,"storagePrefix",Ci),Jt(this,"storageVersion",ZF),Jt(this,"events",new Map),Jt(this,"shouldPersist",!1),Jt(this,"init",async()=>{if(!Og())try{const i={eventId:b5(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:f5(this.core.relayer.protocol,this.core.relayer.version,yw)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Jt(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=b5(),u=this.core.projectId||"",d=Date.now(),h=zu({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Jt(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return zu(zu({},a),this.setMethods(a.eventId))}),Jt(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Jt(this,"setEventListeners",()=>{this.core.heartbeat.on(Xn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{z.fromMiliseconds(Date.now())-z.fromMiliseconds(i.timestamp)>JF&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Jt(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Jt(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Jt(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Jt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Jt(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,zu(zu({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Jt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Jt(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${XF}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${yw}${s}`,{method:"POST",body:JSON.stringify(i)})}),Jt(this,"getAppDomain",()=>p5().url),this.logger=We(r,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}}var Yz=Object.defineProperty,X6=Object.getOwnPropertySymbols,Jz=Object.prototype.hasOwnProperty,Xz=Object.prototype.propertyIsEnumerable,Tw=(t,e,r)=>e in t?Yz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q6=(t,e)=>{for(var r in e||(e={}))Jz.call(e,r)&&Tw(t,r,e[r]);if(X6)for(var r of X6(e))Xz.call(e,r)&&Tw(t,r,e[r]);return t},ht=(t,e,r)=>Tw(t,typeof e!="symbol"?e+"":e,r);class kw extends hL{constructor(e){var r;super(e),ht(this,"protocol",g6),ht(this,"version",w6),ht(this,"name",zp),ht(this,"relayUrl"),ht(this,"projectId"),ht(this,"customStoragePrefix"),ht(this,"events",new nt.exports.EventEmitter),ht(this,"logger"),ht(this,"heartbeat"),ht(this,"relayer"),ht(this,"crypto"),ht(this,"storage"),ht(this,"history"),ht(this,"expirer"),ht(this,"pairing"),ht(this,"verify"),ht(this,"echoClient"),ht(this,"linkModeSupportedApps"),ht(this,"eventClient"),ht(this,"initialized",!1),ht(this,"logChunkController"),ht(this,"on",(a,c)=>this.events.on(a,c)),ht(this,"once",(a,c)=>this.events.once(a,c)),ht(this,"off",(a,c)=>this.events.off(a,c)),ht(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ht(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:gt.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||v6,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=es({level:typeof e?.logger=="string"&&e.logger?e.logger:vF.logger,name:zp}),{logger:s,chunkLoggerController:o}=fw({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=We(s,this.name),this.heartbeat=new kp,this.crypto=new Ij(this,this.logger,e?.keychain),this.history=new Bz(this,this.logger),this.expirer=new Fz(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new z4(Q6(Q6({},EF),e?.storageOptions)),this.relayer=new Qj({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new kz(this,this.logger),this.verify=new zz(this,this.logger,this.storage),this.echoClient=new Wz(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Zz(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new kw(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(RF,n),r}get context(){return it(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(E6,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(E6)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,n=`${r}_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[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Qz=kw,e8="wc",t8=2,r8="client",Rw=`${e8}@${t8}:${r8}:`,Dw={name:r8,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},n8="WALLETCONNECT_DEEPLINK_CHOICE",eq="proposal",i8="Proposal expired",tq="session",Ec=z.SEVEN_DAYS,rq="engine",Xt={wc_sessionPropose:{req:{ttl:z.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1104},res:{ttl:z.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1106},res:{ttl:z.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:z.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:z.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1112},res:{ttl:z.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1114},res:{ttl:z.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:z.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:z.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1119}}},Bw={min:z.FIVE_MINUTES,max:z.SEVEN_DAYS},_i={idle:"IDLE",active:"ACTIVE"},s8={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},nq="request",iq=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],sq="wc",oq="auth",aq="authKeys",cq="pairingTopics",lq="requests",Vp=`${sq}@${1.5}:${oq}:`,Kp=`${Vp}:PUB_KEY`;var uq=Object.defineProperty,dq=Object.defineProperties,hq=Object.getOwnPropertyDescriptors,o8=Object.getOwnPropertySymbols,pq=Object.prototype.hasOwnProperty,fq=Object.prototype.propertyIsEnumerable,Uw=(t,e,r)=>e in t?uq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ot=(t,e)=>{for(var r in e||(e={}))pq.call(e,r)&&Uw(t,r,e[r]);if(o8)for(var r of o8(e))fq.call(e,r)&&Uw(t,r,e[r]);return t},kr=(t,e)=>dq(t,hq(e)),V=(t,e,r)=>Uw(t,typeof e!="symbol"?e+"":e,r);class gq extends PL{constructor(e){super(e),V(this,"name",rq),V(this,"events",new nt.exports),V(this,"initialized",!1),V(this,"requestQueue",{state:_i.idle,queue:[]}),V(this,"sessionRequestQueue",{state:_i.idle,queue:[]}),V(this,"requestQueueDelay",z.ONE_SECOND),V(this,"expectedPairingMethodMap",new Map),V(this,"recentlyDeletedMap",new Map),V(this,"recentlyDeletedLimit",200),V(this,"relayMessageCache",[]),V(this,"pendingSessions",new Map),V(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Xt)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},z.toMiliseconds(this.requestQueueDelay)))}),V(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=kr(ot({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let u=i,d,h=!1;try{if(u){const S=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."),h=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),S}if(!u||!h){const{topic:S,uri:I}=await this.client.core.pairing.create();u=S,d=I}if(!u){const{message:S}=J("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(S)}const f=await this.client.core.crypto.generateKeyPair(),g=Xt.wc_sessionPropose.req.ttl||z.FIVE_MINUTES,w=Rt(g),p=kr(ot(ot({requiredNamespaces:s,optionalNamespaces:o,relays:l??[{protocol:y6}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Zt()}),b=He("session_connect",p.id),{reject:m,resolve:E,done:C}=Ro(g,i8),P=({id:S})=>{S===p.id&&(this.client.events.off("proposal_expire",P),this.pendingSessions.delete(p.id),this.events.emit(b,{error:{message:i8,code:0}}))};return this.client.events.on("proposal_expire",P),this.events.once(b,({error:S,session:I})=>{this.client.events.off("proposal_expire",P),S?m(S):I&&E(I)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:p,throwOnFailedPublish:!0,clientRpcId:p.id}),await this.setProposal(p.id,p),{uri:d,approval:C}}),V(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),V(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[ei.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch($){throw o.setError(qo.no_internet_connection),$}try{await this.isValidProposalId(r?.id)}catch($){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(qo.proposal_not_found),$}try{await this.isValidApprove(r)}catch($){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(qo.session_approve_namespace_validation_failure),$}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:p,optionalNamespaces:b}=f;let m=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});m||(m=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:ei.session_approve_started,properties:{topic:g,trace:[ei.session_approve_started,ei.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),C=w.publicKey,P=await this.client.core.crypto.generateSharedKey(E,C),S=ot(ot(ot({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:Rt(Ec)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),I=gt.relay;m.addTrace(ei.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:I})}catch($){throw m.setError(qo.subscribe_session_topic_failure),$}m.addTrace(ei.subscribe_session_topic_success);const N=kr(ot({},S),{topic:P,requiredNamespaces:p,optionalNamespaces:b,pairingTopic:g,acknowledged:!1,self:S.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:E,transportType:gt.relay});await this.client.session.set(P,N),m.addTrace(ei.store_session);try{m.addTrace(ei.publishing_session_settle),await this.sendRequest({topic:P,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch($=>{throw m?.setError(qo.session_settle_publish_failure),$}),m.addTrace(ei.session_settle_publish_success),m.addTrace(ei.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch($=>{throw m?.setError(qo.session_approve_publish_failure),$}),m.addTrace(ei.session_approve_publish_success)}catch($){throw this.client.logger.error($),this.client.session.delete(P,Ze("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),$}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.client.proposal.delete(a,Ze("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,Rt(Ec)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),V(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i,rpcOpts:Xt.wc_sessionPropose.reject}),await this.client.proposal.delete(n,Ze("USER_DISCONNECTED")))}),V(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=Ro(),c=Zt(),l=un().toString(),u=this.client.session.get(n).namespaces;return this.events.once(He("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:u}),a(d)}),{acknowledged:s}}),V(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=Zt(),{done:s,resolve:o,reject:a}=Ro();return this.events.once(He("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,Rt(Ec)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),V(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:n,request:i,topic:s,expiry:o=Xt.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===gt.relay&&await this.confirmOnlineStateOrThrow();const c=Zt(),l=un().toString(),{done:u,resolve:d,reject:h}=Ro(o,"Request expired. Please try again.");this.events.once(He("session_request",c),({error:b,result:m})=>{b?h(b):d(m)});const f="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:kr(ot({},i),{expiryTimestamp:Rt(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await u();const w={request:kr(ot({},i),{expiryTimestamp:Rt(o)}),chainId:n},p=this.shouldSetTVF(f,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(ot({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:w,expiry:o,throwOnFailedPublish:!0},p&&{tvf:this.getTVFParams(c,w)})).catch(m=>h(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const E=await Gk(this.client.core.storage,n8);await Wk({id:c,topic:s,wcDeepLink:E})}b()}),u()]).then(b=>b[2])}),V(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===gt.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Dt(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):Et(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),V(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=Zt(),s=un().toString(),{done:o,resolve:a,reject:c}=Ro();this.events.once(He("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(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:n}))}),V(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=un().toString(),a=Zt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),V(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Ze("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=J("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),V(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>AB(n,r)))),V(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),V(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?gt.link_mode:gt.relay;o===gt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:g,methods:w=[],expiry:p}=r,b=[...r.resources||[]],{topic:m,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:E}});const C=await this.client.core.crypto.generateKeyPair(),P=Pp(C);if(await Promise.all([this.client.auth.authKeys.set(Kp,{responseTopic:P,publicKey:C}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:m})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),w.length>0){const{namespace:_}=rc(a[0]);let k=FR(_,"request",w);Ep(b)&&(k=jR(k,b.pop())),b.push(k)}const S=p&&p>Xt.wc_sessionAuthenticate.req.ttl?p:Xt.wc_sessionAuthenticate.req.ttl,I={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:g,resources:b},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Rt(S)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Rt(Xt.wc_sessionPropose.req.ttl),id:Zt()},{done:D,resolve:T,reject:R}=Ro(S,"Request expired"),M=Zt(),x=He("session_connect",$.id),y=He("session_request",M),v=async({error:_,session:k})=>{this.events.off(y,A),_?R(_):k&&T({session:k})},A=async _=>{var k,L,F;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),_.error){const te=Ze("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===te.code?void 0:(this.events.off(x,v),R(_.error.message))}await this.deleteProposal($.id),this.events.off(x,v);const{cacaos:H,responder:q}=_.result,W=[],Y=[];for(const te of H){await k5({cacao:te,projectId:this.client.core.projectId})||(this.client.logger.error(te,"Signature verification failed"),R(Ze("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ee}=te,Ce=Ep(Ee.resources),xe=[Bg(Ee.iss)],_e=vp(Ee.iss);if(Ce){const Ge=B5(Ce),xr=U5(Ce);W.push(...Ge),xe.push(...xr)}for(const Ge of xe)Y.push(`${Ge}:${_e}`)}const ae=await this.client.core.crypto.generateSharedKey(C,q.publicKey);let re;W.length>0&&(re={topic:ae,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:Rt(Ec),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:A4([...new Set(W)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(ae,{transportType:o}),await this.client.session.set(ae,re),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:q.metadata}),re=this.client.session.get(ae)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(L=q.metadata.redirect)!=null&&L.linkMode&&(F=q.metadata.redirect)!=null&&F.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ae,{transportType:gt.link_mode})),T({auths:H,session:re})};this.events.once(x,v),this.events.once(y,A);let O;try{if(s){const _=Nr("wc_sessionAuthenticate",I,M);this.client.core.history.set(m,_);const k=await this.client.core.crypto.encode("",_,{type:Cu,encoding:Gs});O=Np(n,m,k)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:I,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:$,expiry:Xt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(_){throw this.events.off(x,v),this.events.off(y,A),_}return await this.setProposal($.id,$),await this.setAuthRequest(M,{request:kr(ot({},I),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:O??E,response:D}}),V(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ho.authenticated_session_approve_started]}});try{this.isInitialized()}catch(p){throw s.setError(Uu.no_internet_connection),p}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Uu.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||gt.relay;a===gt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Pp(c),d={type:Qi,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const p of i){if(!await k5({cacao:p,projectId:this.client.core.projectId})){s.setError(Uu.invalid_cacao);const P=Ze("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:P,encodeOpts:d}),new Error(P.message)}s.addTrace(Ho.cacaos_verified);const{p:b}=p,m=Ep(b.resources),E=[Bg(b.iss)],C=vp(b.iss);if(m){const P=B5(m),S=U5(m);h.push(...P),E.push(...S)}for(const P of E)f.push(`${P}:${C}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Ho.create_authenticated_session_topic);let w;if(h?.length>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Rt(Ec),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:A4([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Ho.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(p){throw s.setError(Uu.subscribe_authenticated_session_topic_failure),p}s.addTrace(Ho.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),s.addTrace(Ho.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ho.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(p){throw s.setError(Uu.authenticated_session_approve_publish_failure),p}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}}),V(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===gt.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Pp(o),l={type:Qi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:l,rpcOpts:Xt.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,Ze("USER_DISCONNECTED"))}),V(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return R5(n,i)}),V(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),V(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),V(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Ze("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(n8).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,Ze("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=_i.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),V(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(qo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Ze("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),V(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=_i.idle,this.client.events.emit("session_request_expire",{id:r}))}),V(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),V(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),V(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,Rt(Xt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),V(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=gt.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),V(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||Rt(Xt.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),V(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=r,h=Nr(i,s,c);let f;const g=!!u;try{const b=g?Gs:Yn;f=await this.client.core.crypto.encode(n,h,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),b}let w;if(iq.includes(i)){const b=vi(JSON.stringify(h)),m=vi(f);w=await this.client.core.verify.register({id:m,decryptedId:b})}const p=Xt[i].req;if(p.attestation=w,o&&(p.ttl=o),a&&(p.id=a),this.client.core.history.set(n,h),g){const b=Np(u,n,f);await global.Linking.openURL(b,this.client.name)}else{const b=Xt[i].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=kr(ot({},d),{correlationId:h.id}),l?(b.internal=kr(ot({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,f,b)):this.client.core.relayer.publish(n,f,b).catch(m=>this.client.logger.error(m))}return h.id}),V(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=Zs(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=d?Gs:Yn;u=await this.client.core.crypto.encode(i,l,kr(ot({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),g}let h,f;try{h=await this.client.core.history.get(i,n);const g=h.request;try{this.shouldSetTVF(g.method,g.params)&&(f=this.getTVFParams(n,g.params,s))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),g}if(d){const g=Np(c,i,u);await global.Linking.openURL(g,this.client.name)}else{const g=h.request.method,w=Xt[g].res;w.tvf=kr(ot({},f),{correlationId:n}),o?(w.internal=kr(ot({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,w)):this.client.core.relayer.publish(i,u,w).catch(p=>this.client.logger.error(p))}await this.client.core.history.resolve(l)}),V(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=bc(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?Gs:Yn;u=await this.client.core.crypto.encode(i,l,kr(ot({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,n)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),f}if(d){const f=Np(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,g=a||Xt[f].res;this.client.core.relayer.publish(i,u,g)}await this.client.core.history.resolve(l)}),V(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;Hs(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Hs(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),V(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),V(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),V(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===_i.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=_i.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=_i.idle}),V(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),V(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),V(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=J("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),V(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),V(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ns.proposal_listener_not_found)),this.isValidConnect(ot({},i.params));const u=a.expiryTimestamp||Rt(Xt.wc_sessionPropose.req.ttl),d=ot({id:c,pairingTopic:n,expiryTimestamp:u},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:vi(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(xi.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:Xt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),V(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(Dt(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:r,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:r})}else if(Et(n)){await this.client.proposal.delete(s,Ze("USER_DISCONNECTED"));const o=He("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),V(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=n.params,f=[...this.pendingSessions.values()].find(p=>p.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(f.proposalId),w=kr(ot(ot(ot({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:gt.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit(He("session_connect",f.proposalId),{session:w}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),V(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;Dt(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(He("session_approve",i),{})):Et(n)&&(await this.client.session.delete(r,Ze("USER_DISCONNECTED")),this.events.emit(He("session_approve",i),{error:n.error}))}),V(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Au.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Ze("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ot({topic:r},i));try{Au.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Au.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),V(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),V(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=He("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Dt(n)?this.events.emit(He("session_update",i),{}):Et(n)&&this.events.emit(He("session_update",i),{error:n.error})}),V(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Rt(Ec)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),V(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=He("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Dt(n)?this.events.emit(He("session_extend",i),{}):Et(n)&&this.events.emit(He("session_extend",i),{error:n.error})}),V(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),V(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=He("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Dt(n)?this.events.emit(He("session_ping",i),{}):Et(n)&&this.events.emit(He("session_ping",i),{error:n.error})},500)}),V(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Yt.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Ze("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),V(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:d,params:h}=a;try{await this.isValidRequest(ot({topic:o},h));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:vi(JSON.stringify(Nr("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),w={id:d,topic:o,params:h,verifyContext:g};await this.setPendingSessionRequest(w),u===gt.link_mode&&(n=f.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),V(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=He("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Dt(n)?this.events.emit(He("session_request",i),{result:n.result}):Et(n)&&this.events.emit(He("session_request",i),{error:n.error})}),V(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Au.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ot({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Au.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),V(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Dt(n)?this.events.emit(He("session_request",i),{result:n.result}):Et(n)&&this.events.emit(He("session_request",i),{error:n.error})}),V(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:vi(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===gt.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:Qi,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Xt.wc_sessionAuthenticate.autoReject,appLink:h})}}),V(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),V(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=_i.idle,this.processSessionRequestQueue()},z.toMiliseconds(this.requestQueueDelay))}),V(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=He("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(He("session_request",s.request.id),{error:n})})}),V(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===_i.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=_i.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),V(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),V(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:Nr("wc_sessionPropose",kr(ot({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),V(this,"isValidConnect",async r=>{if(!Hr(r)){const{message:l}=J("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(ur(n)||await this.isValidPairingTopic(n),!MB(c,!0)){const{message:l}=J("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!ur(i)&&Su(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!ur(s)&&Su(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ur(o)||this.validateSessionProps(o,"sessionProperties"),!ur(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),V(this,"validateNamespaces",(r,n)=>{const i=FB(r,"connect()",n);if(i)throw new Error(i.message)}),V(this,"isValidApprove",async r=>{if(!Hr(r))throw new Error(J("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=ow(i,"approve()");if(l)throw new Error(l.message);const u=k4(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!Pt(s,!0)){const{message:d}=J("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(ur(o)||this.validateSessionProps(o,"sessionProperties"),!ur(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),V(this,"isValidReject",async r=>{if(!Hr(r)){const{message:s}=J("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!zB(i)){const{message:s}=J("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),V(this,"isValidSessionSettleRequest",r=>{if(!Hr(r)){const{message:l}=J("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!N4(n)){const{message:l}=J("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=kB(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ow(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Hs(o)){const{message:l}=J("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),V(this,"isValidUpdate",async r=>{if(!Hr(r)){const{message:c}=J("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=ow(i,"update()");if(o)throw new Error(o.message);const a=k4(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),V(this,"isValidExtend",async r=>{if(!Hr(r)){const{message:i}=J("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),V(this,"isValidRequest",async r=>{if(!Hr(r)){const{message:c}=J("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!T4(a,s)){const{message:c}=J("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!qB(i)){const{message:c}=J("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!VB(a,s,i.method)){const{message:c}=J("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!YB(o,Bw)){const{message:c}=J("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Bw.min} and ${Bw.max}`);throw new Error(c)}}),V(this,"isValidRespond",async r=>{var n;if(!Hr(r)){const{message:o}=J("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!HB(s)){const{message:o}=J("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),V(this,"isValidPing",async r=>{if(!Hr(r)){const{message:i}=J("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),V(this,"isValidEmit",async r=>{if(!Hr(r)){const{message:a}=J("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!T4(o,s)){const{message:a}=J("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!WB(i)){const{message:a}=J("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!KB(o,s,i.name)){const{message:a}=J("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),V(this,"isValidDisconnect",async r=>{if(!Hr(r)){const{message:i}=J("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),V(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!Pt(i,!1))throw new Error("uri is required parameter");if(!Pt(s,!1))throw new Error("domain is required parameter");if(!Pt(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>rc(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=rc(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),V(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Bu,validation:"UNKNOWN",origin:o.url||""}};try{if(a===gt.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),V(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=J("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),V(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),V(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),V(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=J("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),V(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,l,u,d,h;return!r||n!==gt.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((d=r?.redirect)==null?void 0:d.universal)!==""&&((h=r?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),V(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),V(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=m5(r,"topic")||"",i=decodeURIComponent(m5(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:gt.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),V(this,"registerLinkModeListeners",async()=>{var r;if(Og()||zs()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),V(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(s8).includes(i.method)}),V(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return kr(ot({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),V(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),V(this,"extractTxHashesFromResult",(r,n)=>{try{const i=s8[r];if(typeof n=="string")return[n];const s=n[i.key];if(Jn(s))return r==="solana_signAllTransactions"?s.map(o=>_R(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Yt.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Kp)?this.client.auth.authKeys.get(Kp):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===gt.link_mode?Gs:Yn});yc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:vi(n)})):jo(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Nn.expired,async e=>{const{topic:r,id:n}=w5(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,J("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,J("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(zo.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(zo.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Pt(e,!1)){const{message:r}=J("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=J("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Hs(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=J("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Pt(e,!1)){const{message:r}=J("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=J("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Hs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=J("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=J("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Pt(e,!1)){const{message:r}=J("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=J("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!jB(e)){const{message:r}=J("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=J("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Hs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=J("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class wq extends Wo{constructor(e,r){super(e,r,eq,Rw),this.core=e,this.logger=r}}class mq extends Wo{constructor(e,r){super(e,r,tq,Rw),this.core=e,this.logger=r}}class bq extends Wo{constructor(e,r){super(e,r,nq,Rw,n=>n.id),this.core=e,this.logger=r}}class yq extends Wo{constructor(e,r){super(e,r,aq,Vp,()=>Kp),this.core=e,this.logger=r}}class vq extends Wo{constructor(e,r){super(e,r,cq,Vp),this.core=e,this.logger=r}}class Eq extends Wo{constructor(e,r){super(e,r,lq,Vp,n=>n.id),this.core=e,this.logger=r}}var Cq=Object.defineProperty,xq=(t,e,r)=>e in t?Cq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lw=(t,e,r)=>xq(t,typeof e!="symbol"?e+"":e,r);class $q{constructor(e,r){this.core=e,this.logger=r,Lw(this,"authKeys"),Lw(this,"pairingTopics"),Lw(this,"requests"),this.authKeys=new yq(this.core,this.logger),this.pairingTopics=new vq(this.core,this.logger),this.requests=new Eq(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var _q=Object.defineProperty,Iq=(t,e,r)=>e in t?_q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oe=(t,e,r)=>Iq(t,typeof e!="symbol"?e+"":e,r);class Fw extends AL{constructor(e){super(e),Oe(this,"protocol",e8),Oe(this,"version",t8),Oe(this,"name",Dw.name),Oe(this,"metadata"),Oe(this,"core"),Oe(this,"logger"),Oe(this,"events",new nt.exports.EventEmitter),Oe(this,"engine"),Oe(this,"session"),Oe(this,"proposal"),Oe(this,"pendingRequest"),Oe(this,"auth"),Oe(this,"signConfig"),Oe(this,"on",(n,i)=>this.events.on(n,i)),Oe(this,"once",(n,i)=>this.events.once(n,i)),Oe(this,"off",(n,i)=>this.events.off(n,i)),Oe(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Oe(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Oe(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Oe(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Oe(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Dw.name,this.metadata=Fk(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ln(es({level:e?.logger||Dw.logger}));this.core=e?.core||new Qz(e),this.logger=We(r,this.name),this.session=new mq(this.core,this.logger),this.proposal=new wq(this.core,this.logger),this.pendingRequest=new bq(this.core,this.logger),this.engine=new gq(this),this.auth=new $q(this.core,this.logger)}static async init(e){const r=new Fw(e);return await r.initialize(),r}get context(){return it(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},z.toMiliseconds(z.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Mw={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof zt<"u"&&zt,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof zt<"u"&&zt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(y){return y&&DataView.prototype.isPrototypeOf(y)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(y){return y&&u.indexOf(Object.prototype.toString.call(y))>-1};function h(y){if(typeof y!="string"&&(y=String(y)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(y)||y==="")throw new TypeError('Invalid character in header field name: "'+y+'"');return y.toLowerCase()}function f(y){return typeof y!="string"&&(y=String(y)),y}function g(y){var v={next:function(){var A=y.shift();return{done:A===void 0,value:A}}};return c.iterable&&(v[Symbol.iterator]=function(){return v}),v}function w(y){this.map={},y instanceof w?y.forEach(function(v,A){this.append(A,v)},this):Array.isArray(y)?y.forEach(function(v){if(v.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+v.length);this.append(v[0],v[1])},this):y&&Object.getOwnPropertyNames(y).forEach(function(v){this.append(v,y[v])},this)}w.prototype.append=function(y,v){y=h(y),v=f(v);var A=this.map[y];this.map[y]=A?A+", "+v:v},w.prototype.delete=function(y){delete this.map[h(y)]},w.prototype.get=function(y){return y=h(y),this.has(y)?this.map[y]:null},w.prototype.has=function(y){return this.map.hasOwnProperty(h(y))},w.prototype.set=function(y,v){this.map[h(y)]=f(v)},w.prototype.forEach=function(y,v){for(var A in this.map)this.map.hasOwnProperty(A)&&y.call(v,this.map[A],A,this)},w.prototype.keys=function(){var y=[];return this.forEach(function(v,A){y.push(A)}),g(y)},w.prototype.values=function(){var y=[];return this.forEach(function(v){y.push(v)}),g(y)},w.prototype.entries=function(){var y=[];return this.forEach(function(v,A){y.push([A,v])}),g(y)},c.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function p(y){if(!y._noBody){if(y.bodyUsed)return Promise.reject(new TypeError("Already read"));y.bodyUsed=!0}}function b(y){return new Promise(function(v,A){y.onload=function(){v(y.result)},y.onerror=function(){A(y.error)}})}function m(y){var v=new FileReader,A=b(v);return v.readAsArrayBuffer(y),A}function E(y){var v=new FileReader,A=b(v),O=/charset=([A-Za-z0-9_-]+)/.exec(y.type),_=O?O[1]:"utf-8";return v.readAsText(y,_),A}function C(y){for(var v=new Uint8Array(y),A=new Array(v.length),O=0;O<v.length;O++)A[O]=String.fromCharCode(v[O]);return A.join("")}function P(y){if(y.slice)return y.slice(0);var v=new Uint8Array(y.byteLength);return v.set(new Uint8Array(y)),v.buffer}function S(){return this.bodyUsed=!1,this._initBody=function(y){this.bodyUsed=this.bodyUsed,this._bodyInit=y,y?typeof y=="string"?this._bodyText=y:c.blob&&Blob.prototype.isPrototypeOf(y)?this._bodyBlob=y:c.formData&&FormData.prototype.isPrototypeOf(y)?this._bodyFormData=y:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)?this._bodyText=y.toString():c.arrayBuffer&&c.blob&&l(y)?(this._bodyArrayBuffer=P(y.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(y)||d(y))?this._bodyArrayBuffer=P(y):this._bodyText=y=Object.prototype.toString.call(y):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof y=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var y=p(this);if(y)return y;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var y=p(this);return y||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(m);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var y=p(this);if(y)return y;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(C(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(D)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function N(y){var v=y.toUpperCase();return I.indexOf(v)>-1?v:y}function $(y,v){if(!(this instanceof $))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');v=v||{};var A=v.body;if(y instanceof $){if(y.bodyUsed)throw new TypeError("Already read");this.url=y.url,this.credentials=y.credentials,v.headers||(this.headers=new w(y.headers)),this.method=y.method,this.mode=y.mode,this.signal=y.signal,!A&&y._bodyInit!=null&&(A=y._bodyInit,y.bodyUsed=!0)}else this.url=String(y);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new w(v.headers)),this.method=N(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(v.cache==="no-store"||v.cache==="no-cache")){var O=/([?&])_=[^&]*/;if(O.test(this.url))this.url=this.url.replace(O,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function D(y){var v=new FormData;return y.trim().split("&").forEach(function(A){if(A){var O=A.split("="),_=O.shift().replace(/\+/g," "),k=O.join("=").replace(/\+/g," ");v.append(decodeURIComponent(_),decodeURIComponent(k))}}),v}function T(y){var v=new w,A=y.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(O){return O.indexOf(`
39
+ ***************************************************************************** */var ww=function(t,e){return ww=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},ww(t,e)};function UL(t,e){ww(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var mw=function(){return mw=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},mw.apply(this,arguments)};function LL(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function FL(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function ML(t,e){return function(r,n){e(r,n,t)}}function jL(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function zL(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(d){o(d)}}function c(u){try{l(n.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function qL(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function HL(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function WL(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function bw(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function n6(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function VL(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(n6(arguments[e]));return t}function KL(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Ru(t){return this instanceof Ru?(this.v=t,this):new Ru(t)}function GL(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(f){return new Promise(function(g,w){s.push([h,f,g,w])>1||a(h,f)})})}function a(h,f){try{c(n[h](f))}catch(g){d(s[0][3],g)}}function c(h){h.value instanceof Ru?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function ZL(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Ru(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function YL(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof bw=="function"?bw(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function JL(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function XL(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function QL(t){return t&&t.__esModule?t:{default:t}}function eF(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function tF(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rF=Object.freeze({__proto__:null,__extends:UL,get __assign(){return mw},__rest:LL,__decorate:FL,__param:ML,__metadata:jL,__awaiter:zL,__generator:qL,__createBinding:HL,__exportStar:WL,__values:bw,__read:n6,__spread:VL,__spreadArrays:KL,__await:Ru,__asyncGenerator:GL,__asyncDelegator:ZL,__asyncValues:YL,__makeTemplateObject:JL,__importStar:XL,__importDefault:QL,__classPrivateFieldGet:eF,__classPrivateFieldSet:tF}),nF=h2(rF),ts={},i6;function iF(){if(i6)return ts;i6=1,Object.defineProperty(ts,"__esModule",{value:!0}),ts.isBrowserCryptoAvailable=ts.getSubtleCrypto=ts.getBrowerCrypto=void 0;function t(){return zt?.crypto||zt?.msCrypto||{}}ts.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}ts.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return ts.isBrowserCryptoAvailable=r,ts}var rs={},s6;function sF(){if(s6)return rs;s6=1,Object.defineProperty(rs,"__esModule",{value:!0}),rs.isBrowser=rs.isNode=rs.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}rs.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}rs.isNode=e;function r(){return!t()&&!e()}return rs.isBrowser=r,rs}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=nF;e.__exportStar(iF(),t),e.__exportStar(sF(),t)})(r6);function Zt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function un(t=6){return BigInt(Zt(t))}function Nr(t,e,r){return{id:r||Zt(),jsonrpc:"2.0",method:t,params:e}}function Zs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function bc(t,e,r){return{id:t,jsonrpc:"2.0",error:oF(e,r)}}function oF(t,e){return typeof t>"u"?e6(X4):(typeof t=="string"&&(t=Object.assign(Object.assign({},e6(gw)),{message:t})),typeof e<"u"&&(t.data=e),DL(t.code)&&(t=BL(t.code)),t)}class aF{}class cF extends aF{constructor(){super()}}class lF extends cF{constructor(e){super()}}const uF="^https?:",dF="^wss?:";function hF(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function o6(t,e){const r=hF(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function a6(t){return o6(t,uF)}function c6(t){return o6(t,dF)}function pF(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function l6(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function yc(t){return l6(t)&&"method"in t}function jo(t){return l6(t)&&(Dt(t)||Et(t))}function Dt(t){return"result"in t}function Et(t){return"error"in t}class bt extends lF{constructor(e){super(e),this.events=new nt.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Nr(e.method,e.params||[],e.id||un().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Et(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),jo(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const fF=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),gF=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",u6=t=>t.split("?")[0],d6=10,wF=fF();class h6{constructor(e){if(this.url=e,this.events=new nt.exports.EventEmitter,this.registering=!1,!c6(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(wi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!c6(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=r6.isReactNative()?void 0:{rejectUnauthorized:!pF(e)},s=new wF(e,[],i);gF()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Wi(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=bc(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return t6(e,u6(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>d6&&this.events.setMaxListeners(d6)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${u6(this.url)}`));return this.events.emit("register_error",r),r}}var mF=Object.defineProperty,p6=Object.getOwnPropertySymbols,bF=Object.prototype.hasOwnProperty,yF=Object.prototype.propertyIsEnumerable,f6=(t,e,r)=>e in t?mF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e)=>{for(var r in e||(e={}))bF.call(e,r)&&f6(t,r,e[r]);if(p6)for(var r of p6(e))yF.call(e,r)&&f6(t,r,e[r]);return t};const g6="wc",w6=2,zp="core",Ci=`${g6}@2:${zp}:`,vF={name:zp,logger:"error"},EF={database:":memory:"},CF="crypto",m6="client_ed25519_seed",xF=z.ONE_DAY,$F="keychain",_F="0.3",IF="messages",SF="0.3",b6=z.SIX_HOURS,AF="publisher",y6="irn",PF="error",v6="wss://relay.walletconnect.org",OF="relayer",Yt={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},NF="_subscription",On={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},TF=.1,yw="2.20.2",gt={link_mode:"link_mode",relay:"relay"},qp={inbound:"inbound",outbound:"outbound"},kF="0.3",RF="WALLETCONNECT_CLIENT_ID",E6="WALLETCONNECT_LINK_MODE_APPS",dn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},DF="subscription",BF="0.3",UF="pairing",LF="0.3",Du={wc_pairingDelete:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:z.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:z.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:z.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:z.ONE_DAY,prompt:!1,tag:0},res:{ttl:z.ONE_DAY,prompt:!1,tag:0}}},zo={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Qn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},FF="history",MF="0.3",jF="expirer",Nn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},zF="0.3",qF="verify-api",HF="https://verify.walletconnect.com",C6="https://verify.walletconnect.org",Bu=C6,WF=`${Bu}/v3`,VF=[HF,C6],KF="echo",GF="https://echo.walletconnect.com",xi={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},ns={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},ei={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},qo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ho={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Uu={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},ZF=.1,YF="event-client",JF=86400,XF="https://pulse.walletconnect.org/batch";function QF(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,p=0,b=0,m=g.length;b!==m&&g[b]===0;)b++,w++;for(var E=(m-b)*u+1>>>0,C=new Uint8Array(E);b!==m;){for(var P=g[b],S=0,I=E-1;(P!==0||S<p)&&I!==-1;I--,S++)P+=256*C[I]>>>0,C[I]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");p=S,b++}for(var N=E-p;N!==E&&C[N]===0;)N++;for(var $=c.repeat(w);N<E;++N)$+=t.charAt(C[N]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var p=0,b=0;g[w]===c;)p++,w++;for(var m=(g.length-w)*l+1>>>0,E=new Uint8Array(m);g[w];){var C=r[g.charCodeAt(w)];if(C===255)return;for(var P=0,S=m-1;(C!==0||P<b)&&S!==-1;S--,P++)C+=a*E[S]>>>0,E[S]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");b=P,w++}if(g[w]!==" "){for(var I=m-b;I!==m&&E[I]===0;)I++;for(var N=new Uint8Array(p+(m-I)),$=p;I!==m;)N[$++]=E[I++];return N}}}function f(g){var w=h(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var eM=QF,tM=eM;const x6=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},rM=t=>new TextEncoder().encode(t),nM=t=>new TextDecoder().decode(t);class iM{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class sM{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return $6(this,e)}}class oM{constructor(e){this.decoders=e}or(e){return $6(this,e)}decode(e){const r=e[0],n=this.decoders[r];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 $6=(t,e)=>new oM(Tr(Tr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class aM{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new iM(e,r,n),this.decoder=new sM(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Hp=({name:t,prefix:e,encode:r,decode:n})=>new aM(t,e,r,n),Lu=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=tM(r,e);return Hp({prefix:t,name:e,encode:n,decode:s=>x6(i(s))})},cM=(t,e,r,n)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},lM=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},dr=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Hp({prefix:e,name:t,encode(i){return lM(i,n,r)},decode(i){return cM(i,n,r,t)}}),uM=Hp({prefix:"\0",name:"identity",encode:t=>nM(t),decode:t=>rM(t)});var dM=Object.freeze({__proto__:null,identity:uM});const hM=dr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pM=Object.freeze({__proto__:null,base2:hM});const fM=dr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gM=Object.freeze({__proto__:null,base8:fM});const wM=Lu({prefix:"9",name:"base10",alphabet:"0123456789"});var mM=Object.freeze({__proto__:null,base10:wM});const bM=dr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yM=dr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vM=Object.freeze({__proto__:null,base16:bM,base16upper:yM});const EM=dr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),CM=dr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xM=dr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$M=dr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_M=dr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),IM=dr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),SM=dr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),AM=dr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PM=dr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var OM=Object.freeze({__proto__:null,base32:EM,base32upper:CM,base32pad:xM,base32padupper:$M,base32hex:_M,base32hexupper:IM,base32hexpad:SM,base32hexpadupper:AM,base32z:PM});const NM=Lu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),TM=Lu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var kM=Object.freeze({__proto__:null,base36:NM,base36upper:TM});const RM=Lu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),DM=Lu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var BM=Object.freeze({__proto__:null,base58btc:RM,base58flickr:DM});const UM=dr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),LM=dr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),FM=dr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),MM=dr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jM=Object.freeze({__proto__:null,base64:UM,base64pad:LM,base64url:FM,base64urlpad:MM});const _6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),zM=_6.reduce((t,e,r)=>(t[r]=e,t),[]),qM=_6.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function HM(t){return t.reduce((e,r)=>(e+=zM[r],e),"")}function WM(t){const e=[];for(const r of t){const n=qM[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const VM=Hp({prefix:"\u{1F680}",name:"base256emoji",encode:HM,decode:WM});var KM=Object.freeze({__proto__:null,base256emoji:VM}),GM=S6,I6=128,ZM=127,YM=~ZM,JM=Math.pow(2,31);function S6(t,e,r){e=e||[],r=r||0;for(var n=r;t>=JM;)e[r++]=t&255|I6,t/=128;for(;t&YM;)e[r++]=t&255|I6,t>>>=7;return e[r]=t|0,S6.bytes=r-n+1,e}var XM=vw,QM=128,A6=127;function vw(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw vw.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&A6)<<i:(o&A6)*Math.pow(2,i),i+=7}while(o>=QM);return vw.bytes=s-n,r}var ej=Math.pow(2,7),tj=Math.pow(2,14),rj=Math.pow(2,21),nj=Math.pow(2,28),ij=Math.pow(2,35),sj=Math.pow(2,42),oj=Math.pow(2,49),aj=Math.pow(2,56),cj=Math.pow(2,63),lj=function(t){return t<ej?1:t<tj?2:t<rj?3:t<nj?4:t<ij?5:t<sj?6:t<oj?7:t<aj?8:t<cj?9:10},uj={encode:GM,decode:XM,encodingLength:lj},P6=uj;const O6=(t,e,r=0)=>(P6.encode(t,e,r),e),N6=t=>P6.encodingLength(t),Ew=(t,e)=>{const r=e.byteLength,n=N6(t),i=n+N6(r),s=new Uint8Array(i+r);return O6(t,s,0),O6(r,s,n),s.set(e,i),new dj(t,r,e,s)};class dj{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const T6=({name:t,code:e,encode:r})=>new hj(t,e,r);class hj{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ew(this.code,r):r.then(n=>Ew(this.code,n))}else throw Error("Unknown type, must be binary type")}}const k6=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),pj=T6({name:"sha2-256",code:18,encode:k6("SHA-256")}),fj=T6({name:"sha2-512",code:19,encode:k6("SHA-512")});var gj=Object.freeze({__proto__:null,sha256:pj,sha512:fj});const R6=0,wj="identity",D6=x6;var mj=Object.freeze({__proto__:null,identity:{code:R6,name:wj,encode:D6,digest:t=>Ew(R6,D6(t))}});new TextEncoder,new TextDecoder;const B6=Tr(Tr(Tr(Tr(Tr(Tr(Tr(Tr(Tr(Tr({},dM),pM),gM),mM),vM),OM),kM),BM),jM),KM);Tr(Tr({},gj),mj);function bj(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function U6(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const L6=U6("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cw=U6("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=bj(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yj=Tr({utf8:L6,"utf-8":L6,hex:B6.base16,latin1:Cw,ascii:Cw,binary:Cw},B6);function vj(t,e="utf8"){const r=yj[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var Ej=Object.defineProperty,Cj=(t,e,r)=>e in t?Ej(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$i=(t,e,r)=>Cj(t,typeof e!="symbol"?e+"":e,r);class xj{constructor(e,r){this.core=e,this.logger=r,$i(this,"keychain",new Map),$i(this,"name",$F),$i(this,"version",_F),$i(this,"initialized",!1),$i(this,"storagePrefix",Ci),$i(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),$i(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),$i(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),$i(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=J("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),$i(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=We(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ag(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $j=Object.defineProperty,_j=(t,e,r)=>e in t?$j(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hr=(t,e,r)=>_j(t,typeof e!="symbol"?e+"":e,r);class Ij{constructor(e,r,n){this.core=e,this.logger=r,hr(this,"name",CF),hr(this,"keychain"),hr(this,"randomSessionIdentifier",nw()),hr(this,"initialized",!1),hr(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),hr(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),hr(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=gp(i);return xg(s.publicKey)}),hr(this,"generateKeyPair",()=>{this.isInitialized();const i=lB();return this.setPrivateKey(i.publicKey,i.privateKey)}),hr(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=gp(s),a=this.randomSessionIdentifier;return await F3(a,i,xF,o)}),hr(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=uB(a,s);return this.setSymKey(c,o)}),hr(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Pp(i);return await this.keychain.set(o,i),o}),hr(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),hr(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),hr(this,"encode",async(i,s,o)=>{this.isInitialized();const a=x4(o),c=wi(s);if(_4(a))return pB(c,o?.encoding);if($4(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return dB({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),hr(this,"decode",async(i,s,o)=>{this.isInitialized();const a=gB(s,o);if(_4(a)){const c=fB(s,o?.encoding);return Wi(c)}if($4(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=hB({symKey:c,encoded:s,encoding:o?.encoding});return Wi(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),hr(this,"getPayloadType",(i,s=Yn)=>{const o=$u({encoded:i,encoding:s});return Fo(o.type)}),hr(this,"getPayloadSenderPublicKey",(i,s=Yn)=>{const o=$u({encoded:i,encoding:s});return o.senderPublicKey?tt(o.senderPublicKey,Or):void 0}),this.core=e,this.logger=We(r,this.name),this.keychain=n||new xj(this.core,this.logger)}get context(){return it(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(m6)}catch{e=nw(),await this.keychain.set(m6,e)}return vj(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Sj=Object.defineProperty,Aj=Object.defineProperties,Pj=Object.getOwnPropertyDescriptors,F6=Object.getOwnPropertySymbols,Oj=Object.prototype.hasOwnProperty,Nj=Object.prototype.propertyIsEnumerable,xw=(t,e,r)=>e in t?Sj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tj=(t,e)=>{for(var r in e||(e={}))Oj.call(e,r)&&xw(t,r,e[r]);if(F6)for(var r of F6(e))Nj.call(e,r)&&xw(t,r,e[r]);return t},kj=(t,e)=>Aj(t,Pj(e)),hn=(t,e,r)=>xw(t,typeof e!="symbol"?e+"":e,r);class Rj extends mL{constructor(e,r){super(e,r),this.logger=e,this.core=r,hn(this,"messages",new Map),hn(this,"messagesWithoutClientAck",new Map),hn(this,"name",IF),hn(this,"version",SF),hn(this,"initialized",!1),hn(this,"storagePrefix",Ci),hn(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),hn(this,"set",async(n,i,s)=>{this.isInitialized();const o=vi(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===qp.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,kj(Tj({},c),{[o]:i}))}return await this.persist(),o}),hn(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),hn(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),hn(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=vi(i);return typeof s[o]<"u"}),hn(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=vi(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),hn(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=We(e,this.name),this.core=r}get context(){return it(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,Ag(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ag(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pg(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Pg(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Dj=Object.defineProperty,Bj=Object.defineProperties,Uj=Object.getOwnPropertyDescriptors,M6=Object.getOwnPropertySymbols,Lj=Object.prototype.hasOwnProperty,Fj=Object.prototype.propertyIsEnumerable,$w=(t,e,r)=>e in t?Dj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wp=(t,e)=>{for(var r in e||(e={}))Lj.call(e,r)&&$w(t,r,e[r]);if(M6)for(var r of M6(e))Fj.call(e,r)&&$w(t,r,e[r]);return t},_w=(t,e)=>Bj(t,Uj(e)),ti=(t,e,r)=>$w(t,typeof e!="symbol"?e+"":e,r);class Mj extends bL{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ti(this,"events",new nt.exports.EventEmitter),ti(this,"name",AF),ti(this,"queue",new Map),ti(this,"publishTimeout",z.toMiliseconds(z.ONE_MINUTE)),ti(this,"initialPublishTimeout",z.toMiliseconds(z.ONE_SECOND*15)),ti(this,"needsTransportRestart",!1),ti(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||b6,c=Op(s),l=s?.prompt||!1,u=s?.tag||0,d=s?.id||un().toString(),h={topic:n,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}},f=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const g=new Promise(async w=>{const p=({id:m})=>{h.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Yt.publish,p),w(h))};this.relayer.events.on(Yt.publish,p);const b=qs(new Promise((m,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}).then(m).catch(C=>{this.logger.warn(C,C?.message),E(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await b,this.events.removeListener(Yt.publish,p)}catch(m){this.queue.set(d,_w(Wp({},h),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}}),await qs(g,this.publishTimeout,f)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(d)}}),ti(this,"on",(n,i)=>{this.events.on(n,i)}),ti(this,"once",(n,i)=>{this.events.once(n,i)}),ti(this,"off",(n,i)=>{this.events.off(n,i)}),ti(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=We(r,this.name),this.registerEventListeners()}get context(){return it(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=b6,prompt:l,tag:u,id:d,attestation:h,tvf:f}=e,g={method:_u(Op().protocol).publish,params:Wp({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:h},f),id:d};ur((r=g.params)==null?void 0:r.prompt)&&((n=g.params)==null||delete n.prompt),ur((i=g.params)==null?void 0:i.tag)&&((s=g.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const w=await this.relayer.request(g);return this.relayer.events.emit(Yt.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,_w(Wp({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(_w(Wp({},e),{topic:i,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Xn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Yt.connection_stalled);return}this.checkQueue()}),this.relayer.on(Yt.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var jj=Object.defineProperty,zj=(t,e,r)=>e in t?jj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vc=(t,e,r)=>zj(t,typeof e!="symbol"?e+"":e,r);class qj{constructor(){vc(this,"map",new Map),vc(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),vc(this,"get",e=>this.map.get(e)||[]),vc(this,"exists",(e,r)=>this.get(e).includes(r)),vc(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),vc(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Hj=Object.defineProperty,Wj=Object.defineProperties,Vj=Object.getOwnPropertyDescriptors,j6=Object.getOwnPropertySymbols,Kj=Object.prototype.hasOwnProperty,Gj=Object.prototype.propertyIsEnumerable,Iw=(t,e,r)=>e in t?Hj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e)=>{for(var r in e||(e={}))Kj.call(e,r)&&Iw(t,r,e[r]);if(j6)for(var r of j6(e))Gj.call(e,r)&&Iw(t,r,e[r]);return t},Sw=(t,e)=>Wj(t,Vj(e)),st=(t,e,r)=>Iw(t,typeof e!="symbol"?e+"":e,r);class Zj extends EL{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,st(this,"subscriptions",new Map),st(this,"topicMap",new qj),st(this,"events",new nt.exports.EventEmitter),st(this,"name",DF),st(this,"version",BF),st(this,"pending",new Map),st(this,"cached",[]),st(this,"initialized",!1),st(this,"storagePrefix",Ci),st(this,"subscribeTimeout",z.toMiliseconds(z.ONE_MINUTE)),st(this,"initialSubscribeTimeout",z.toMiliseconds(z.ONE_SECOND*15)),st(this,"clientId"),st(this,"batchSubscribeTopicsLimit",500),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),st(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Op(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),st(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),st(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),st(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),st(this,"on",(n,i)=>{this.events.on(n,i)}),st(this,"once",(n,i)=>{this.events.once(n,i)}),st(this,"off",(n,i)=>{this.events.off(n,i)}),st(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),st(this,"start",async()=>{await this.onConnect()}),st(this,"stop",async()=>{await this.onDisconnect()}),st(this,"restart",async()=>{await this.restore(),await this.onRestart()}),st(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),st(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Xn.pulse,async()=>{await this.checkPending()}),this.events.on(dn.created,async n=>{const i=dn.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(dn.deleted,async n=>{const i=dn.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=We(r,this.name),this.clientId=""}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}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,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Op(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=Ze("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i;(!n||n?.transportType===gt.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:_u(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===gt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},z.toMiliseconds(z.ONE_SECOND)),a;const c=new Promise(async u=>{const d=h=>{h.topic===e&&(this.events.removeListener(dn.created,d),u(h.id))};this.events.on(dn.created,d);try{const h=await qs(new Promise((f,g)=>{this.relayer.request(s).catch(w=>{this.logger.warn(w,w?.message),g(w)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(dn.created,d),u(h)}catch{}}),l=await qs(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Yt.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:_u(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await qs(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Yt.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:_u(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await qs(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Yt.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:_u(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Sw(Fu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Fu({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,Fu({},r)),this.topicMap.set(r.topic,e),this.events.emit(dn.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(dn.deleted,Sw(Fu({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(dn.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(dn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Sw(Fu({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await Xk(z.toMiliseconds(z.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=J("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 vi(e+await this.getClientId())}}var Yj=Object.defineProperty,z6=Object.getOwnPropertySymbols,Jj=Object.prototype.hasOwnProperty,Xj=Object.prototype.propertyIsEnumerable,Aw=(t,e,r)=>e in t?Yj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,q6=(t,e)=>{for(var r in e||(e={}))Jj.call(e,r)&&Aw(t,r,e[r]);if(z6)for(var r of z6(e))Xj.call(e,r)&&Aw(t,r,e[r]);return t},Ue=(t,e,r)=>Aw(t,typeof e!="symbol"?e+"":e,r);class Qj extends yL{constructor(e){super(e),Ue(this,"protocol","wc"),Ue(this,"version",2),Ue(this,"core"),Ue(this,"logger"),Ue(this,"events",new nt.exports.EventEmitter),Ue(this,"provider"),Ue(this,"messages"),Ue(this,"subscriber"),Ue(this,"publisher"),Ue(this,"name",OF),Ue(this,"transportExplicitlyClosed",!1),Ue(this,"initialized",!1),Ue(this,"connectionAttemptInProgress",!1),Ue(this,"relayUrl"),Ue(this,"projectId"),Ue(this,"packageName"),Ue(this,"bundleId"),Ue(this,"hasExperiencedNetworkDisruption",!1),Ue(this,"pingTimeout"),Ue(this,"heartBeatTimeout",z.toMiliseconds(z.THIRTY_SECONDS+z.FIVE_SECONDS)),Ue(this,"reconnectTimeout"),Ue(this,"connectPromise"),Ue(this,"reconnectInProgress",!1),Ue(this,"requestsInFlight",[]),Ue(this,"connectTimeout",z.toMiliseconds(z.ONE_SECOND*15)),Ue(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||un().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),Ue(this,"resetPingTimeout",()=>{mp()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Ue(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Yt.connect)}),Ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ue(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Yt.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ue(this,"registerProviderListeners",()=>{this.provider.on(On.payload,this.onPayloadHandler),this.provider.on(On.connect,this.onConnectHandler),this.provider.on(On.disconnect,this.onDisconnectHandler),this.provider.on(On.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?We(e.logger,this.name):ln(es({level:e.logger||PF})),this.messages=new Rj(this.logger,e.core),this.subscriber=new Zj(this,this.logger),this.publisher=new Mj(this,this.logger),this.relayUrl=e?.relayUrl||v6,this.projectId=e.projectId,Bk()?this.packageName=h5():Uk()&&(this.bundleId=h5()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return it(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:gt.relay},qp.outbound)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(dn.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(dn.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,q6({internal:{throwOnFailedPublish:o}},r)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await qs(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(e).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await D4())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=Rt(z.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Yt.message,e),await this.recordMessageEvent(e,qp.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(On.disconnect,s),await qs(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(On.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(On.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(On.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,z.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(mp())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new bt(new h6(zk({sdkVersion:yw,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),yc(e)){if(!e.method.endsWith(NF))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:gt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(q6({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else jo(e)&&this.events.emit(Yt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,qp.inbound),this.events.emit(Yt.message,e))}async acknowledgePayload(e){const r=Zs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(On.payload,this.onPayloadHandler),this.provider.off(On.connect,this.onConnectHandler),this.provider.off(On.disconnect,this.onDisconnectHandler),this.provider.off(On.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await D4();eU(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Yt.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},z.toMiliseconds(TF)))))}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function ez(){}function H6(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function W6(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function V6(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const tz="[object RegExp]",rz="[object String]",nz="[object Number]",iz="[object Boolean]",K6="[object Arguments]",sz="[object Symbol]",oz="[object Date]",az="[object Map]",cz="[object Set]",lz="[object Array]",uz="[object Function]",dz="[object ArrayBuffer]",Pw="[object Object]",hz="[object Error]",pz="[object DataView]",fz="[object Uint8Array]",gz="[object Uint8ClampedArray]",wz="[object Uint16Array]",mz="[object Uint32Array]",bz="[object BigUint64Array]",yz="[object Int8Array]",vz="[object Int16Array]",Ez="[object Int32Array]",Cz="[object BigInt64Array]",xz="[object Float32Array]",$z="[object Float64Array]";function _z(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Iz(t,e,r){return Mu(t,e,void 0,void 0,void 0,void 0,r)}function Mu(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return ju(t,e,s,o)}return ju(t,e,s,o)}function ju(t,e,r,n){if(Object.is(t,e))return!0;let i=V6(t),s=V6(e);if(i===K6&&(i=Pw),s===K6&&(s=Pw),i!==s)return!1;switch(i){case rz:return t.toString()===e.toString();case nz:{const c=t.valueOf(),l=e.valueOf();return _z(c,l)}case iz:case oz:case sz:return Object.is(t.valueOf(),e.valueOf());case tz:return t.source===e.source&&t.flags===e.flags;case uz:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case az:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Mu(l,e.get(c),c,t,e,r,n))return!1;return!0}case cz:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(f=>Mu(d,f,void 0,t,e,r,n));if(h===-1)return!1;l.splice(h,1)}return!0}case lz:case fz:case gz:case wz:case mz:case bz:case yz:case vz:case Ez:case Cz:case xz:case $z:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Mu(t[c],e[c],c,t,e,r,n))return!1;return!0}case dz:return t.byteLength!==e.byteLength?!1:ju(new Uint8Array(t),new Uint8Array(e),r,n);case pz:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ju(new Uint8Array(t),new Uint8Array(e),r,n);case hz:return t.name===e.name&&t.message===e.message;case Pw:{if(!(ju(t.constructor,e.constructor,r,n)||H6(t)&&H6(e)))return!1;const c=[...Object.keys(t),...W6(t)],l=[...Object.keys(e),...W6(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=t[d];if(!Object.hasOwn(e,d))return!1;const f=e[d];if(!Mu(h,f,d,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function Sz(t,e){return Iz(t,e,ez)}var Az=Object.defineProperty,G6=Object.getOwnPropertySymbols,Pz=Object.prototype.hasOwnProperty,Oz=Object.prototype.propertyIsEnumerable,Ow=(t,e,r)=>e in t?Az(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z6=(t,e)=>{for(var r in e||(e={}))Pz.call(e,r)&&Ow(t,r,e[r]);if(G6)for(var r of G6(e))Oz.call(e,r)&&Ow(t,r,e[r]);return t},Vr=(t,e,r)=>Ow(t,typeof e!="symbol"?e+"":e,r);class Wo extends vL{constructor(e,r,n,i=Ci,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,Vr(this,"map",new Map),Vr(this,"version",kF),Vr(this,"cached",[]),Vr(this,"initialized",!1),Vr(this,"getKey"),Vr(this,"storagePrefix",Ci),Vr(this,"recentlyDeleted",[]),Vr(this,"recentlyDeletedLimit",200),Vr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ur(o)?this.map.set(this.getKey(o),o):NB(o)?this.map.set(o.id,o):TB(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Vr(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Vr(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Vr(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Sz(a[c],o[c]))):this.values)),Vr(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Z6(Z6({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Vr(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=We(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=J("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Nz=Object.defineProperty,Tz=(t,e,r)=>e in t?Nz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pe=(t,e,r)=>Tz(t,typeof e!="symbol"?e+"":e,r);class kz{constructor(e,r){this.core=e,this.logger=r,Pe(this,"name",UF),Pe(this,"version",LF),Pe(this,"events",new nt.exports),Pe(this,"pairings"),Pe(this,"initialized",!1),Pe(this,"storagePrefix",Ci),Pe(this,"ignoredPayloadTypes",[Qi]),Pe(this,"registeredMethods",[]),Pe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Pe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Pe(this,"create",async n=>{this.isInitialized();const i=nw(),s=await this.core.crypto.setSymKey(i),o=Rt(z.FIVE_MINUTES),a={protocol:y6},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},l=S4({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(zo.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:l}}),Pe(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[xi.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=I4(n.uri);i.props.properties.topic=s,i.addTrace(xi.pairing_uri_validation_success),i.addTrace(xi.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(xi.existing_pairing),u.active)throw i.setError(ns.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(xi.pairing_not_expired)}const d=c||Rt(z.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(xi.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(zo.create,h),i.addTrace(xi.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(xi.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(ns.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(ns.subscribe_pairing_topic_failure),f}return i.addTrace(xi.subscribe_pairing_topic_success),h}),Pe(this,"activate",async({topic:n})=>{this.isInitialized();const i=Rt(z.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Pe(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ro();this.events.once(He("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),Pe(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Pe(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Pe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Pe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Ze("USER_DISCONNECTED")),await this.deletePairing(i))}),Pe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return S4({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Pe(this,"sendRequest",async(n,i,s)=>{const o=Nr(i,s),a=await this.core.crypto.encode(n,o),c=Du[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Pe(this,"sendResult",async(n,i,s)=>{const o=Zs(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=Du[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),Pe(this,"sendError",async(n,i,s)=>{const o=bc(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=Du[c]?Du[c].res:Du.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),Pe(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ze("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Pe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>Hs(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Pe(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Pe(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Pe(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(zo.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Pe(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{Dt(i)?this.events.emit(He("pairing_ping",s),{}):Et(i)&&this.events.emit(He("pairing_ping",s),{error:i.error})},500)}),Pe(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(zo.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Pe(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Ze("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Pe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Ze("WC_METHOD_UNSUPPORTED",n))}),Pe(this,"isValidPair",(n,i)=>{var s;if(!Hr(n)){const{message:a}=J("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(ns.malformed_pairing_uri),new Error(a)}if(!OB(n.uri)){const{message:a}=J("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(ns.malformed_pairing_uri),new Error(a)}const o=I4(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=J("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(ns.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=J("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(ns.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&z.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(ns.pairing_expired);const{message:a}=J("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Pe(this,"isValidPing",async n=>{if(!Hr(n)){const{message:s}=J("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Pe(this,"isValidDisconnect",async n=>{if(!Hr(n)){const{message:s}=J("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Pe(this,"isValidPairingTopic",async n=>{if(!Pt(n,!1)){const{message:i}=J("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=J("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Hs(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=J("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=We(r,this.name),this.pairings=new Wo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return it(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Yt.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==gt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);yc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):jo(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Nn.expired,async e=>{const{topic:r}=w5(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(zo.expire,{topic:r}))})}}var Rz=Object.defineProperty,Dz=(t,e,r)=>e in t?Rz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pr=(t,e,r)=>Dz(t,typeof e!="symbol"?e+"":e,r);class Bz extends wL{constructor(e,r){super(e,r),this.core=e,this.logger=r,pr(this,"records",new Map),pr(this,"events",new nt.exports.EventEmitter),pr(this,"name",FF),pr(this,"version",MF),pr(this,"cached",[]),pr(this,"initialized",!1),pr(this,"storagePrefix",Ci),pr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),pr(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:Rt(z.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Qn.created,o)}),pr(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Et(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Qn.updated,i))}),pr(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),pr(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Qn.deleted,s)}}),this.persist()}),pr(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),pr(this,"on",(n,i)=>{this.events.on(n,i)}),pr(this,"once",(n,i)=>{this.events.once(n,i)}),pr(this,"off",(n,i)=>{this.events.off(n,i)}),pr(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=We(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:Nr(r.request.method,r.request.params,r.id),chainId:r.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 r=this.records.get(e);if(!r){const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Qn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Qn.created,e=>{const r=Qn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Qn.updated,e=>{const r=Qn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Qn.deleted,e=>{const r=Qn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Xn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{z.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Qn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Uz=Object.defineProperty,Lz=(t,e,r)=>e in t?Uz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_r=(t,e,r)=>Lz(t,typeof e!="symbol"?e+"":e,r);class Fz extends CL{constructor(e,r){super(e,r),this.core=e,this.logger=r,_r(this,"expirations",new Map),_r(this,"events",new nt.exports.EventEmitter),_r(this,"name",jF),_r(this,"version",zF),_r(this,"cached",[]),_r(this,"initialized",!1),_r(this,"storagePrefix",Ci),_r(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),_r(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),_r(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Nn.created,{target:s,expiration:o})}),_r(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),_r(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Nn.deleted,{target:i,expiration:s})}}),_r(this,"on",(n,i)=>{this.events.on(n,i)}),_r(this,"once",(n,i)=>{this.events.once(n,i)}),_r(this,"off",(n,i)=>{this.events.off(n,i)}),_r(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=We(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return qk(e);if(typeof e=="number")return Hk(e);const{message:r}=J("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Nn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=J("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=J("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;z.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Nn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Xn.pulse,()=>this.checkExpirations()),this.events.on(Nn.created,e=>{const r=Nn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Nn.expired,e=>{const r=Nn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Nn.deleted,e=>{const r=Nn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mz=Object.defineProperty,jz=(t,e,r)=>e in t?Mz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ot=(t,e,r)=>jz(t,typeof e!="symbol"?e+"":e,r);class zz extends xL{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,Ot(this,"name",qF),Ot(this,"abortController"),Ot(this,"isDevEnv"),Ot(this,"verifyUrlV3",WF),Ot(this,"storagePrefix",Ci),Ot(this,"version",w6),Ot(this,"publicKey"),Ot(this,"fetchPromise"),Ot(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&z.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ot(this,"register",async i=>{if(!du()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=Mi(),u=this.startAbortTimer(z.ONE_SECOND*5),d=await new Promise((h,f)=>{const g=()=>{window.removeEventListener("message",p),l.body.removeChild(w),f("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const p=b=>{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.data);if(m.type==="verify_attestation"){if(tc(m.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",p),h(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};l.body.appendChild(w),window.addEventListener("message",p,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),Ot(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(tc(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),Ot(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(z.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Ot(this,"getVerifyUrl",i=>{let s=i||Bu;return VF.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Bu}`),s=Bu),s}),Ot(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(z.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),Ot(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ot(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ot(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Ot(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ot(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),Ot(this,"validateAttestation",(i,s)=>{const o=mB(i,s.publicKey),a={hasExpired:z.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=We(r,this.name),this.abortController=new AbortController,this.isDevEnv=Og(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return it(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),z.toMiliseconds(e))}}var qz=Object.defineProperty,Hz=(t,e,r)=>e in t?qz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y6=(t,e,r)=>Hz(t,typeof e!="symbol"?e+"":e,r);class Wz extends $L{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Y6(this,"context",KF),Y6(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${GF}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=We(r,this.context)}}var Vz=Object.defineProperty,J6=Object.getOwnPropertySymbols,Kz=Object.prototype.hasOwnProperty,Gz=Object.prototype.propertyIsEnumerable,Nw=(t,e,r)=>e in t?Vz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zu=(t,e)=>{for(var r in e||(e={}))Kz.call(e,r)&&Nw(t,r,e[r]);if(J6)for(var r of J6(e))Gz.call(e,r)&&Nw(t,r,e[r]);return t},Jt=(t,e,r)=>Nw(t,typeof e!="symbol"?e+"":e,r);class Zz extends _L{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Jt(this,"context",YF),Jt(this,"storagePrefix",Ci),Jt(this,"storageVersion",ZF),Jt(this,"events",new Map),Jt(this,"shouldPersist",!1),Jt(this,"init",async()=>{if(!Og())try{const i={eventId:b5(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:f5(this.core.relayer.protocol,this.core.relayer.version,yw)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Jt(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=b5(),u=this.core.projectId||"",d=Date.now(),h=zu({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Jt(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return zu(zu({},a),this.setMethods(a.eventId))}),Jt(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Jt(this,"setEventListeners",()=>{this.core.heartbeat.on(Xn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{z.fromMiliseconds(Date.now())-z.fromMiliseconds(i.timestamp)>JF&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Jt(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Jt(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Jt(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Jt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Jt(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,zu(zu({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Jt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Jt(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${XF}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${yw}${s}`,{method:"POST",body:JSON.stringify(i)})}),Jt(this,"getAppDomain",()=>p5().url),this.logger=We(r,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}}var Yz=Object.defineProperty,X6=Object.getOwnPropertySymbols,Jz=Object.prototype.hasOwnProperty,Xz=Object.prototype.propertyIsEnumerable,Tw=(t,e,r)=>e in t?Yz(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q6=(t,e)=>{for(var r in e||(e={}))Jz.call(e,r)&&Tw(t,r,e[r]);if(X6)for(var r of X6(e))Xz.call(e,r)&&Tw(t,r,e[r]);return t},ht=(t,e,r)=>Tw(t,typeof e!="symbol"?e+"":e,r);class kw extends hL{constructor(e){var r;super(e),ht(this,"protocol",g6),ht(this,"version",w6),ht(this,"name",zp),ht(this,"relayUrl"),ht(this,"projectId"),ht(this,"customStoragePrefix"),ht(this,"events",new nt.exports.EventEmitter),ht(this,"logger"),ht(this,"heartbeat"),ht(this,"relayer"),ht(this,"crypto"),ht(this,"storage"),ht(this,"history"),ht(this,"expirer"),ht(this,"pairing"),ht(this,"verify"),ht(this,"echoClient"),ht(this,"linkModeSupportedApps"),ht(this,"eventClient"),ht(this,"initialized",!1),ht(this,"logChunkController"),ht(this,"on",(a,c)=>this.events.on(a,c)),ht(this,"once",(a,c)=>this.events.once(a,c)),ht(this,"off",(a,c)=>this.events.off(a,c)),ht(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ht(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:gt.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||v6,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=es({level:typeof e?.logger=="string"&&e.logger?e.logger:vF.logger,name:zp}),{logger:s,chunkLoggerController:o}=fw({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=We(s,this.name),this.heartbeat=new kp,this.crypto=new Ij(this,this.logger,e?.keychain),this.history=new Bz(this,this.logger),this.expirer=new Fz(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new z4(Q6(Q6({},EF),e?.storageOptions)),this.relayer=new Qj({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new kz(this,this.logger),this.verify=new zz(this,this.logger,this.storage),this.echoClient=new Wz(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Zz(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new kw(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(RF,n),r}get context(){return it(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(E6,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(E6)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,n=`${r}_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[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Qz=kw,e8="wc",t8=2,r8="client",Rw=`${e8}@${t8}:${r8}:`,Dw={name:r8,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},n8="WALLETCONNECT_DEEPLINK_CHOICE",eq="proposal",i8="Proposal expired",tq="session",Ec=z.SEVEN_DAYS,rq="engine",Xt={wc_sessionPropose:{req:{ttl:z.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1104},res:{ttl:z.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1106},res:{ttl:z.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:z.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:z.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1112},res:{ttl:z.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:z.ONE_DAY,prompt:!1,tag:1114},res:{ttl:z.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:z.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:z.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:z.FIVE_MINUTES,prompt:!1,tag:1119}}},Bw={min:z.FIVE_MINUTES,max:z.SEVEN_DAYS},_i={idle:"IDLE",active:"ACTIVE"},s8={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},nq="request",iq=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],sq="wc",oq="auth",aq="authKeys",cq="pairingTopics",lq="requests",Vp=`${sq}@${1.5}:${oq}:`,Kp=`${Vp}:PUB_KEY`;var uq=Object.defineProperty,dq=Object.defineProperties,hq=Object.getOwnPropertyDescriptors,o8=Object.getOwnPropertySymbols,pq=Object.prototype.hasOwnProperty,fq=Object.prototype.propertyIsEnumerable,Uw=(t,e,r)=>e in t?uq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ot=(t,e)=>{for(var r in e||(e={}))pq.call(e,r)&&Uw(t,r,e[r]);if(o8)for(var r of o8(e))fq.call(e,r)&&Uw(t,r,e[r]);return t},kr=(t,e)=>dq(t,hq(e)),V=(t,e,r)=>Uw(t,typeof e!="symbol"?e+"":e,r);class gq extends PL{constructor(e){super(e),V(this,"name",rq),V(this,"events",new nt.exports),V(this,"initialized",!1),V(this,"requestQueue",{state:_i.idle,queue:[]}),V(this,"sessionRequestQueue",{state:_i.idle,queue:[]}),V(this,"requestQueueDelay",z.ONE_SECOND),V(this,"expectedPairingMethodMap",new Map),V(this,"recentlyDeletedMap",new Map),V(this,"recentlyDeletedLimit",200),V(this,"relayMessageCache",[]),V(this,"pendingSessions",new Map),V(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Xt)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},z.toMiliseconds(this.requestQueueDelay)))}),V(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=kr(ot({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let u=i,d,h=!1;try{if(u){const S=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."),h=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),S}if(!u||!h){const{topic:S,uri:I}=await this.client.core.pairing.create();u=S,d=I}if(!u){const{message:S}=J("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(S)}const f=await this.client.core.crypto.generateKeyPair(),g=Xt.wc_sessionPropose.req.ttl||z.FIVE_MINUTES,w=Rt(g),p=kr(ot(ot({requiredNamespaces:s,optionalNamespaces:o,relays:l??[{protocol:y6}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Zt()}),b=He("session_connect",p.id),{reject:m,resolve:E,done:C}=Ro(g,i8),P=({id:S})=>{S===p.id&&(this.client.events.off("proposal_expire",P),this.pendingSessions.delete(p.id),this.events.emit(b,{error:{message:i8,code:0}}))};return this.client.events.on("proposal_expire",P),this.events.once(b,({error:S,session:I})=>{this.client.events.off("proposal_expire",P),S?m(S):I&&E(I)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:p,throwOnFailedPublish:!0,clientRpcId:p.id}),await this.setProposal(p.id,p),{uri:d,approval:C}}),V(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),V(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[ei.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch($){throw o.setError(qo.no_internet_connection),$}try{await this.isValidProposalId(r?.id)}catch($){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(qo.proposal_not_found),$}try{await this.isValidApprove(r)}catch($){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(qo.session_approve_namespace_validation_failure),$}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:p,optionalNamespaces:b}=f;let m=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});m||(m=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:ei.session_approve_started,properties:{topic:g,trace:[ei.session_approve_started,ei.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),C=w.publicKey,P=await this.client.core.crypto.generateSharedKey(E,C),S=ot(ot(ot({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:Rt(Ec)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),I=gt.relay;m.addTrace(ei.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:I})}catch($){throw m.setError(qo.subscribe_session_topic_failure),$}m.addTrace(ei.subscribe_session_topic_success);const N=kr(ot({},S),{topic:P,requiredNamespaces:p,optionalNamespaces:b,pairingTopic:g,acknowledged:!1,self:S.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:E,transportType:gt.relay});await this.client.session.set(P,N),m.addTrace(ei.store_session);try{m.addTrace(ei.publishing_session_settle),await this.sendRequest({topic:P,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch($=>{throw m?.setError(qo.session_settle_publish_failure),$}),m.addTrace(ei.session_settle_publish_success),m.addTrace(ei.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch($=>{throw m?.setError(qo.session_approve_publish_failure),$}),m.addTrace(ei.session_approve_publish_success)}catch($){throw this.client.logger.error($),this.client.session.delete(P,Ze("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),$}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.client.proposal.delete(a,Ze("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,Rt(Ec)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),V(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i,rpcOpts:Xt.wc_sessionPropose.reject}),await this.client.proposal.delete(n,Ze("USER_DISCONNECTED")))}),V(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=Ro(),c=Zt(),l=un().toString(),u=this.client.session.get(n).namespaces;return this.events.once(He("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:u}),a(d)}),{acknowledged:s}}),V(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=Zt(),{done:s,resolve:o,reject:a}=Ro();return this.events.once(He("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,Rt(Ec)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),V(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:n,request:i,topic:s,expiry:o=Xt.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===gt.relay&&await this.confirmOnlineStateOrThrow();const c=Zt(),l=un().toString(),{done:u,resolve:d,reject:h}=Ro(o,"Request expired. Please try again.");this.events.once(He("session_request",c),({error:b,result:m})=>{b?h(b):d(m)});const f="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:kr(ot({},i),{expiryTimestamp:Rt(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await u();const w={request:kr(ot({},i),{expiryTimestamp:Rt(o)}),chainId:n},p=this.shouldSetTVF(f,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(ot({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:w,expiry:o,throwOnFailedPublish:!0},p&&{tvf:this.getTVFParams(c,w)})).catch(m=>h(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const E=await Gk(this.client.core.storage,n8);await Wk({id:c,topic:s,wcDeepLink:E})}b()}),u()]).then(b=>b[2])}),V(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===gt.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Dt(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):Et(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),V(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=Zt(),s=un().toString(),{done:o,resolve:a,reject:c}=Ro();this.events.once(He("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(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:n}))}),V(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=un().toString(),a=Zt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),V(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Ze("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=J("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),V(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>AB(n,r)))),V(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),V(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?gt.link_mode:gt.relay;o===gt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:g,methods:w=[],expiry:p}=r,b=[...r.resources||[]],{topic:m,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:E}});const C=await this.client.core.crypto.generateKeyPair(),P=Pp(C);if(await Promise.all([this.client.auth.authKeys.set(Kp,{responseTopic:P,publicKey:C}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:m})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),w.length>0){const{namespace:_}=rc(a[0]);let k=FR(_,"request",w);Ep(b)&&(k=jR(k,b.pop())),b.push(k)}const S=p&&p>Xt.wc_sessionAuthenticate.req.ttl?p:Xt.wc_sessionAuthenticate.req.ttl,I={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:g,resources:b},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Rt(S)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Rt(Xt.wc_sessionPropose.req.ttl),id:Zt()},{done:D,resolve:T,reject:R}=Ro(S,"Request expired"),M=Zt(),x=He("session_connect",$.id),y=He("session_request",M),v=async({error:_,session:k})=>{this.events.off(y,A),_?R(_):k&&T({session:k})},A=async _=>{var k,L,F;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),_.error){const te=Ze("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===te.code?void 0:(this.events.off(x,v),R(_.error.message))}await this.deleteProposal($.id),this.events.off(x,v);const{cacaos:H,responder:q}=_.result,W=[],Y=[];for(const te of H){await k5({cacao:te,projectId:this.client.core.projectId})||(this.client.logger.error(te,"Signature verification failed"),R(Ze("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ee}=te,Ce=Ep(Ee.resources),xe=[Bg(Ee.iss)],_e=vp(Ee.iss);if(Ce){const Ge=B5(Ce),xr=U5(Ce);W.push(...Ge),xe.push(...xr)}for(const Ge of xe)Y.push(`${Ge}:${_e}`)}const ae=await this.client.core.crypto.generateSharedKey(C,q.publicKey);let re;W.length>0&&(re={topic:ae,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:Rt(Ec),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:A4([...new Set(W)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(ae,{transportType:o}),await this.client.session.set(ae,re),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:q.metadata}),re=this.client.session.get(ae)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(L=q.metadata.redirect)!=null&&L.linkMode&&(F=q.metadata.redirect)!=null&&F.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ae,{transportType:gt.link_mode})),T({auths:H,session:re})};this.events.once(x,v),this.events.once(y,A);let O;try{if(s){const _=Nr("wc_sessionAuthenticate",I,M);this.client.core.history.set(m,_);const k=await this.client.core.crypto.encode("",_,{type:Cu,encoding:Gs});O=Np(n,m,k)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:I,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:$,expiry:Xt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(_){throw this.events.off(x,v),this.events.off(y,A),_}return await this.setProposal($.id,$),await this.setAuthRequest(M,{request:kr(ot({},I),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:O??E,response:D}}),V(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ho.authenticated_session_approve_started]}});try{this.isInitialized()}catch(p){throw s.setError(Uu.no_internet_connection),p}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Uu.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||gt.relay;a===gt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Pp(c),d={type:Qi,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const p of i){if(!await k5({cacao:p,projectId:this.client.core.projectId})){s.setError(Uu.invalid_cacao);const P=Ze("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:P,encodeOpts:d}),new Error(P.message)}s.addTrace(Ho.cacaos_verified);const{p:b}=p,m=Ep(b.resources),E=[Bg(b.iss)],C=vp(b.iss);if(m){const P=B5(m),S=U5(m);h.push(...P),E.push(...S)}for(const P of E)f.push(`${P}:${C}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Ho.create_authenticated_session_topic);let w;if(h?.length>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Rt(Ec),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:A4([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Ho.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(p){throw s.setError(Uu.subscribe_authenticated_session_topic_failure),p}s.addTrace(Ho.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),s.addTrace(Ho.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ho.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(p){throw s.setError(Uu.authenticated_session_approve_publish_failure),p}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}}),V(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===gt.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Pp(o),l={type:Qi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:l,rpcOpts:Xt.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,Ze("USER_DISCONNECTED"))}),V(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return R5(n,i)}),V(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),V(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),V(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Ze("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(n8).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,Ze("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=_i.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),V(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(qo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Ze("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),V(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=_i.idle,this.client.events.emit("session_request_expire",{id:r}))}),V(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),V(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),V(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,Rt(Xt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),V(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=gt.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),V(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||Rt(Xt.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),V(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=r,h=Nr(i,s,c);let f;const g=!!u;try{const b=g?Gs:Yn;f=await this.client.core.crypto.encode(n,h,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),b}let w;if(iq.includes(i)){const b=vi(JSON.stringify(h)),m=vi(f);w=await this.client.core.verify.register({id:m,decryptedId:b})}const p=Xt[i].req;if(p.attestation=w,o&&(p.ttl=o),a&&(p.id=a),this.client.core.history.set(n,h),g){const b=Np(u,n,f);await global.Linking.openURL(b,this.client.name)}else{const b=Xt[i].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=kr(ot({},d),{correlationId:h.id}),l?(b.internal=kr(ot({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,f,b)):this.client.core.relayer.publish(n,f,b).catch(m=>this.client.logger.error(m))}return h.id}),V(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=Zs(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=d?Gs:Yn;u=await this.client.core.crypto.encode(i,l,kr(ot({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),g}let h,f;try{h=await this.client.core.history.get(i,n);const g=h.request;try{this.shouldSetTVF(g.method,g.params)&&(f=this.getTVFParams(n,g.params,s))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),g}if(d){const g=Np(c,i,u);await global.Linking.openURL(g,this.client.name)}else{const g=h.request.method,w=Xt[g].res;w.tvf=kr(ot({},f),{correlationId:n}),o?(w.internal=kr(ot({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,w)):this.client.core.relayer.publish(i,u,w).catch(p=>this.client.logger.error(p))}await this.client.core.history.resolve(l)}),V(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=bc(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?Gs:Yn;u=await this.client.core.crypto.encode(i,l,kr(ot({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,n)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),f}if(d){const f=Np(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,g=a||Xt[f].res;this.client.core.relayer.publish(i,u,g)}await this.client.core.history.resolve(l)}),V(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;Hs(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Hs(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),V(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),V(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),V(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===_i.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=_i.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=_i.idle}),V(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),V(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),V(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=J("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),V(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),V(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ns.proposal_listener_not_found)),this.isValidConnect(ot({},i.params));const u=a.expiryTimestamp||Rt(Xt.wc_sessionPropose.req.ttl),d=ot({id:c,pairingTopic:n,expiryTimestamp:u},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:vi(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(xi.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:Xt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),V(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(Dt(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:r,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:r})}else if(Et(n)){await this.client.proposal.delete(s,Ze("USER_DISCONNECTED"));const o=He("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),V(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=n.params,f=[...this.pendingSessions.values()].find(p=>p.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(f.proposalId),w=kr(ot(ot(ot({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:gt.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit(He("session_connect",f.proposalId),{session:w}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),V(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;Dt(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(He("session_approve",i),{})):Et(n)&&(await this.client.session.delete(r,Ze("USER_DISCONNECTED")),this.events.emit(He("session_approve",i),{error:n.error}))}),V(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Au.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Ze("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ot({topic:r},i));try{Au.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Au.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),V(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),V(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=He("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Dt(n)?this.events.emit(He("session_update",i),{}):Et(n)&&this.events.emit(He("session_update",i),{error:n.error})}),V(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Rt(Ec)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),V(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=He("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Dt(n)?this.events.emit(He("session_extend",i),{}):Et(n)&&this.events.emit(He("session_extend",i),{error:n.error})}),V(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),V(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=He("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Dt(n)?this.events.emit(He("session_ping",i),{}):Et(n)&&this.events.emit(He("session_ping",i),{error:n.error})},500)}),V(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Yt.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Ze("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),V(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:d,params:h}=a;try{await this.isValidRequest(ot({topic:o},h));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:vi(JSON.stringify(Nr("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),w={id:d,topic:o,params:h,verifyContext:g};await this.setPendingSessionRequest(w),u===gt.link_mode&&(n=f.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),V(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=He("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Dt(n)?this.events.emit(He("session_request",i),{result:n.result}):Et(n)&&this.events.emit(He("session_request",i),{error:n.error})}),V(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Au.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ot({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Au.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),V(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Dt(n)?this.events.emit(He("session_request",i),{result:n.result}):Et(n)&&this.events.emit(He("session_request",i),{error:n.error})}),V(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:vi(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===gt.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:Qi,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Xt.wc_sessionAuthenticate.autoReject,appLink:h})}}),V(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),V(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=_i.idle,this.processSessionRequestQueue()},z.toMiliseconds(this.requestQueueDelay))}),V(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=He("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(He("session_request",s.request.id),{error:n})})}),V(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===_i.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=_i.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),V(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),V(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:Nr("wc_sessionPropose",kr(ot({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),V(this,"isValidConnect",async r=>{if(!Hr(r)){const{message:l}=J("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(ur(n)||await this.isValidPairingTopic(n),!MB(c,!0)){const{message:l}=J("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!ur(i)&&Su(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!ur(s)&&Su(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ur(o)||this.validateSessionProps(o,"sessionProperties"),!ur(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),V(this,"validateNamespaces",(r,n)=>{const i=FB(r,"connect()",n);if(i)throw new Error(i.message)}),V(this,"isValidApprove",async r=>{if(!Hr(r))throw new Error(J("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=ow(i,"approve()");if(l)throw new Error(l.message);const u=k4(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!Pt(s,!0)){const{message:d}=J("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(ur(o)||this.validateSessionProps(o,"sessionProperties"),!ur(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),V(this,"isValidReject",async r=>{if(!Hr(r)){const{message:s}=J("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!zB(i)){const{message:s}=J("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),V(this,"isValidSessionSettleRequest",r=>{if(!Hr(r)){const{message:l}=J("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!N4(n)){const{message:l}=J("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=kB(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ow(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Hs(o)){const{message:l}=J("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),V(this,"isValidUpdate",async r=>{if(!Hr(r)){const{message:c}=J("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=ow(i,"update()");if(o)throw new Error(o.message);const a=k4(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),V(this,"isValidExtend",async r=>{if(!Hr(r)){const{message:i}=J("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),V(this,"isValidRequest",async r=>{if(!Hr(r)){const{message:c}=J("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!T4(a,s)){const{message:c}=J("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!qB(i)){const{message:c}=J("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!VB(a,s,i.method)){const{message:c}=J("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!YB(o,Bw)){const{message:c}=J("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Bw.min} and ${Bw.max}`);throw new Error(c)}}),V(this,"isValidRespond",async r=>{var n;if(!Hr(r)){const{message:o}=J("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!HB(s)){const{message:o}=J("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),V(this,"isValidPing",async r=>{if(!Hr(r)){const{message:i}=J("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),V(this,"isValidEmit",async r=>{if(!Hr(r)){const{message:a}=J("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!T4(o,s)){const{message:a}=J("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!WB(i)){const{message:a}=J("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!KB(o,s,i.name)){const{message:a}=J("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),V(this,"isValidDisconnect",async r=>{if(!Hr(r)){const{message:i}=J("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),V(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!Pt(i,!1))throw new Error("uri is required parameter");if(!Pt(s,!1))throw new Error("domain is required parameter");if(!Pt(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>rc(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=rc(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),V(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Bu,validation:"UNKNOWN",origin:o.url||""}};try{if(a===gt.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),V(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=J("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),V(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),V(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),V(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=J("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),V(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,l,u,d,h;return!r||n!==gt.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((d=r?.redirect)==null?void 0:d.universal)!==""&&((h=r?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),V(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),V(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=m5(r,"topic")||"",i=decodeURIComponent(m5(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:gt.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),V(this,"registerLinkModeListeners",async()=>{var r;if(Og()||zs()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),V(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(s8).includes(i.method)}),V(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return kr(ot({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),V(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),V(this,"extractTxHashesFromResult",(r,n)=>{try{const i=s8[r];if(typeof n=="string")return[n];const s=n[i.key];if(Jn(s))return r==="solana_signAllTransactions"?s.map(o=>_R(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=J("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Yt.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Kp)?this.client.auth.authKeys.get(Kp):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===gt.link_mode?Gs:Yn});yc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:vi(n)})):jo(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Nn.expired,async e=>{const{topic:r,id:n}=w5(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,J("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,J("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(zo.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(zo.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Pt(e,!1)){const{message:r}=J("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=J("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Hs(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=J("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Pt(e,!1)){const{message:r}=J("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=J("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Hs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=J("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=J("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Pt(e,!1)){const{message:r}=J("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=J("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!jB(e)){const{message:r}=J("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=J("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Hs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=J("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class wq extends Wo{constructor(e,r){super(e,r,eq,Rw),this.core=e,this.logger=r}}class mq extends Wo{constructor(e,r){super(e,r,tq,Rw),this.core=e,this.logger=r}}class bq extends Wo{constructor(e,r){super(e,r,nq,Rw,n=>n.id),this.core=e,this.logger=r}}class yq extends Wo{constructor(e,r){super(e,r,aq,Vp,()=>Kp),this.core=e,this.logger=r}}class vq extends Wo{constructor(e,r){super(e,r,cq,Vp),this.core=e,this.logger=r}}class Eq extends Wo{constructor(e,r){super(e,r,lq,Vp,n=>n.id),this.core=e,this.logger=r}}var Cq=Object.defineProperty,xq=(t,e,r)=>e in t?Cq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lw=(t,e,r)=>xq(t,typeof e!="symbol"?e+"":e,r);class $q{constructor(e,r){this.core=e,this.logger=r,Lw(this,"authKeys"),Lw(this,"pairingTopics"),Lw(this,"requests"),this.authKeys=new yq(this.core,this.logger),this.pairingTopics=new vq(this.core,this.logger),this.requests=new Eq(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var _q=Object.defineProperty,Iq=(t,e,r)=>e in t?_q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oe=(t,e,r)=>Iq(t,typeof e!="symbol"?e+"":e,r);class Fw extends AL{constructor(e){super(e),Oe(this,"protocol",e8),Oe(this,"version",t8),Oe(this,"name",Dw.name),Oe(this,"metadata"),Oe(this,"core"),Oe(this,"logger"),Oe(this,"events",new nt.exports.EventEmitter),Oe(this,"engine"),Oe(this,"session"),Oe(this,"proposal"),Oe(this,"pendingRequest"),Oe(this,"auth"),Oe(this,"signConfig"),Oe(this,"on",(n,i)=>this.events.on(n,i)),Oe(this,"once",(n,i)=>this.events.once(n,i)),Oe(this,"off",(n,i)=>this.events.off(n,i)),Oe(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Oe(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Oe(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Oe(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Oe(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Dw.name,this.metadata=Fk(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ln(es({level:e?.logger||Dw.logger}));this.core=e?.core||new Qz(e),this.logger=We(r,this.name),this.session=new mq(this.core,this.logger),this.proposal=new wq(this.core,this.logger),this.pendingRequest=new bq(this.core,this.logger),this.engine=new gq(this),this.auth=new $q(this.core,this.logger)}static async init(e){const r=new Fw(e);return await r.initialize(),r}get context(){return it(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},z.toMiliseconds(z.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Mw={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof zt<"u"&&zt,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof zt<"u"&&zt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(y){return y&&DataView.prototype.isPrototypeOf(y)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(y){return y&&u.indexOf(Object.prototype.toString.call(y))>-1};function h(y){if(typeof y!="string"&&(y=String(y)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(y)||y==="")throw new TypeError('Invalid character in header field name: "'+y+'"');return y.toLowerCase()}function f(y){return typeof y!="string"&&(y=String(y)),y}function g(y){var v={next:function(){var A=y.shift();return{done:A===void 0,value:A}}};return c.iterable&&(v[Symbol.iterator]=function(){return v}),v}function w(y){this.map={},y instanceof w?y.forEach(function(v,A){this.append(A,v)},this):Array.isArray(y)?y.forEach(function(v){if(v.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+v.length);this.append(v[0],v[1])},this):y&&Object.getOwnPropertyNames(y).forEach(function(v){this.append(v,y[v])},this)}w.prototype.append=function(y,v){y=h(y),v=f(v);var A=this.map[y];this.map[y]=A?A+", "+v:v},w.prototype.delete=function(y){delete this.map[h(y)]},w.prototype.get=function(y){return y=h(y),this.has(y)?this.map[y]:null},w.prototype.has=function(y){return this.map.hasOwnProperty(h(y))},w.prototype.set=function(y,v){this.map[h(y)]=f(v)},w.prototype.forEach=function(y,v){for(var A in this.map)this.map.hasOwnProperty(A)&&y.call(v,this.map[A],A,this)},w.prototype.keys=function(){var y=[];return this.forEach(function(v,A){y.push(A)}),g(y)},w.prototype.values=function(){var y=[];return this.forEach(function(v){y.push(v)}),g(y)},w.prototype.entries=function(){var y=[];return this.forEach(function(v,A){y.push([A,v])}),g(y)},c.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function p(y){if(!y._noBody){if(y.bodyUsed)return Promise.reject(new TypeError("Already read"));y.bodyUsed=!0}}function b(y){return new Promise(function(v,A){y.onload=function(){v(y.result)},y.onerror=function(){A(y.error)}})}function m(y){var v=new FileReader,A=b(v);return v.readAsArrayBuffer(y),A}function E(y){var v=new FileReader,A=b(v),O=/charset=([A-Za-z0-9_-]+)/.exec(y.type),_=O?O[1]:"utf-8";return v.readAsText(y,_),A}function C(y){for(var v=new Uint8Array(y),A=new Array(v.length),O=0;O<v.length;O++)A[O]=String.fromCharCode(v[O]);return A.join("")}function P(y){if(y.slice)return y.slice(0);var v=new Uint8Array(y.byteLength);return v.set(new Uint8Array(y)),v.buffer}function S(){return this.bodyUsed=!1,this._initBody=function(y){this.bodyUsed=this.bodyUsed,this._bodyInit=y,y?typeof y=="string"?this._bodyText=y:c.blob&&Blob.prototype.isPrototypeOf(y)?this._bodyBlob=y:c.formData&&FormData.prototype.isPrototypeOf(y)?this._bodyFormData=y:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)?this._bodyText=y.toString():c.arrayBuffer&&c.blob&&l(y)?(this._bodyArrayBuffer=P(y.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(y)||d(y))?this._bodyArrayBuffer=P(y):this._bodyText=y=Object.prototype.toString.call(y):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof y=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var y=p(this);if(y)return y;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var y=p(this);return y||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(m);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var y=p(this);if(y)return y;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(C(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(D)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function N(y){var v=y.toUpperCase();return I.indexOf(v)>-1?v:y}function $(y,v){if(!(this instanceof $))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');v=v||{};var A=v.body;if(y instanceof $){if(y.bodyUsed)throw new TypeError("Already read");this.url=y.url,this.credentials=y.credentials,v.headers||(this.headers=new w(y.headers)),this.method=y.method,this.mode=y.mode,this.signal=y.signal,!A&&y._bodyInit!=null&&(A=y._bodyInit,y.bodyUsed=!0)}else this.url=String(y);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new w(v.headers)),this.method=N(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(v.cache==="no-store"||v.cache==="no-cache")){var O=/([?&])_=[^&]*/;if(O.test(this.url))this.url=this.url.replace(O,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function D(y){var v=new FormData;return y.trim().split("&").forEach(function(A){if(A){var O=A.split("="),_=O.shift().replace(/\+/g," "),k=O.join("=").replace(/\+/g," ");v.append(decodeURIComponent(_),decodeURIComponent(k))}}),v}function T(y){var v=new w,A=y.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(O){return O.indexOf(`
40
40
  `)===0?O.substr(1,O.length):O}).forEach(function(O){var _=O.split(":"),k=_.shift().trim();if(k){var L=_.join(":").trim();try{v.append(k,L)}catch(F){console.warn("Response "+F.message)}}}),v}S.call($.prototype);function R(y,v){if(!(this instanceof R))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(v||(v={}),this.type="default",this.status=v.status===void 0?200:v.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=v.statusText===void 0?"":""+v.statusText,this.headers=new w(v.headers),this.url=v.url||"",this._initBody(y)}S.call(R.prototype),R.prototype.clone=function(){return new R(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},R.error=function(){var y=new R(null,{status:200,statusText:""});return y.ok=!1,y.status=0,y.type="error",y};var M=[301,302,303,307,308];R.redirect=function(y,v){if(M.indexOf(v)===-1)throw new RangeError("Invalid status code");return new R(null,{status:v,headers:{location:y}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(v,A){this.message=v,this.name=A;var O=Error(v);this.stack=O.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function x(y,v){return new Promise(function(A,O){var _=new $(y,v);if(_.signal&&_.signal.aborted)return O(new o.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function L(){k.abort()}k.onload=function(){var q={statusText:k.statusText,headers:T(k.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(k.status<200||k.status>599)?q.status=200:q.status=k.status,q.url="responseURL"in k?k.responseURL:q.headers.get("X-Request-URL");var W="response"in k?k.response:k.responseText;setTimeout(function(){A(new R(W,q))},0)},k.onerror=function(){setTimeout(function(){O(new TypeError("Network request failed"))},0)},k.ontimeout=function(){setTimeout(function(){O(new TypeError("Network request timed out"))},0)},k.onabort=function(){setTimeout(function(){O(new o.DOMException("Aborted","AbortError"))},0)};function F(q){try{return q===""&&a.location.href?a.location.href:q}catch{return q}}if(k.open(_.method,F(_.url),!0),_.credentials==="include"?k.withCredentials=!0:_.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(c.blob?k.responseType="blob":c.arrayBuffer&&(k.responseType="arraybuffer")),v&&typeof v.headers=="object"&&!(v.headers instanceof w||a.Headers&&v.headers instanceof a.Headers)){var H=[];Object.getOwnPropertyNames(v.headers).forEach(function(q){H.push(h(q)),k.setRequestHeader(q,f(v.headers[q]))}),_.headers.forEach(function(q,W){H.indexOf(W)===-1&&k.setRequestHeader(W,q)})}else _.headers.forEach(function(q,W){k.setRequestHeader(W,q)});_.signal&&(_.signal.addEventListener("abort",L),k.onreadystatechange=function(){k.readyState===4&&_.signal.removeEventListener("abort",L)}),k.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return x.polyfill=!0,a.fetch||(a.fetch=x,a.Headers=w,a.Request=$,a.Response=R),o.Headers=w,o.Request=$,o.Response=R,o.fetch=x,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=r.fetch?r:n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Mw,Mw.exports);var a8=V_(Mw.exports),Sq=Object.defineProperty,Aq=Object.defineProperties,Pq=Object.getOwnPropertyDescriptors,c8=Object.getOwnPropertySymbols,Oq=Object.prototype.hasOwnProperty,Nq=Object.prototype.propertyIsEnumerable,l8=(t,e,r)=>e in t?Sq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,u8=(t,e)=>{for(var r in e||(e={}))Oq.call(e,r)&&l8(t,r,e[r]);if(c8)for(var r of c8(e))Nq.call(e,r)&&l8(t,r,e[r]);return t},d8=(t,e)=>Aq(t,Pq(e));const Tq={Accept:"application/json","Content-Type":"application/json"},kq="POST",h8={headers:Tq,method:kq},p8=10;class Ct{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new nt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!a6(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=wi(e),n=await(await a8(this.url,d8(u8({},h8),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!a6(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=wi({id:1,jsonrpc:"2.0",method:"test",params:[]});await a8(e,d8(u8({},h8),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Wi(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=bc(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return t6(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>p8&&this.events.setMaxListeners(p8)}}var Rq=Object.defineProperty,f8=Object.getOwnPropertySymbols,Dq=Object.prototype.hasOwnProperty,Bq=Object.prototype.propertyIsEnumerable,g8=(t,e,r)=>e in t?Rq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,w8=(t,e)=>{for(var r in e||(e={}))Dq.call(e,r)&&g8(t,r,e[r]);if(f8)for(var r of f8(e))Bq.call(e,r)&&g8(t,r,e[r]);return t};const m8="error",Uq="wss://relay.walletconnect.org",Lq="wc",Fq="universal_provider",Gp=`${Lq}@2:${Fq}:`,b8="https://rpc.walletconnect.org/v1/",Cc="generic",Mq=`${b8}bundler`,Tn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function jq(){}function jw(t){return t==null||typeof t!="object"&&typeof t!="function"}function zw(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function zq(t){if(jw(t))return t;if(Array.isArray(t)||zw(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const n=new r(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const n=new r(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function y8(t){return typeof t=="object"&&t!==null}function v8(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function E8(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const qq="[object RegExp]",C8="[object String]",x8="[object Number]",$8="[object Boolean]",_8="[object Arguments]",Hq="[object Symbol]",Wq="[object Date]",Vq="[object Map]",Kq="[object Set]",Gq="[object Array]",Zq="[object ArrayBuffer]",Yq="[object Object]",Jq="[object DataView]",Xq="[object Uint8Array]",Qq="[object Uint8ClampedArray]",eH="[object Uint16Array]",tH="[object Uint32Array]",rH="[object Int8Array]",nH="[object Int16Array]",iH="[object Int32Array]",sH="[object Float32Array]",oH="[object Float64Array]";function aH(t,e){return xc(t,void 0,t,new Map,e)}function xc(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(jw(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=xc(t[a],a,r,n,i);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,xc(c,a,r,n,i));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(xc(a,void 0,r,n,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(zw(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=xc(t[a],a,r,n,i);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),Vo(o,t,r,n,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),Vo(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),Vo(o,t,r,n,i),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Vo(o,t,r,n,i),o}if(typeof t=="object"&&cH(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),Vo(o,t,r,n,i),o}return t}function Vo(t,e,r=t,n,i){const s=[...Object.keys(e),...v8(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=xc(e[a],a,r,n,i))}}function cH(t){switch(E8(t)){case _8:case Gq:case Zq:case Jq:case $8:case Wq:case sH:case oH:case rH:case nH:case iH:case Vq:case x8:case Yq:case qq:case Kq:case C8:case Hq:case Xq:case Qq:case eH:case tH:return!0;default:return!1}}function lH(t,e){return aH(t,(r,n,i,s)=>{const o=e?.(r,n,i,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case x8:case C8:case $8:{const a=new t.constructor(t?.valueOf());return Vo(a,t),a}case _8:{const a={};return Vo(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function I8(t){return lH(t)}function S8(t){return t!==null&&typeof t=="object"&&E8(t)==="[object Arguments]"}function uH(t){return zw(t)}function dH(t){var e;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!((e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&e.writable)?!1:t.toString()===`[object ${n}]`}let r=t;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(t)===r}function hH(t,...e){const r=e.slice(0,-1),n=e[e.length-1];let i=t;for(let s=0;s<r.length;s++){const o=r[s];i=qw(i,o,n,new Map)}return i}function qw(t,e,r,n){var i;if(jw(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return zq(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let o=0;o<e.length;o++)e[o]=(i=e[o])!=null?i:void 0}const s=[...Object.keys(e),...v8(e)];for(let o=0;o<s.length;o++){const a=s[o];let c=e[a],l=t[a];if(S8(c)&&(c=w8({},c)),S8(l)&&(l=w8({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=I8(c)),Array.isArray(c))if(typeof l=="object"&&l!=null){const d=[],h=Reflect.ownKeys(l);for(let f=0;f<h.length;f++){const g=h[f];d[g]=l[g]}l=d}else l=[];const u=r(l,c,a,t,e,n);u!=null?t[a]=u:Array.isArray(c)||y8(l)&&y8(c)?t[a]=qw(l,c,r,n):l==null&&dH(c)?t[a]=qw({},c,r,n):l==null&&uH(c)?t[a]=I8(c):(l===void 0||c!==void 0)&&(t[a]=c)}return t}function pH(t,...e){return hH(t,...e,jq)}var fH=Object.defineProperty,gH=Object.defineProperties,wH=Object.getOwnPropertyDescriptors,A8=Object.getOwnPropertySymbols,mH=Object.prototype.hasOwnProperty,bH=Object.prototype.propertyIsEnumerable,P8=(t,e,r)=>e in t?fH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zp=(t,e)=>{for(var r in e||(e={}))mH.call(e,r)&&P8(t,r,e[r]);if(A8)for(var r of A8(e))bH.call(e,r)&&P8(t,r,e[r]);return t},yH=(t,e)=>gH(t,wH(e));function pn(t,e,r){var n;const i=rc(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${b8}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Ko(t){return t.includes(":")?t.split(":")[1]:t}function O8(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function vH(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const s=e.namespaces[i].accounts;n.push(...s)}),n}function Hw(t={},e={}){const r=N8(t),n=N8(e);return pH(r,n)}function N8(t){var e,r,n,i;const s={};if(!Su(t))return s;for(const[o,a]of Object.entries(t)){const c=iw(o)?[o]:a.chains,l=a.methods||[],u=a.events||[],d=a.rpcMap||{},h=Iu(o);s[h]=yH(Zp(Zp({},s[h]),a),{chains:bp(c,(e=s[h])==null?void 0:e.chains),methods:bp(l,(r=s[h])==null?void 0:r.methods),events:bp(u,(n=s[h])==null?void 0:n.events),rpcMap:Zp(Zp({},d),(i=s[h])==null?void 0:i.rpcMap)})}return s}function T8(t){return t.includes(":")?t.split(":")[2]:t}function k8(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=iw(r)?[r]:n.chains?n.chains:O8(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function Ww(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const R8={},Le=t=>R8[t],Vw=(t,e)=>{R8[t]=e};var EH=Object.defineProperty,CH=(t,e,r)=>e in t?EH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$c=(t,e,r)=>CH(t,typeof e!="symbol"?e+"":e,r);class xH{constructor(e){$c(this,"name","polkadot"),$c(this,"client"),$c(this,"httpProviders"),$c(this,"events"),$c(this,"namespace"),$c(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Ko(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var $H=Object.defineProperty,_H=Object.defineProperties,IH=Object.getOwnPropertyDescriptors,D8=Object.getOwnPropertySymbols,SH=Object.prototype.hasOwnProperty,AH=Object.prototype.propertyIsEnumerable,Kw=(t,e,r)=>e in t?$H(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,B8=(t,e)=>{for(var r in e||(e={}))SH.call(e,r)&&Kw(t,r,e[r]);if(D8)for(var r of D8(e))AH.call(e,r)&&Kw(t,r,e[r]);return t},U8=(t,e)=>_H(t,IH(e)),_c=(t,e,r)=>Kw(t,typeof e!="symbol"?e+"":e,r);class PH{constructor(e){_c(this,"name","eip155"),_c(this,"client"),_c(this,"chainId"),_c(this,"namespace"),_c(this,"httpProviders"),_c(this,"events"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||pn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=parseInt(Ko(r));e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,n;let i=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const s=parseInt(i,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,n,i;const s=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0];if(!s)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((i=o?.sessionProperties)==null?void 0:i.capabilities)||{};if(a!=null&&a[s])return a?.[s];const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:U8(B8({},o.sessionProperties||{}),{capabilities:U8(B8({},a||{}),{[s]:c})})})}catch(l){console.warn("Failed to update session with capabilities",l)}return c}async getCallStatus(e){var r,n;const i=this.client.session.get(e.topic),s=(r=i.sessionProperties)==null?void 0:r.bundler_name;if(s){const a=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(n=i.sessionProperties)==null?void 0:n.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var n;const i=new URL(e),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Nr("eth_getUserOperationReceipt",[(n=r.request.params)==null?void 0:n[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${Mq}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var OH=Object.defineProperty,NH=(t,e,r)=>e in t?OH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ic=(t,e,r)=>NH(t,typeof e!="symbol"?e+"":e,r);class TH{constructor(e){Ic(this,"name","solana"),Ic(this,"client"),Ic(this,"httpProviders"),Ic(this,"events"),Ic(this,"namespace"),Ic(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Ko(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var kH=Object.defineProperty,RH=(t,e,r)=>e in t?kH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sc=(t,e,r)=>RH(t,typeof e!="symbol"?e+"":e,r);class DH{constructor(e){Sc(this,"name","cosmos"),Sc(this,"client"),Sc(this,"httpProviders"),Sc(this,"events"),Sc(this,"namespace"),Sc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Ko(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var BH=Object.defineProperty,UH=(t,e,r)=>e in t?BH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ac=(t,e,r)=>UH(t,typeof e!="symbol"?e+"":e,r);class LH{constructor(e){Ac(this,"name","algorand"),Ac(this,"client"),Ac(this,"httpProviders"),Ac(this,"events"),Ac(this,"namespace"),Ac(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||pn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new bt(new Ct(n,Le("disableProviderPing")))}}var FH=Object.defineProperty,MH=(t,e,r)=>e in t?FH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pc=(t,e,r)=>MH(t,typeof e!="symbol"?e+"":e,r);class jH{constructor(e){Pc(this,"name","cip34"),Pc(this,"client"),Pc(this,"httpProviders"),Pc(this,"events"),Pc(this,"namespace"),Pc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r),i=Ko(r);e[i]=this.createHttpProvider(i,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var zH=Object.defineProperty,qH=(t,e,r)=>e in t?zH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oc=(t,e,r)=>qH(t,typeof e!="symbol"?e+"":e,r);class HH{constructor(e){Oc(this,"name","elrond"),Oc(this,"client"),Oc(this,"httpProviders"),Oc(this,"events"),Oc(this,"namespace"),Oc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Ko(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var WH=Object.defineProperty,VH=(t,e,r)=>e in t?WH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nc=(t,e,r)=>VH(t,typeof e!="symbol"?e+"":e,r);class KH{constructor(e){Nc(this,"name","multiversx"),Nc(this,"client"),Nc(this,"httpProviders"),Nc(this,"events"),Nc(this,"namespace"),Nc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Ko(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var GH=Object.defineProperty,ZH=(t,e,r)=>e in t?GH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tc=(t,e,r)=>ZH(t,typeof e!="symbol"?e+"":e,r);class YH{constructor(e){Tc(this,"name","near"),Tc(this,"client"),Tc(this,"httpProviders"),Tc(this,"events"),Tc(this,"namespace"),Tc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||pn(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace);return typeof n>"u"?void 0:new bt(new Ct(n,Le("disableProviderPing")))}}var JH=Object.defineProperty,XH=(t,e,r)=>e in t?JH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kc=(t,e,r)=>XH(t,typeof e!="symbol"?e+"":e,r);class QH{constructor(e){kc(this,"name","tezos"),kc(this,"client"),kc(this,"httpProviders"),kc(this,"events"),kc(this,"namespace"),kc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||pn(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace);return typeof n>"u"?void 0:new bt(new Ct(n))}}var eW=Object.defineProperty,tW=(t,e,r)=>e in t?eW(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rc=(t,e,r)=>tW(t,typeof e!="symbol"?e+"":e,r);class rW{constructor(e){Rc(this,"name",Cc),Rc(this,"client"),Rc(this,"httpProviders"),Rc(this,"events"),Rc(this,"namespace"),Rc(this,"chainId"),this.namespace=e.namespace,this.events=Le("events"),this.client=Le("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Tn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const n={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(i=>{const s=rc(i);n[`${s.namespace}:${s.reference}`]=this.createHttpProvider(i)}),n}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||pn(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new bt(new Ct(n,Le("disableProviderPing")))}}var nW=Object.defineProperty,iW=Object.defineProperties,sW=Object.getOwnPropertyDescriptors,L8=Object.getOwnPropertySymbols,oW=Object.prototype.hasOwnProperty,aW=Object.prototype.propertyIsEnumerable,Gw=(t,e,r)=>e in t?nW(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yp=(t,e)=>{for(var r in e||(e={}))oW.call(e,r)&&Gw(t,r,e[r]);if(L8)for(var r of L8(e))aW.call(e,r)&&Gw(t,r,e[r]);return t},Zw=(t,e)=>iW(t,sW(e)),kn=(t,e,r)=>Gw(t,typeof e!="symbol"?e+"":e,r);class Yw{constructor(e){kn(this,"client"),kn(this,"namespaces"),kn(this,"optionalNamespaces"),kn(this,"sessionProperties"),kn(this,"scopedProperties"),kn(this,"events",new nt.exports),kn(this,"rpcProviders",{}),kn(this,"session"),kn(this,"providerOpts"),kn(this,"logger"),kn(this,"uri"),kn(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ln(es({level:e?.logger||m8})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new Yw(e);return await r.initialize(),r}async request(e,r,n){const[i,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Yp({},e),chainId:`${i}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(e,r,n,i){const s=new Date().getTime();this.request(e,n,i).then(o=>r(null,Zs(s,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Ze("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:i}=await this.client.authenticate(e,r);n&&(this.uri=n,this.events.emit("display_uri",n));const s=await i();if(this.session=s.session,this.session){const o=k8(this.session.namespaces);this.namespaces=Hw(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const i=await n();this.session=i;const s=k8(i.namespaces);return this.namespaces=Hw(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[n,i]=this.validateChain(e),s=this.getProvider(n);s.name===Cc?s.setDefaultChain(`${n}:${i}`,r):s.setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(Jn(r)){for(const n of r)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: ${r.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,r;if(this.client=this.providerOpts.client||await Fw.init({core:this.providerOpts.core,logger:this.providerOpts.logger||m8,relayUrl:this.providerOpts.relayUrl||Uq,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(n){throw this.logger.error("Failed to get session",n),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Iu(r)))];Vw("client",this.client),Vw("events",this.events),Vw("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=vH(r,this.session),i=O8(n),s=Hw(this.namespaces,this.optionalNamespaces),o=Zw(Yp({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new PH({namespace:o});break;case"algorand":this.rpcProviders[r]=new LH({namespace:o});break;case"solana":this.rpcProviders[r]=new TH({namespace:o});break;case"cosmos":this.rpcProviders[r]=new DH({namespace:o});break;case"polkadot":this.rpcProviders[r]=new xH({namespace:o});break;case"cip34":this.rpcProviders[r]=new jH({namespace:o});break;case"elrond":this.rpcProviders[r]=new HH({namespace:o});break;case"multiversx":this.rpcProviders[r]=new KH({namespace:o});break;case"near":this.rpcProviders[r]=new YH({namespace:o});break;case"tezos":this.rpcProviders[r]=new QH({namespace:o});break;default:this.rpcProviders[Cc]?this.rpcProviders[Cc].updateNamespace(o):this.rpcProviders[Cc]=new rW({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:n}=e;n===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:n,topic:i}=e;if(i!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=n;if(s.name==="accountsChanged"){const o=s.data;o&&Jn(o)&&this.events.emit("accountsChanged",o.map(T8))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Iu(o),l=Ww(o)!==Ww(a)?`${c}:${Ww(a)}`:o;this.onChainChanged(l)}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n,i;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:s}=r,o=(i=this.client)==null?void 0:i.session.get(e);this.session=Zw(Yp({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Zw(Yp({},Ze("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Tn.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Cc]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i,scopedProperties:s}=e;r&&Object.keys(r).length&&(this.namespaces=r),n&&Object.keys(n).length&&(this.optionalNamespaces=n),this.sessionProperties=i,this.scopedProperties=s}validateChain(e){const[r,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(o=>Iu(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Iu(Object.keys(this.namespaces)[0]),s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[n,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(n,i),this.events.emit("chainChanged",i);const s=this.getProvider(n).getDefaultChain();r||this.getProvider(n).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:n,previousChainId:s,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:n}){var i,s;try{if(r===n)return;const o=(s=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${n}:`)).map(T8);if(!Jn(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${r}`,i={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var n;const i=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${Gp}/${e}${i}`,r)}async getFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${Gp}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Gp}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const n of r)n.startsWith(Gp)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}}const cW=Yw,lW="wc",uW="ethereum_provider",dW=`${lW}@2:${uW}:`,hW="https://rpc.walletconnect.org/v1/",Jp=["eth_sendTransaction","personal_sign"],F8=["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"],Xp=["chainChanged","accountsChanged"],M8=["chainChanged","accountsChanged","message","disconnect","connect"];var pW=Object.defineProperty,fW=Object.defineProperties,gW=Object.getOwnPropertyDescriptors,j8=Object.getOwnPropertySymbols,wW=Object.prototype.hasOwnProperty,mW=Object.prototype.propertyIsEnumerable,Jw=(t,e,r)=>e in t?pW(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Go=(t,e)=>{for(var r in e||(e={}))wW.call(e,r)&&Jw(t,r,e[r]);if(j8)for(var r of j8(e))mW.call(e,r)&&Jw(t,r,e[r]);return t},qu=(t,e)=>fW(t,gW(e)),fn=(t,e,r)=>Jw(t,typeof e!="symbol"?e+"":e,r);function Qp(t){return Number(t[0].split(":")[1])}function ef(t){return`0x${t.toString(16)}`}function bW(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!Jn(e))throw new Error("Invalid chains");const c={chains:e,methods:n||Jp,events:s||Xp,rpcMap:Go({},e.length?{[Qp(e)]:a[Qp(e)]}:{})},l=s?.filter(f=>!Xp.includes(f)),u=n?.filter(f=>!Jp.includes(f));if(!r&&!o&&!i&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const d=l?.length&&u?.length||!r,h={chains:[...new Set(d?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:F8))],events:[...new Set(c.events.concat(o!=null&&o.length?o:M8))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?h:void 0}}class tf{constructor(){fn(this,"events",new nt.exports.EventEmitter),fn(this,"namespace","eip155"),fn(this,"accounts",[]),fn(this,"signer"),fn(this,"chainId",1),fn(this,"modal"),fn(this,"rpc"),fn(this,"STORAGE_KEY",dW),fn(this,"on",(e,r)=>(this.events.on(e,r),this)),fn(this,"once",(e,r)=>(this.events.once(e,r),this)),fn(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),fn(this,"off",(e,r)=>(this.events.off(e,r),this)),fn(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new tf;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:n,optional:i}=bW(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const d=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(qu(Go({namespaces:Go({},n&&{[this.namespace]:n})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic,scopedProperties:d})).then(h=>{a(h)}).catch(h=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(h.message))})});if(!s)return;const o=a5(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ef(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(qu(Go({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=i.session;if(s){const o=a5(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ef(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(n=this.modal)==null||n.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?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 r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ef(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",qu(Go({},Ze("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ef(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;const i=(r=e?.chains)!=null?r:[],s=(n=e?.optionalChains)!=null?n:[],o=i.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=i.length?e?.methods||Jp:[],c=i.length?e?.events||Xp:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],d=e?.rpcMap||this.buildRpcMap(o,e.projectId),h=e?.qrModalOptions||void 0;return{chains:i?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:d,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:h,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Qp(this.rpc.chains):Qp(this.rpc.optionalChains),this.signer=await cW.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{createAppKit:n}=await Promise.resolve().then(function(){return Qce}),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return ule}),s=i(qu(Go({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!s.networks.length)throw new Error("No networks found for WalletConnect\xB7");r=n(qu(Go({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch{throw new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&Jn(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&Jn(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${hW}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const yW=tf;var z8={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(zt,function(){var r=1e3,n=6e4,i=36e5,s="millisecond",o="second",a="minute",c="hour",l="day",u="week",d="month",h="quarter",f="year",g="date",w="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,b=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,m={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(x){var y=["th","st","nd","rd"],v=x%100;return"["+x+(y[(v-20)%10]||y[v]||y[0])+"]"}},E=function(x,y,v){var A=String(x);return!A||A.length>=y?x:""+Array(y+1-A.length).join(v)+x},C={s:E,z:function(x){var y=-x.utcOffset(),v=Math.abs(y),A=Math.floor(v/60),O=v%60;return(y<=0?"+":"-")+E(A,2,"0")+":"+E(O,2,"0")},m:function x(y,v){if(y.date()<v.date())return-x(v,y);var A=12*(v.year()-y.year())+(v.month()-y.month()),O=y.clone().add(A,d),_=v-O<0,k=y.clone().add(A+(_?-1:1),d);return+(-(A+(v-O)/(_?O-k:k-O))||0)},a:function(x){return x<0?Math.ceil(x)||0:Math.floor(x)},p:function(x){return{M:d,y:f,w:u,d:l,D:g,h:c,m:a,s:o,ms:s,Q:h}[x]||String(x||"").toLowerCase().replace(/s$/,"")},u:function(x){return x===void 0}},P="en",S={};S[P]=m;var I="$isDayjsObject",N=function(x){return x instanceof R||!(!x||!x[I])},$=function x(y,v,A){var O;if(!y)return P;if(typeof y=="string"){var _=y.toLowerCase();S[_]&&(O=_),v&&(S[_]=v,O=_);var k=y.split("-");if(!O&&k.length>1)return x(k[0])}else{var L=y.name;S[L]=y,O=L}return!A&&O&&(P=O),O||!A&&P},D=function(x,y){if(N(x))return x.clone();var v=typeof y=="object"?y:{};return v.date=x,v.args=arguments,new R(v)},T=C;T.l=$,T.i=N,T.w=function(x,y){return D(x,{locale:y.$L,utc:y.$u,x:y.$x,$offset:y.$offset})};var R=function(){function x(v){this.$L=$(v.locale,null,!0),this.parse(v),this.$x=this.$x||v.x||{},this[I]=!0}var y=x.prototype;return y.parse=function(v){this.$d=function(A){var O=A.date,_=A.utc;if(O===null)return new Date(NaN);if(T.u(O))return new Date;if(O instanceof Date)return new Date(O);if(typeof O=="string"&&!/Z$/i.test(O)){var k=O.match(p);if(k){var L=k[2]-1||0,F=(k[7]||"0").substring(0,3);return _?new Date(Date.UTC(k[1],L,k[3]||1,k[4]||0,k[5]||0,k[6]||0,F)):new Date(k[1],L,k[3]||1,k[4]||0,k[5]||0,k[6]||0,F)}}return new Date(O)}(v),this.init()},y.init=function(){var v=this.$d;this.$y=v.getFullYear(),this.$M=v.getMonth(),this.$D=v.getDate(),this.$W=v.getDay(),this.$H=v.getHours(),this.$m=v.getMinutes(),this.$s=v.getSeconds(),this.$ms=v.getMilliseconds()},y.$utils=function(){return T},y.isValid=function(){return this.$d.toString()!==w},y.isSame=function(v,A){var O=D(v);return this.startOf(A)<=O&&O<=this.endOf(A)},y.isAfter=function(v,A){return D(v)<this.startOf(A)},y.isBefore=function(v,A){return this.endOf(A)<D(v)},y.$g=function(v,A,O){return T.u(v)?this[A]:this.set(O,v)},y.unix=function(){return Math.floor(this.valueOf()/1e3)},y.valueOf=function(){return this.$d.getTime()},y.startOf=function(v,A){var O=this,_=!!T.u(A)||A,k=T.p(v),L=function(te,Ee){var Ce=T.w(O.$u?Date.UTC(O.$y,Ee,te):new Date(O.$y,Ee,te),O);return _?Ce:Ce.endOf(l)},F=function(te,Ee){return T.w(O.toDate()[te].apply(O.toDate("s"),(_?[0,0,0,0]:[23,59,59,999]).slice(Ee)),O)},H=this.$W,q=this.$M,W=this.$D,Y="set"+(this.$u?"UTC":"");switch(k){case f:return _?L(1,0):L(31,11);case d:return _?L(1,q):L(0,q+1);case u:var ae=this.$locale().weekStart||0,re=(H<ae?H+7:H)-ae;return L(_?W-re:W+(6-re),q);case l:case g:return F(Y+"Hours",0);case c:return F(Y+"Minutes",1);case a:return F(Y+"Seconds",2);case o:return F(Y+"Milliseconds",3);default:return this.clone()}},y.endOf=function(v){return this.startOf(v,!1)},y.$set=function(v,A){var O,_=T.p(v),k="set"+(this.$u?"UTC":""),L=(O={},O[l]=k+"Date",O[g]=k+"Date",O[d]=k+"Month",O[f]=k+"FullYear",O[c]=k+"Hours",O[a]=k+"Minutes",O[o]=k+"Seconds",O[s]=k+"Milliseconds",O)[_],F=_===l?this.$D+(A-this.$W):A;if(_===d||_===f){var H=this.clone().set(g,1);H.$d[L](F),H.init(),this.$d=H.set(g,Math.min(this.$D,H.daysInMonth())).$d}else L&&this.$d[L](F);return this.init(),this},y.set=function(v,A){return this.clone().$set(v,A)},y.get=function(v){return this[T.p(v)]()},y.add=function(v,A){var O,_=this;v=Number(v);var k=T.p(A),L=function(q){var W=D(_);return T.w(W.date(W.date()+Math.round(q*v)),_)};if(k===d)return this.set(d,this.$M+v);if(k===f)return this.set(f,this.$y+v);if(k===l)return L(1);if(k===u)return L(7);var F=(O={},O[a]=n,O[c]=i,O[o]=r,O)[k]||1,H=this.$d.getTime()+v*F;return T.w(H,this)},y.subtract=function(v,A){return this.add(-1*v,A)},y.format=function(v){var A=this,O=this.$locale();if(!this.isValid())return O.invalidDate||w;var _=v||"YYYY-MM-DDTHH:mm:ssZ",k=T.z(this),L=this.$H,F=this.$m,H=this.$M,q=O.weekdays,W=O.months,Y=O.meridiem,ae=function(Ee,Ce,xe,_e){return Ee&&(Ee[Ce]||Ee(A,_))||xe[Ce].slice(0,_e)},re=function(Ee){return T.s(L%12||12,Ee,"0")},te=Y||function(Ee,Ce,xe){var _e=Ee<12?"AM":"PM";return xe?_e.toLowerCase():_e};return _.replace(b,function(Ee,Ce){return Ce||function(xe){switch(xe){case"YY":return String(A.$y).slice(-2);case"YYYY":return T.s(A.$y,4,"0");case"M":return H+1;case"MM":return T.s(H+1,2,"0");case"MMM":return ae(O.monthsShort,H,W,3);case"MMMM":return ae(W,H);case"D":return A.$D;case"DD":return T.s(A.$D,2,"0");case"d":return String(A.$W);case"dd":return ae(O.weekdaysMin,A.$W,q,2);case"ddd":return ae(O.weekdaysShort,A.$W,q,3);case"dddd":return q[A.$W];case"H":return String(L);case"HH":return T.s(L,2,"0");case"h":return re(1);case"hh":return re(2);case"a":return te(L,F,!0);case"A":return te(L,F,!1);case"m":return String(F);case"mm":return T.s(F,2,"0");case"s":return String(A.$s);case"ss":return T.s(A.$s,2,"0");case"SSS":return T.s(A.$ms,3,"0");case"Z":return k}return null}(Ee)||k.replace(":","")})},y.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},y.diff=function(v,A,O){var _,k=this,L=T.p(A),F=D(v),H=(F.utcOffset()-this.utcOffset())*n,q=this-F,W=function(){return T.m(k,F)};switch(L){case f:_=W()/12;break;case d:_=W();break;case h:_=W()/3;break;case u:_=(q-H)/6048e5;break;case l:_=(q-H)/864e5;break;case c:_=q/i;break;case a:_=q/n;break;case o:_=q/r;break;default:_=q}return O?_:T.a(_)},y.daysInMonth=function(){return this.endOf(d).$D},y.$locale=function(){return S[this.$L]},y.locale=function(v,A){if(!v)return this.$L;var O=this.clone(),_=$(v,A,!0);return _&&(O.$L=_),O},y.clone=function(){return T.w(this.$d,this)},y.toDate=function(){return new Date(this.valueOf())},y.toJSON=function(){return this.isValid()?this.toISOString():null},y.toISOString=function(){return this.$d.toISOString()},y.toString=function(){return this.$d.toUTCString()},x}(),M=R.prototype;return D.prototype=M,[["$ms",s],["$s",o],["$m",a],["$H",c],["$W",l],["$M",d],["$y",f],["$D",g]].forEach(function(x){M[x[1]]=function(y){return this.$g(y,x[0],x[1])}}),D.extend=function(x,y){return x.$i||(x(y,R,D),x.$i=!0),D},D.locale=$,D.isDayjs=N,D.unix=function(x){return D(1e3*x)},D.en=S[P],D.Ls=S,D.p={},D})})(z8);var Xw=z8.exports,q8={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(zt,function(){return{name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(r){var n=["th","st","nd","rd"],i=r%100;return"["+r+(n[(i-20)%10]||n[i]||n[0])+"]"}}})})(q8);var vW=q8.exports,H8={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(zt,function(){return function(r,n,i){r=r||{};var s=n.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(l,u,d,h){return s.fromToBase(l,u,d,h)}i.en.relativeTime=o,s.fromToBase=function(l,u,d,h,f){for(var g,w,p,b=d.$locale().relativeTime||o,m=r.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],E=m.length,C=0;C<E;C+=1){var P=m[C];P.d&&(g=h?i(l).diff(d,P.d,!0):d.diff(l,P.d,!0));var S=(r.rounding||Math.round)(Math.abs(g));if(p=g>0,S<=P.r||!P.r){S<=1&&C>0&&(P=m[C-1]);var I=b[P.l];f&&(S=f(""+S)),w=typeof I=="string"?I.replace("%d",S):I(S,u,P.l,p);break}}if(u)return w;var N=p?b.future:b.past;return typeof N=="function"?N(w):N.replace("%s",w)},s.to=function(l,u){return a(l,u,this,!0)},s.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?i.utc():i()};s.toNow=function(l){return this.to(c(this),l)},s.fromNow=function(l){return this.from(c(this),l)}}})})(H8);var EW=H8.exports,W8={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(zt,function(){return function(r,n,i){i.updateLocale=function(s,o){var a=i.Ls[s];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(W8);var CW=W8.exports;Xw.extend(EW),Xw.extend(CW);const xW={...vW,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}};Xw.locale("en-web3-modal",xW);const V8={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(r=>r.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]}};var $W=20,_W=1,Zo=1e6,K8=1e6,IW=-7,SW=21,AW=!1,Hu="[big.js] ",Yo=Hu+"Invalid ",rf=Yo+"decimal places",PW=Yo+"rounding mode",G8=Hu+"Division by zero",Ye={},Ii=void 0,OW=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Z8(){function t(e){var r=this;if(!(r instanceof t))return e===Ii?Z8():new t(e);if(e instanceof t)r.s=e.s,r.e=e.e,r.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(Yo+"value");e=e===0&&1/e<0?"-0":String(e)}NW(r,e)}r.constructor=t}return t.prototype=Ye,t.DP=$W,t.RM=_W,t.NE=IW,t.PE=SW,t.strict=AW,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function NW(t,e){var r,n,i;if(!OW.test(e))throw Error(Yo+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),i=e.length,n=0;n<i&&e.charAt(n)=="0";)++n;if(n==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=r-n-1,t.c=[],r=0;n<=i;)t.c[r++]=+e.charAt(n++)}return t}function Jo(t,e,r,n){var i=t.c;if(r===Ii&&(r=t.constructor.RM),r!==0&&r!==1&&r!==2&&r!==3)throw Error(PW);if(e<1)n=r===3&&(n||!!i[0])||e===0&&(r===1&&i[0]>=5||r===2&&(i[0]>5||i[0]===5&&(n||i[1]!==Ii))),i.length=1,n?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(n=r===1&&i[e]>=5||r===2&&(i[e]>5||i[e]===5&&(n||i[e+1]!==Ii||i[e-1]&1))||r===3&&(n||!!i[0]),i.length=e,n){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function Xo(t,e,r){var n=t.e,i=t.c.join(""),s=i.length;if(e)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)i="0"+i;i="0."+i}else if(n>0)if(++n>s)for(n-=s;n--;)i+="0";else n<s&&(i=i.slice(0,n)+"."+i.slice(n));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&r?"-"+i:i}Ye.abs=function(){var t=new this.constructor(this);return t.s=1,t},Ye.cmp=function(t){var e,r=this,n=r.c,i=(t=new r.constructor(t)).c,s=r.s,o=t.s,a=r.e,c=t.e;if(!n[0]||!i[0])return n[0]?s:i[0]?-o:0;if(s!=o)return s;if(e=s<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=i.length)?a:c,s=-1;++s<o;)if(n[s]!=i[s])return n[s]>i[s]^e?1:-1;return a==c?0:a>c^e?1:-1},Ye.div=function(t){var e=this,r=e.constructor,n=e.c,i=(t=new r(t)).c,s=e.s==t.s?1:-1,o=r.DP;if(o!==~~o||o<0||o>Zo)throw Error(rf);if(!i[0])throw Error(G8);if(!n[0])return t.s=s,t.c=[t.e=0],t;var a,c,l,u,d,h=i.slice(),f=a=i.length,g=n.length,w=n.slice(0,a),p=w.length,b=t,m=b.c=[],E=0,C=o+(b.e=e.e-t.e)+1;for(b.s=s,s=C<0?0:C,h.unshift(0);p++<a;)w.push(0);do{for(l=0;l<10;l++){if(a!=(p=w.length))u=a>p?1:-1;else for(d=-1,u=0;++d<a;)if(i[d]!=w[d]){u=i[d]>w[d]?1:-1;break}if(u<0){for(c=p==a?i:h;p;){if(w[--p]<c[p]){for(d=p;d&&!w[--d];)w[d]=9;--w[d],w[p]+=10}w[p]-=c[p]}for(;!w[0];)w.shift()}else break}m[E++]=u?l:++l,w[0]&&u?w[p]=n[f]||0:w=[n[f]]}while((f++<g||w[0]!==Ii)&&s--);return!m[0]&&E!=1&&(m.shift(),b.e--,C--),E>C&&Jo(b,C,r.RM,w[0]!==Ii),b},Ye.eq=function(t){return this.cmp(t)===0},Ye.gt=function(t){return this.cmp(t)>0},Ye.gte=function(t){return this.cmp(t)>-1},Ye.lt=function(t){return this.cmp(t)<0},Ye.lte=function(t){return this.cmp(t)<1},Ye.minus=Ye.sub=function(t){var e,r,n,i,s=this,o=s.constructor,a=s.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,s.plus(t);var l=s.c.slice(),u=s.e,d=t.c,h=t.e;if(!l[0]||!d[0])return d[0]?t.s=-c:l[0]?t=new o(s):t.s=1,t;if(a=u-h){for((i=a<0)?(a=-a,n=l):(h=u,n=d),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(r=((i=l.length<d.length)?l:d).length,a=c=0;c<r;c++)if(l[c]!=d[c]){i=l[c]<d[c];break}if(i&&(n=l,l=d,d=n,t.s=-t.s),(c=(r=d.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;r>a;){if(l[--r]<d[r]){for(e=r;e&&!l[--e];)l[e]=9;--l[e],l[r]+=10}l[r]-=d[r]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t},Ye.mod=function(t){var e,r=this,n=r.constructor,i=r.s,s=(t=new n(t)).s;if(!t.c[0])throw Error(G8);return r.s=t.s=1,e=t.cmp(r)==1,r.s=i,t.s=s,e?new n(r):(i=n.DP,s=n.RM,n.DP=n.RM=0,r=r.div(t),n.DP=i,n.RM=s,this.minus(r.times(t)))},Ye.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t},Ye.plus=Ye.add=function(t){var e,r,n,i=this,s=i.constructor;if(t=new s(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new s(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,r=0;e;a[e]%=10)r=(a[--e]=a[e]+l[e]+r)/10|0;for(r&&(a.unshift(r),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t},Ye.pow=function(t){var e=this,r=new e.constructor("1"),n=r,i=t<0;if(t!==~~t||t<-K8||t>K8)throw Error(Yo+"exponent");for(i&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return i?r.div(n):n},Ye.prec=function(t,e){if(t!==~~t||t<1||t>Zo)throw Error(Yo+"precision");return Jo(new this.constructor(this),t,e)},Ye.round=function(t,e){if(t===Ii)t=0;else if(t!==~~t||t<-Zo||t>Zo)throw Error(rf);return Jo(new this.constructor(this),t+this.e+1,e)},Ye.sqrt=function(){var t,e,r,n=this,i=n.constructor,s=n.s,o=n.e,a=new i("0.5");if(!n.c[0])return new i(n);if(s<0)throw Error(Hu+"No square root");s=Math.sqrt(+Xo(n,!0,!0)),s===0||s===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),s=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):t=new i(s+""),o=t.e+(i.DP+=4);do r=t,t=a.times(r.plus(n.div(r)));while(r.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return Jo(t,(i.DP-=4)+t.e+1,i.RM)},Ye.times=Ye.mul=function(t){var e,r=this,n=r.constructor,i=r.c,s=(t=new n(t)).c,o=i.length,a=s.length,c=r.e,l=t.e;if(t.s=r.s==t.s?1:-1,!i[0]||!s[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=s,s=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+s[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t},Ye.toExponential=function(t,e){var r=this,n=r.c[0];if(t!==Ii){if(t!==~~t||t<0||t>Zo)throw Error(rf);for(r=Jo(new r.constructor(r),++t,e);r.c.length<t;)r.c.push(0)}return Xo(r,!0,!!n)},Ye.toFixed=function(t,e){var r=this,n=r.c[0];if(t!==Ii){if(t!==~~t||t<0||t>Zo)throw Error(rf);for(r=Jo(new r.constructor(r),t+r.e+1,e),t=t+r.e+1;r.c.length<t;)r.c.push(0)}return Xo(r,!1,!!n)},Ye[Symbol.for("nodejs.util.inspect.custom")]=Ye.toJSON=Ye.toString=function(){var t=this,e=t.constructor;return Xo(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])},Ye.toNumber=function(){var t=+Xo(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(Hu+"Imprecise conversion");return t},Ye.toPrecision=function(t,e){var r=this,n=r.constructor,i=r.c[0];if(t!==Ii){if(t!==~~t||t<1||t>Zo)throw Error(Yo+"precision");for(r=Jo(new n(r),t,e);r.c.length<t;)r.c.push(0)}return Xo(r,t<=r.e||r.e<=n.NE||r.e>=n.PE,!!i)},Ye.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(Hu+"valueOf disallowed");return Xo(t,t.e<=e.NE||t.e>=e.PE,!0)};var Wu=Z8();const nf={bigNumber(t){return t?new Wu(t):new Wu(0)},multiply(t,e){if(t===void 0||e===void 0)return new Wu(0);const r=new Wu(t),n=new Wu(e);return r.times(n)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},TW=[{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"}]}],kW=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],RW=[{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"}]}],de={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",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network"},DW={getERC20Abi:t=>de.USDT_CONTRACT_ADDRESSES.includes(t)?RW:TW,getSwapAbi:()=>kW},Ys={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[r,n,i]=e;if(!r||!n||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:r,chainId:n,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[r,n]=e;if(!r||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:r,chainId:n}}},Se={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types"};function Qw(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const $e={setItem(t,e){Vu()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Vu())return localStorage.getItem(t)||void 0},removeItem(t){Vu()&&localStorage.removeItem(t)},clear(){Vu()&&localStorage.clear()}};function Vu(){return typeof window<"u"&&typeof localStorage<"u"}function Js(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const BW=Symbol(),Y8=Object.getPrototypeOf,em=new WeakMap,UW=t=>t&&(em.has(t)?em.get(t):Y8(t)===Object.prototype||Y8(t)===Array.prototype),LW=t=>UW(t)&&t[BW]||null,J8=(t,e=!0)=>{em.set(t,e)},tm=t=>typeof t=="object"&&t!==null,Xs=new WeakMap,Ku=new WeakSet,FW=(t=Object.is,e=(l,u)=>new Proxy(l,u),r=l=>tm(l)&&!Ku.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,u,d=n)=>{const h=i.get(l);if(h?.[0]===u)return h[1];const f=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return J8(f,!0),i.set(l,[u,f]),Reflect.ownKeys(l).forEach(g=>{if(Object.getOwnPropertyDescriptor(f,g))return;const w=Reflect.get(l,g),{enumerable:p}=Reflect.getOwnPropertyDescriptor(l,g),b={value:w,enumerable:p,configurable:!0};if(Ku.has(w))J8(w,!1);else if(w instanceof Promise)delete b.value,b.get=()=>d(w);else if(Xs.has(w)){const[m,E]=Xs.get(w);b.value=s(m,E(),d)}Object.defineProperty(f,g,b)}),Object.preventExtensions(f)},o=new WeakMap,a=[1,1],c=l=>{if(!tm(l))throw new Error("object required");const u=o.get(l);if(u)return u;let d=a[0];const h=new Set,f=($,D=++a[0])=>{d!==D&&(d=D,h.forEach(T=>T($,D)))};let g=a[1];const w=($=++a[1])=>(g!==$&&!h.size&&(g=$,b.forEach(([D])=>{const T=D[1]($);T>d&&(d=T)})),d),p=$=>(D,T)=>{const R=[...D];R[1]=[$,...R[1]],f(R,T)},b=new Map,m=($,D)=>{if(b.has($))throw new Error("prop listener already exists");if(h.size){const T=D[3](p($));b.set($,[D,T])}else b.set($,[D])},E=$=>{var D;const T=b.get($);T&&(b.delete($),(D=T[1])==null||D.call(T))},C=$=>(h.add($),h.size===1&&b.forEach(([T,R],M)=>{if(R)throw new Error("remove already exists");const x=T[3](p(M));b.set(M,[T,x])}),()=>{h.delete($),h.size===0&&b.forEach(([T,R],M)=>{R&&(R(),b.set(M,[T]))})}),P=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),I=e(P,{deleteProperty($,D){const T=Reflect.get($,D);E(D);const R=Reflect.deleteProperty($,D);return R&&f(["delete",[D],T]),R},set($,D,T,R){const M=Reflect.has($,D),x=Reflect.get($,D,R);if(M&&(t(x,T)||o.has(T)&&t(x,o.get(T))))return!0;E(D),tm(T)&&(T=LW(T)||T);let y=T;if(T instanceof Promise)T.then(v=>{T.status="fulfilled",T.value=v,f(["resolve",[D],v])}).catch(v=>{T.status="rejected",T.reason=v,f(["reject",[D],v])});else{!Xs.has(T)&&r(T)&&(y=c(T));const v=!Ku.has(y)&&Xs.get(y);v&&m(D,v)}return Reflect.set($,D,y,R),f(["set",[D],T,x]),!0}});o.set(l,I);const N=[P,w,s,C];return Xs.set(I,N),Reflect.ownKeys(l).forEach($=>{const D=Object.getOwnPropertyDescriptor(l,$);"value"in D&&(I[$]=l[$],delete D.value,delete D.writable),Object.defineProperty(P,$,D)}),I})=>[c,Xs,Ku,t,e,r,n,i,s,o,a],[MW]=FW();function at(t={}){return MW(t)}function Ir(t,e,r){const n=Xs.get(t);n||console.warn("Please use proxy object");let i;const s=[],o=n[3];let a=!1;const l=o(u=>{if(s.push(u),r){e(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Gu(t,e){const r=Xs.get(t);r||console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}function Qo(t){return Ku.add(t),t}function Rr(t,e,r,n){let i=t[e];return Ir(t,()=>{const s=t[e];Object.is(i,s)||r(i=s)},n)}function jW(t){const e=at({data:Array.from(t||[]),has(r){return this.data.some(n=>n[0]===r)},set(r,n){const i=this.data.find(s=>s[0]===r);return i?i[1]=n:this.data.push([r,n]),this},get(r){var n;return(n=this.data.find(i=>i[0]===r))==null?void 0:n[1]},delete(r){const n=this.data.findIndex(i=>i[0]===r);return n===-1?!1:(this.data.splice(n,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(r){this.data.forEach(n=>{r(n[1],n[0],this)})},keys(){return this.data.map(r=>r[0]).values()},values(){return this.data.map(r=>r[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}const rm=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",zW=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Bt={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:rm,SECURE_SITE_DASHBOARD:`${rm}/dashboard`,SECURE_SITE_FAVICON:`${rm}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",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"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],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:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in a new browser tab"},DEFAULT_FEATURES:{swaps:!0,onramp:!0,receive:!0,send:!0,email:!0,emailShowWallets:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],history:!0,analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0},DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}},he={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=he.getActiveNamespace(),e=he.getActiveCaipNetworkId(),r=e?e.split(":")[1]:void 0,n=r?isNaN(Number(r))?r:Number(r):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{$e.setItem(Se.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=$e.getItem(Se.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{$e.removeItem(Se.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{$e.setItem(Se.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{$e.setItem(Se.ACTIVE_CAIP_NETWORK_ID,t),he.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return $e.getItem(Se.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{$e.removeItem(Se.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=Qw(t);$e.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=he.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),$e.setItem(Se.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=$e.getItem(Se.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const r=Qw(t);$e.setItem(r,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return $e.getItem(Se.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=Qw(t);return $e.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{$e.setItem(Se.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return $e.getItem(Se.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{$e.removeItem(Se.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return $e.getItem(Se.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return $e.getItem(Se.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{$e.setItem(Se.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return $e.getItem(Se.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=$e.getItem(Se.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));$e.setItem(Se.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=he.getConnectedNamespaces();e.includes(t)||(e.push(t),he.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=he.getConnectedNamespaces(),r=e.indexOf(t);r>-1&&(e.splice(r,1),he.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return $e.getItem(Se.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{$e.setItem(Se.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{$e.removeItem(Se.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=$e.getItem(Se.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=he.getBalanceCache();$e.setItem(Se.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const r=he.getBalanceCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.portfolio))return r.balance;he.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=he.getBalanceCache();e[t.caipAddress]=t,$e.setItem(Se.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=$e.getItem(Se.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=he.getBalanceCache();$e.setItem(Se.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const r=he.getNativeBalanceCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.nativeBalance))return r;console.info("Discarding cache for address",t),he.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=he.getNativeBalanceCache();e[t.caipAddress]=t,$e.setItem(Se.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=$e.getItem(Se.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const r=he.getEnsCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.ens))return r.ens;he.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=he.getEnsCache();e[t.address]=t,$e.setItem(Se.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=he.getEnsCache();$e.setItem(Se.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=$e.getItem(Se.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const r=he.getIdentityCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.identity))return r.identity;he.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=he.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},$e.setItem(Se.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=he.getIdentityCache();$e.setItem(Se.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{$e.removeItem(Se.PORTFOLIO_CACHE),$e.removeItem(Se.NATIVE_BALANCE_CACHE),$e.removeItem(Se.ENS_CACHE),$e.removeItem(Se.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{$e.setItem(Se.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=$e.getItem(Se.PREFERRED_ACCOUNT_TYPES);return JSON.parse(t)}catch{console.info("Unable to get preferred account types")}}},X={isMobile(){return this.isClient()?!!(window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return X.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Bt.TEN_SEC_MS:!0},isAllowedRetry(t,e=Bt.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},getPairingExpiry(){return Date.now()+Bt.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let r;return(...n)=>{function i(){t(...n)}r&&clearTimeout(r),r=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e){if(X.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t;r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,href:r}},formatUniversalUrl(t,e){if(!X.isHttpUrl(t))return this.formatNativeUrl(t,e);let r=t;r.endsWith("/")||(r=`${r}/`);const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,href:r}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?he.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,r){window?.open(t,this.getOpenTargetForPlatform(e),r||"noreferrer noopener")},returnOpenHref(t,e,r){return window?.open(t,this.getOpenTargetForPlatform(e),r||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},async preloadImage(t){const e=new Promise((r,n)=>{const i=new Image;i.onload=r,i.onerror=n,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,X.wait(2e3)])},formatBalance(t,e){let r="0.000";if(typeof t=="string"){const n=Number(t);if(n){const i=Math.floor(n*1e3)/1e3;i&&(r=i.toString())}}return`${r}${e?` ${e}`:""}`},formatBalance2(t,e){let r;if(t==="0")r="0";else if(typeof t=="string"){const n=Number(t);n&&(r=n.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:r??"0",rest:r==="0"?"000":"",symbol:e}},getApiUrl(){return de.W3M_API_URL},getBlockchainApiUrl(){return de.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return de.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const r={};return e&&t&&(t.forEach((n,i)=>{r[n]=i}),e.sort((n,i)=>{const s=r[n.id],o=r[i.id];return s!==void 0&&o!==void 0?s-o:s!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const r of t)e+=r.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[r,n]=e.split(".");return{dollars:r,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const r=new Set;return t.filter(n=>{const i=n[e];return r.has(i)?!1:(r.add(i),!0)})},generateSdkVersion(t,e,r){const i=t.length===0?Bt.ADAPTER_TYPES.UNIVERSAL:t.map(s=>s.adapterType).join(",");return`${e}-${i}-${r}`},createAccount(t,e,r,n,i){return{namespace:t,address:e,type:r,publicKey:n,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),r=e[0];return e.filter(Boolean).length===3&&r in de.CHAIN_NAME_MAP},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,r="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",s=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),r,e);return t.replace(s,encodeURIComponent(o))}return this.injectIntoUrl(t,r,e)},injectIntoUrl(t,e,r){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",n),s=e.length,o=i!==-1?i:t.length,a=t.substring(0,n+s),c=t.substring(n+s,o),l=t.substring(i),u=c+r;return a+u+l}};async function Zu(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class sf{constructor({baseUrl:e,clientId:r}){this.baseUrl=e,this.clientId=r}async get({headers:e,signal:r,cache:n,...i}){const s=this.createUrl(i);return(await Zu(s,{method:"GET",headers:e,signal:r,cache:n})).json()}async getBlob({headers:e,signal:r,...n}){const i=this.createUrl(n);return(await Zu(i,{method:"GET",headers:e,signal:r})).blob()}async post({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await Zu(s,{method:"POST",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await Zu(s,{method:"PUT",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await Zu(s,{method:"DELETE",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:r}){const n=new URL(e,this.baseUrl);return r&&Object.entries(r).forEach(([i,s])=>{s&&n.searchParams.append(i,s)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}}const qW={handleSolanaDeeplinkRedirect(t){if(B.state.activeChain===de.CHAIN.SOLANA){const e=window.location.href,r=encodeURIComponent(e);if(t==="Phantom"&&!("phantom"in window)){const n=e.startsWith("https")?"https":"http",i=e.split("/")[2],s=encodeURIComponent(`${n}://${i}`);window.location.href=`https://phantom.app/ul/browse/${r}?ref=${s}`}t==="Coinbase Wallet"&&!("coinbaseSolana"in window)&&(window.location.href=`https://go.cb-w.com/dapp?cb_url=${r}`)}}},gn=at({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Kr={state:gn,subscribeNetworkImages(t){return Ir(gn.networkImages,()=>t(gn.networkImages))},subscribeKey(t,e){return Rr(gn,t,e)},subscribe(t){return Ir(gn,()=>t(gn))},setWalletImage(t,e){gn.walletImages[t]=e},setNetworkImage(t,e){gn.networkImages[t]=e},setChainImage(t,e){gn.chainImages[t]=e},setConnectorImage(t,e){gn.connectorImages={...gn.connectorImages,[t]:e}},setTokenImage(t,e){gn.tokenImages[t]=e},setCurrencyImage(t,e){gn.currencyImages[t]=e}},HW={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},nm=at({networkImagePromises:{}}),Ut={async fetchWalletImage(t){if(t)return await se._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(nm.networkImagePromises[t]||(nm.networkImagePromises[t]=se._fetchNetworkImage(t)),await nm.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Kr.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return Kr.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return Kr.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Kr.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.imageId)return Kr.state.connectorImages[t.imageId]},getChainImage(t){return Kr.state.networkImages[HW[t]]}},WW={getFeatureValue(t,e){const r=e?.[t];return r===void 0?Bt.DEFAULT_FEATURES[t]:r},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(X.isTelegram()){if(X.isIos())return t.filter(e=>e!=="google");if(X.isMac())return t.filter(e=>e!=="x");if(X.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},be=at({features:Bt.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:{solana:"eoa",bip122:"payment",polkadot:"eoa",eip155:"smartAccount"},enableNetworkSwitch:!0}),G={state:be,subscribeKey(t,e){return Rr(be,t,e)},setOptions(t){Object.assign(be,t)},setFeatures(t){if(!t)return;be.features||(be.features=Bt.DEFAULT_FEATURES);const e={...be.features,...t};be.features=e,be.features.socials&&(be.features.socials=WW.filterSocialsByPlatform(be.features.socials))},setProjectId(t){be.projectId=t},setCustomRpcUrls(t){be.customRpcUrls=t},setAllWallets(t){be.allWallets=t},setIncludeWalletIds(t){be.includeWalletIds=t},setExcludeWalletIds(t){be.excludeWalletIds=t},setFeaturedWalletIds(t){be.featuredWalletIds=t},setTokens(t){be.tokens=t},setTermsConditionsUrl(t){be.termsConditionsUrl=t},setPrivacyPolicyUrl(t){be.privacyPolicyUrl=t},setCustomWallets(t){be.customWallets=t},setIsSiweEnabled(t){be.isSiweEnabled=t},setIsUniversalProvider(t){be.isUniversalProvider=t},setSdkVersion(t){be.sdkVersion=t},setMetadata(t){be.metadata=t},setDisableAppend(t){be.disableAppend=t},setEIP6963Enabled(t){be.enableEIP6963=t},setDebug(t){be.debug=t},setEnableWalletConnect(t){be.enableWalletConnect=t},setEnableWalletGuide(t){be.enableWalletGuide=t},setEnableAuthLogger(t){be.enableAuthLogger=t},setEnableWallets(t){be.enableWallets=t},setHasMultipleAddresses(t){be.hasMultipleAddresses=t},setSIWX(t){be.siwx=t},setConnectMethodsOrder(t){be.features={...be.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){be.features={...be.features,walletFeaturesOrder:t}},setSocialsOrder(t){be.features={...be.features,socials:t}},setCollapseWallets(t){be.features={...be.features,collapseWallets:t}},setEnableEmbedded(t){be.enableEmbedded=t},setAllowUnsupportedChain(t){be.allowUnsupportedChain=t},setManualWCControl(t){be.manualWCControl=t},setEnableNetworkSwitch(t){be.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,r])=>{r&&(be.defaultAccountTypes[e]=r)})},setUniversalProviderConfigOverride(t){be.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return be.universalProviderConfigOverride},getSnapshot(){return Gu(be)}},Qs=at({message:"",variant:"info",open:!1}),eo={state:Qs,subscribeKey(t,e){return Rr(Qs,t,e)},open(t,e){const{debug:r}=G.state,{shortMessage:n,longMessage:i}=t;r&&(Qs.message=n,Qs.variant=e,Qs.open=!0),i&&console.error(typeof i=="function"?i():i)},close(){Qs.open=!1,Qs.message="",Qs.variant="info"}},VW=X.getAnalyticsUrl(),KW=new sf({baseUrl:VW,clientId:null}),GW=["MODAL_CREATED"],is=at({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Ae={state:is,subscribe(t){return Ir(is,()=>t(is))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:r}=G.state;return{projectId:t,st:e,sv:r||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=ge.state.address;if(GW.includes(t.data.event)||typeof window>"u")return;await KW.post({path:"/e",params:Ae.getSdkProperties(),body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),is.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===de.HTTP_STATUS_CODES.FORBIDDEN&&!is.reportedErrors.FORBIDDEN&&(eo.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${Vu()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),is.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){is.timestamp=Date.now(),is.data=t,G.state.features?.analytics&&Ae._sendAnalyticsEvent(is)}},ZW=["1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79","fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa","a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393"],YW=X.getApiUrl(),Rn=new sf({baseUrl:YW,clientId:null}),JW=40,X8=4,XW=20,Je=at({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),se={state:Je,subscribeKey(t,e){return Rr(Je,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:r}=G.state;return{projectId:t,st:e||"appkit",sv:r||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return G.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${Rn.baseUrl}/getWalletImage/${t}`,r=await Rn.getBlob({path:e,params:se._getSdkProperties()});Kr.setWalletImage(t,URL.createObjectURL(r))},async _fetchNetworkImage(t){const e=`${Rn.baseUrl}/public/getAssetImage/${t}`,r=await Rn.getBlob({path:e,params:se._getSdkProperties()});Kr.setNetworkImage(t,URL.createObjectURL(r))},async _fetchConnectorImage(t){const e=`${Rn.baseUrl}/public/getAssetImage/${t}`,r=await Rn.getBlob({path:e,params:se._getSdkProperties()});Kr.setConnectorImage(t,URL.createObjectURL(r))},async _fetchCurrencyImage(t){const e=`${Rn.baseUrl}/public/getCurrencyImage/${t}`,r=await Rn.getBlob({path:e,params:se._getSdkProperties()});Kr.setCurrencyImage(t,URL.createObjectURL(r))},async _fetchTokenImage(t){const e=`${Rn.baseUrl}/public/getTokenImage/${t}`,r=await Rn.getBlob({path:e,params:se._getSdkProperties()});Kr.setTokenImage(t,URL.createObjectURL(r))},async fetchNetworkImages(){const e=B.getAllRequestedCaipNetworks()?.map(({assets:r})=>r?.imageId).filter(Boolean).filter(r=>!Ut.getNetworkImageById(r));e&&await Promise.allSettled(e.map(r=>se._fetchNetworkImage(r)))},async fetchConnectorImages(){const{connectors:t}=oe.state,e=t.map(({imageId:r})=>r).filter(Boolean);await Promise.allSettled(e.map(r=>se._fetchConnectorImage(r)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>se._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>se._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];return se._getSdkProperties().sv.startsWith("html-core-")&&e.push(...ZW),await Rn.get({path:"/getWallets",params:{...se._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:t.exclude?.join(",")}})},async fetchFeaturedWallets(){const{featuredWalletIds:t}=G.state;if(t?.length){const e={...se._getSdkProperties(),page:1,entries:t?.length??X8,include:t},{data:r}=await se.fetchWallets(e);r.sort((i,s)=>t.indexOf(i.id)-t.indexOf(s.id));const n=r.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(n.map(i=>se._fetchWalletImage(i))),Je.featured=r,Je.allFeatured=r}},async fetchRecommendedWallets(){try{Je.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:r}=G.state,n=[...e??[],...r??[]].filter(Boolean),i=B.getRequestedCaipNetworkIds().join(","),s={page:1,entries:X8,include:t,exclude:n,chains:i},{data:o,count:a}=await se.fetchWallets(s),c=he.getRecentWallets(),l=o.map(d=>d.image_id).filter(Boolean),u=c.map(d=>d.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(d=>se._fetchWalletImage(d))),Je.recommended=o,Je.allRecommended=o,Je.count=a??0}catch{}finally{Je.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:r,featuredWalletIds:n}=G.state,i=B.getRequestedCaipNetworkIds().join(","),s=[...Je.recommended.map(({id:u})=>u),...r??[],...n??[]].filter(Boolean),o={page:t,entries:JW,include:e,exclude:s,chains:i},{data:a,count:c}=await se.fetchWallets(o),l=a.slice(0,XW).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>se._fetchWalletImage(u))),Je.wallets=X.uniqueBy([...Je.wallets,...se._filterOutExtensions(a)],"id"),Je.count=c>Je.count?c:Je.count,Je.page=t},async initializeExcludedWallets({ids:t}){const e=B.getRequestedCaipNetworkIds().join(","),r={page:1,entries:t.length,include:t,chains:e},{data:n}=await se.fetchWallets(r);n&&n.forEach(i=>{Je.excludedWallets.push({rdns:i.rdns,name:i.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:r,excludeWalletIds:n}=G.state,i=B.getRequestedCaipNetworkIds().join(",");Je.search=[];const s={page:1,entries:100,search:t?.trim(),badge_type:e,include:r,exclude:n,chains:i},{data:o}=await se.fetchWallets(s);Ae.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>se._fetchWalletImage(c)),X.wait(300)]),Je.search=se._filterOutExtensions(o)},initPromise(t,e){const r=Je.promises[t];return r||(Je.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:r=!0,fetchNetworkImages:n=!0}={}){const i=[t&&se.initPromise("connectorImages",se.fetchConnectorImages),e&&se.initPromise("featuredWallets",se.fetchFeaturedWallets),r&&se.initPromise("recommendedWallets",se.fetchRecommendedWallets),n&&se.initPromise("networkImages",se.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){G.state.features?.analytics&&se.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await Rn.get({path:"/getAnalyticsConfig",params:se._getSdkProperties()});G.setFeatures({analytics:t})}catch{G.setFeatures({analytics:!1})}},setFilterByNamespace(t){if(!t){Je.featured=Je.allFeatured,Je.recommended=Je.allRecommended;return}const e=B.getRequestedCaipNetworkIds().join(",");Je.featured=Je.allFeatured.filter(r=>r.chains?.some(n=>e.includes(n))),Je.recommended=Je.allRecommended.filter(r=>r.chains?.some(n=>e.includes(n)))}},Ve=at({view:"Connect",history:["Connect"],transactionStack:[]}),ne={state:Ve,subscribeKey(t,e){return Rr(Ve,t,e)},pushTransactionStack(t){Ve.transactionStack.push(t)},popTransactionStack(t){const e=Ve.transactionStack.pop();if(e)if(t)this.goBack(),e?.onCancel?.();else{if(e.goBack)this.goBack();else if(e.replace){const n=Ve.history.indexOf("ConnectingSiwe");n>0?this.goBackToIndex(n-1):(De.close(),Ve.history=[])}else e.view&&this.reset(e.view);e?.onSuccess?.()}},push(t,e){t!==Ve.view&&(Ve.view=t,Ve.history.push(t),Ve.data=e)},reset(t,e){Ve.view=t,Ve.history=[t],Ve.data=e},replace(t,e){Ve.history.at(-1)===t||(Ve.view=t,Ve.history[Ve.history.length-1]=t,Ve.data=e)},goBack(){const t=!B.state.activeCaipAddress&&this.state.view==="ConnectingFarcaster";if(Ve.history.length>1&&!Ve.history.includes("UnsupportedChain")){Ve.history.pop();const[e]=Ve.history.slice(-1);e&&(Ve.view=e)}else De.close();Ve.data?.wallet&&(Ve.data.wallet=void 0),setTimeout(()=>{if(t){ge.setFarcasterUrl(void 0,B.state.activeChain);const e=oe.getAuthConnector();e?.provider?.reload();const r=Gu(G.state);e?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType})}},100)},goBackToIndex(t){if(Ve.history.length>1){Ve.history=Ve.history.slice(0,t+1);const[e]=Ve.history.slice(-1);e&&(Ve.view=e)}}},ss=at({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Lt={state:ss,subscribe(t){return Ir(ss,()=>t(ss))},setThemeMode(t){ss.themeMode=t;try{const e=oe.getAuthConnector();if(e){const r=Lt.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:r,w3mThemeVariables:Js(r,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){ss.themeVariables={...ss.themeVariables,...t};try{const e=oe.getAuthConnector();if(e){const r=Lt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:r,w3mThemeVariables:Js(ss.themeVariables,ss.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Gu(ss)}},Q8={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},Xe=at({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Q8}}),oe={state:Xe,subscribe(t){return Ir(Xe,()=>{t(Xe)})},subscribeKey(t,e){return Rr(Xe,t,e)},initialize(t){t.forEach(e=>{const r=he.getConnectedConnectorId(e);r&&this.setConnectorId(r,e)})},setActiveConnector(t){t&&(Xe.activeConnector=Qo(t))},setConnectors(t){t.filter(r=>!Xe.allConnectors.some(n=>n.id===r.id&&this.getConnectorName(n.name)===this.getConnectorName(r.name)&&n.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&Xe.allConnectors.push(Qo(r))}),Xe.connectors=this.mergeMultiChainConnectors(Xe.allConnectors)},removeAdapter(t){Xe.allConnectors=Xe.allConnectors.filter(e=>e.chain!==t),Xe.connectors=this.mergeMultiChainConnectors(Xe.allConnectors)},mergeMultiChainConnectors(t){const e=this.generateConnectorMapByName(t),r=[];return e.forEach(n=>{const i=n[0],s=i?.id===de.CONNECTOR_ID.AUTH;n.length>1&&i?r.push({name:i.name,imageUrl:i.imageUrl,imageId:i.imageId,connectors:[...n],type:s?"AUTH":"MULTI_CHAIN",chain:"eip155",id:i?.id||""}):i&&r.push(i)}),r},generateConnectorMapByName(t){const e=new Map;return t.forEach(r=>{const{name:n}=r,i=this.getConnectorName(n);if(!i)return;const s=e.get(i)||[];s.find(a=>a.chain===r.chain)||s.push(r),e.set(i,s)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(r=>{e.find(n=>n.chain===r.chain)||e.push(r)}),e},addConnector(t){if(t.id===de.CONNECTOR_ID.AUTH){const e=t,r=Gu(G.state),n=Lt.getSnapshot().themeMode,i=Lt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType}),e?.provider?.syncTheme({themeMode:n,themeVariables:i,w3mThemeVariables:Js(i,n)}),this.setConnectors([t])}else this.setConnectors([t])},getAuthConnector(t){const e=t||B.state.activeChain,r=Xe.connectors.find(n=>n.id===de.CONNECTOR_ID.AUTH);if(r)return r?.connectors?.length?r.connectors.find(i=>i.chain===e):r},getAnnouncedConnectorRdns(){return Xe.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return Xe.allConnectors.find(e=>e.id===t)},getConnector(t,e){return Xe.allConnectors.filter(n=>n.chain===B.state.activeChain).find(n=>n.explorerId===t||n.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,r=Gu(G.state),n=Lt.getSnapshot().themeMode,i=Lt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,sdkType:r.sdkType,projectId:r.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:i,w3mThemeVariables:Js(i,n)})},getConnectorsByNamespace(t){const e=Xe.allConnectors.filter(r=>r.chain===t);return this.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=oe.getConnector(t.id,t.rdns);B.state.activeChain===de.CHAIN.SOLANA&&qW.handleSolanaDeeplinkRedirect(e?.name||t.name||""),e?ne.push("ConnectingExternal",{connector:e}):ne.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?this.getConnectorsByNamespace(t):this.mergeMultiChainConnectors(Xe.allConnectors)},setFilterByNamespace(t){Xe.filterByNamespace=t,Xe.connectors=this.getConnectors(t),se.setFilterByNamespace(t)},setConnectorId(t,e){t&&(Xe.activeConnectorIds={...Xe.activeConnectorIds,[e]:t},he.setConnectedConnectorId(e,t))},removeConnectorId(t){Xe.activeConnectorIds={...Xe.activeConnectorIds,[t]:void 0},he.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return Xe.activeConnectorIds[t]},isConnected(t){return t?!!Xe.activeConnectorIds[t]:Object.values(Xe.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Xe.activeConnectorIds={...Q8}}};function of(t,e){return oe.getConnectorId(t)===e}function QW(t){const e=Array.from(B.state.chains.keys());let r=[];return t?(r.push([t,B.state.chains.get(t)]),of(t,de.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(n=>{n!==t&&of(n,de.CONNECTOR_ID.WALLET_CONNECT)&&r.push([n,B.state.chains.get(n)])}):of(t,de.CONNECTOR_ID.AUTH)&&e.forEach(n=>{n!==t&&of(n,de.CONNECTOR_ID.AUTH)&&r.push([n,B.state.chains.get(n)])})):r=Array.from(B.state.chains.entries()),r}class eV extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}new eV(128);const tV="0.1.1";function rV(){return tV}class Dr extends Error{constructor(e,r={}){const n=(()=>{if(r.cause instanceof Dr){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause?.message?r.cause.message:r.details})(),i=r.cause instanceof Dr&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
41
41
  `);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${rV()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return eE(this,e)}}function eE(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?eE(t.cause,e):e?null:t}function nV(t,e){if(nE(t)>e)throw new dV({givenSize:nE(t),maxSize:e})}const os={zero:48,nine:57,A:65,F:70,a:97,f:102};function tE(t){if(t>=os.zero&&t<=os.nine)return t-os.zero;if(t>=os.A&&t<=os.F)return t-(os.A-10);if(t>=os.a&&t<=os.f)return t-(os.a-10)}function iV(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new hV({size:t.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const o=r==="right";i[o?s:n-s-1]=t[o?s:t.length-s-1]}return i}function im(t,e){if(om(t)>e)throw new yV({givenSize:om(t),maxSize:e})}function rE(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const i=t.replace("0x","");if(i.length>n*2)throw new vV({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const sV=new TextEncoder;function oV(t){return t instanceof Uint8Array?t:typeof t=="string"?cV(t):aV(t)}function aV(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function cV(t,e={}){const{size:r}=e;let n=t;r&&(im(t,r),n=sm(t,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const l=tE(i.charCodeAt(c++)),u=tE(i.charCodeAt(c++));if(l===void 0||u===void 0)throw new Dr(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=l*16+u}return o}function lV(t,e={}){const{size:r}=e,n=sV.encode(t);return typeof r=="number"?(nV(n,r),uV(n,r)):n}function uV(t,e){return iV(t,{dir:"right",size:e})}function nE(t){return t.length}class dV extends Dr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class hV extends Dr{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const pV=new TextEncoder,fV=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function iE(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function gV(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(im(r,e.size),af(r,e.size)):r}function sE(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=fV[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(im(n,e.size),sm(n,e.size)):n}function wV(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const l=typeof t=="bigint"?"n":"";throw new bV({max:s?`${s}${l}`:void 0,min:`${o}${l}`,signed:r,size:n,value:`${t}${l}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?af(c,n):c}function mV(t,e={}){return sE(pV.encode(t),e)}function af(t,e){return rE(t,{dir:"left",size:e})}function sm(t,e){return rE(t,{dir:"right",size:e})}function om(t){return Math.ceil((t.length-2)/2)}class bV extends Dr{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class yV extends Dr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class vV extends Dr{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function EV(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=Po(oV(t));return r==="Bytes"?n:sE(n)}class CV extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const am={checksum:new CV(8192)}.checksum,xV=/^0x[a-fA-F0-9]{40}$/;function oE(t,e={}){const{strict:r=!0}=e;if(!xV.test(t))throw new aE({address:t,cause:new _V});if(r){if(t.toLowerCase()===t)return;if($V(t)!==t)throw new aE({address:t,cause:new IV})}}function $V(t){if(am.has(t))return am.get(t);oE(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=EV(lV(e),{as:"Bytes"}),n=e.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return am.set(t,i),i}class aE extends Dr{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class _V extends Dr{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class IV extends Dr{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const SV=/^(.*)\[([0-9]*)\]$/,AV=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,PV=/^(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 cm(t,e){if(t.length!==e.length)throw new NV({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const i=t[n],s=e[n];r.push(cm.encode(i,s))}return iE(...r)}(function(t){function e(r,n,i=!1){if(r==="address"){const c=n;return oE(c),af(c.toLowerCase(),i?32:0)}if(r==="string")return mV(n);if(r==="bytes")return n;if(r==="bool")return af(gV(n),i?32:1);const s=r.match(PV);if(s){const[c,l,u="256"]=s,d=Number.parseInt(u)/8;return wV(n,{size:i?32:d,signed:l==="int"})}const o=r.match(AV);if(o){const[c,l]=o;if(Number.parseInt(l)!==(n.length-2)/2)throw new OV({expectedSize:Number.parseInt(l),value:n});return sm(n,i?32:0)}const a=r.match(SV);if(a&&Array.isArray(n)){const[c,l]=a,u=[];for(let d=0;d<n.length;d++)u.push(e(l,n[d],!0));return u.length===0?"0x":iE(...u)}throw new TV(r)}t.encode=e})(cm||(cm={}));class OV extends Dr{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${om(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class NV extends Dr{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
42
42
  `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class TV extends Dr{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function cf(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function kV(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yu(t,...e){if(!kV(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function RV(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");cf(t.outputLen),cf(t.blockLen)}function Dc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function cE(t,e){Yu(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const lf=BigInt(2**32-1),lE=BigInt(32);function DV(t,e=!1){return e?{h:Number(t&lf),l:Number(t>>lE&lf)}:{h:Number(t>>lE&lf)|0,l:Number(t&lf)|0}}function BV(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=DV(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const UV=(t,e,r)=>t<<r|e>>>32-r,LV=(t,e,r)=>e<<r|t>>>32-r,FV=(t,e,r)=>e<<r-32|t>>>64-r,MV=(t,e,r)=>t<<r-32|e>>>64-r,Bc=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function jV(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function lm(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Si(t,e){return t<<32-e|t>>>e}const uE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function zV(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function dE(t){for(let e=0;e<t.length;e++)t[e]=zV(t[e])}function qV(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function uf(t){return typeof t=="string"&&(t=qV(t)),Yu(t),t}function HV(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Yu(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class um{clone(){return this._cloneInto()}}function hE(t){const e=n=>t().update(uf(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function pE(t=32){if(Bc&&typeof Bc.getRandomValues=="function")return Bc.getRandomValues(new Uint8Array(t));if(Bc&&typeof Bc.randomBytes=="function")return Bc.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const fE=[],gE=[],wE=[],WV=BigInt(0),Ju=BigInt(1),VV=BigInt(2),KV=BigInt(7),GV=BigInt(256),ZV=BigInt(113);for(let t=0,e=Ju,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],fE.push(2*(5*n+r)),gE.push((t+1)*(t+2)/2%64);let i=WV;for(let s=0;s<7;s++)e=(e<<Ju^(e>>KV)*ZV)%GV,e&VV&&(i^=Ju<<(Ju<<BigInt(s))-Ju);wE.push(i)}const[YV,JV]=BV(wE,!0),mE=(t,e,r)=>r>32?FV(t,e,r):UV(t,e,r),bE=(t,e,r)=>r>32?MV(t,e,r):LV(t,e,r);function XV(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],d=mE(l,u,1)^r[a],h=bE(l,u,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=d,t[o+f+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=gE[o],c=mE(i,s,a),l=bE(i,s,a),u=fE[o];i=t[u],s=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=YV[n],t[1]^=JV[n]}r.fill(0)}class dm extends um{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,cf(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=jV(this.state)}keccak(){uE||dE(this.state32),XV(this.state32,this.rounds),uE||dE(this.state32),this.posOut=0,this.pos=0}update(e){Dc(this);const{blockLen:r,state:n}=this;e=uf(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,(r&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Dc(this,!1),Yu(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return cf(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(cE(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new dm(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}((t,e,r)=>hE(()=>new dm(e,t,r)))(1,136,256/8);function hm(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yE(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wn(t,...e){if(!yE(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function vE(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function QV(t,e){wn(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function EE(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const to=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),eK=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function tK(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function pm(t){if(typeof t=="string")t=tK(t);else if(yE(t))t=fm(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function rK(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function nK(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}const iK=(t,e)=>{function r(n,...i){if(wn(n),t.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?wn(l):wn(l,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&wn(i[1]);const o=e(n,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");wn(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,wn(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(wn(l),s&&l.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(r,t),r};function CE(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(r&&!sK(e))throw new Error("invalid output, must be aligned");return e}function xE(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function sK(t){return t.byteOffset%4===0}function fm(t){return Uint8Array.from(t)}function Uc(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const $E=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),oK=$E("expand 16-byte k"),aK=$E("expand 32-byte k"),cK=to(oK),lK=to(aK);function Fe(t,e){return t<<e|t>>>32-e}function gm(t){return t.byteOffset%4===0}const df=64,uK=16,_E=2**32-1,IE=new Uint32Array;function dK(t,e,r,n,i,s,o,a){const c=i.length,l=new Uint8Array(df),u=to(l),d=gm(i)&&gm(s),h=d?to(i):IE,f=d?to(s):IE;for(let g=0;g<c;o++){if(t(e,r,n,u,o,a),o>=_E)throw new Error("arx: counter overflow");const w=Math.min(df,c-g);if(d&&w===df){const p=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<uK;b++)m=p+b,f[m]=h[m]^u[b];g+=df;continue}for(let p=0,b;p<w;p++)b=g+p,s[b]=i[b]^l[p];g+=w}}function hK(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=rK({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return hm(i),hm(o),EE(s),EE(r),(a,c,l,u,d=0)=>{wn(a),wn(c),wn(l);const h=l.length;if(u===void 0&&(u=new Uint8Array(h)),wn(u),hm(d),d<0||d>=_E)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);const f=[];let g=a.length,w,p;if(g===32)f.push(w=fm(a)),p=lK;else if(g===16&&r)w=new Uint8Array(32),w.set(a),w.set(a,16),p=cK,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);gm(c)||f.push(c=fm(c));const b=to(w);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(p,b,to(c.subarray(0,16)),b),c=c.subarray(16)}const m=16-i;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const C=new Uint8Array(12);C.set(c,s?0:12-c.length),c=C,f.push(c)}const E=to(c);return dK(t,p,b,E,l,u,d,o),Uc(...f),u}}const fr=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class pK{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=pm(e),wn(e,32);const r=fr(e,0),n=fr(e,2),i=fr(e,4),s=fr(e,6),o=fr(e,8),a=fr(e,10),c=fr(e,12),l=fr(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=fr(e,16+2*u)}process(e,r,n=!1){const i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],h=o[5],f=o[6],g=o[7],w=o[8],p=o[9],b=fr(e,r+0),m=fr(e,r+2),E=fr(e,r+4),C=fr(e,r+6),P=fr(e,r+8),S=fr(e,r+10),I=fr(e,r+12),N=fr(e,r+14);let $=s[0]+(b&8191),D=s[1]+((b>>>13|m<<3)&8191),T=s[2]+((m>>>10|E<<6)&8191),R=s[3]+((E>>>7|C<<9)&8191),M=s[4]+((C>>>4|P<<12)&8191),x=s[5]+(P>>>1&8191),y=s[6]+((P>>>14|S<<2)&8191),v=s[7]+((S>>>11|I<<5)&8191),A=s[8]+((I>>>8|N<<8)&8191),O=s[9]+(N>>>5|i),_=0,k=_+$*a+D*(5*p)+T*(5*w)+R*(5*g)+M*(5*f);_=k>>>13,k&=8191,k+=x*(5*h)+y*(5*d)+v*(5*u)+A*(5*l)+O*(5*c),_+=k>>>13,k&=8191;let L=_+$*c+D*a+T*(5*p)+R*(5*w)+M*(5*g);_=L>>>13,L&=8191,L+=x*(5*f)+y*(5*h)+v*(5*d)+A*(5*u)+O*(5*l),_+=L>>>13,L&=8191;let F=_+$*l+D*c+T*a+R*(5*p)+M*(5*w);_=F>>>13,F&=8191,F+=x*(5*g)+y*(5*f)+v*(5*h)+A*(5*d)+O*(5*u),_+=F>>>13,F&=8191;let H=_+$*u+D*l+T*c+R*a+M*(5*p);_=H>>>13,H&=8191,H+=x*(5*w)+y*(5*g)+v*(5*f)+A*(5*h)+O*(5*d),_+=H>>>13,H&=8191;let q=_+$*d+D*u+T*l+R*c+M*a;_=q>>>13,q&=8191,q+=x*(5*p)+y*(5*w)+v*(5*g)+A*(5*f)+O*(5*h),_+=q>>>13,q&=8191;let W=_+$*h+D*d+T*u+R*l+M*c;_=W>>>13,W&=8191,W+=x*a+y*(5*p)+v*(5*w)+A*(5*g)+O*(5*f),_+=W>>>13,W&=8191;let Y=_+$*f+D*h+T*d+R*u+M*l;_=Y>>>13,Y&=8191,Y+=x*c+y*a+v*(5*p)+A*(5*w)+O*(5*g),_+=Y>>>13,Y&=8191;let ae=_+$*g+D*f+T*h+R*d+M*u;_=ae>>>13,ae&=8191,ae+=x*l+y*c+v*a+A*(5*p)+O*(5*w),_+=ae>>>13,ae&=8191;let re=_+$*w+D*g+T*f+R*h+M*d;_=re>>>13,re&=8191,re+=x*u+y*l+v*c+A*a+O*(5*p),_+=re>>>13,re&=8191;let te=_+$*p+D*w+T*g+R*f+M*h;_=te>>>13,te&=8191,te+=x*d+y*u+v*l+A*c+O*a,_+=te>>>13,te&=8191,_=(_<<2)+_|0,_=_+k|0,k=_&8191,_=_>>>13,L+=_,s[0]=k,s[1]=L,s[2]=F,s[3]=H,s[4]=q,s[5]=W,s[6]=Y,s[7]=ae,s[8]=re,s[9]=te}finalize(){const{h:e,pad:r}=this,n=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Uc(n)}update(e){vE(this);const{buffer:r,blockLen:n}=this;e=pm(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Uc(this.h,this.r,this.buffer,this.pad)}digestInto(e){vE(this),QV(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}function fK(t){const e=(n,i)=>t(i).update(pm(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const gK=fK(t=>new pK(t));function wK(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],h=e[2],f=e[3],g=e[4],w=e[5],p=e[6],b=e[7],m=i,E=r[0],C=r[1],P=r[2],S=o,I=a,N=c,$=l,D=u,T=d,R=h,M=f,x=g,y=w,v=p,A=b,O=m,_=E,k=C,L=P;for(let H=0;H<s;H+=2)S=S+D|0,O=Fe(O^S,16),x=x+O|0,D=Fe(D^x,12),S=S+D|0,O=Fe(O^S,8),x=x+O|0,D=Fe(D^x,7),I=I+T|0,_=Fe(_^I,16),y=y+_|0,T=Fe(T^y,12),I=I+T|0,_=Fe(_^I,8),y=y+_|0,T=Fe(T^y,7),N=N+R|0,k=Fe(k^N,16),v=v+k|0,R=Fe(R^v,12),N=N+R|0,k=Fe(k^N,8),v=v+k|0,R=Fe(R^v,7),$=$+M|0,L=Fe(L^$,16),A=A+L|0,M=Fe(M^A,12),$=$+M|0,L=Fe(L^$,8),A=A+L|0,M=Fe(M^A,7),S=S+T|0,L=Fe(L^S,16),v=v+L|0,T=Fe(T^v,12),S=S+T|0,L=Fe(L^S,8),v=v+L|0,T=Fe(T^v,7),I=I+R|0,O=Fe(O^I,16),A=A+O|0,R=Fe(R^A,12),I=I+R|0,O=Fe(O^I,8),A=A+O|0,R=Fe(R^A,7),N=N+M|0,_=Fe(_^N,16),x=x+_|0,M=Fe(M^x,12),N=N+M|0,_=Fe(_^N,8),x=x+_|0,M=Fe(M^x,7),$=$+D|0,k=Fe(k^$,16),y=y+k|0,D=Fe(D^y,12),$=$+D|0,k=Fe(k^$,8),y=y+k|0,D=Fe(D^y,7);let F=0;n[F++]=o+S|0,n[F++]=a+I|0,n[F++]=c+N|0,n[F++]=l+$|0,n[F++]=u+D|0,n[F++]=d+T|0,n[F++]=h+R|0,n[F++]=f+M|0,n[F++]=g+x|0,n[F++]=w+y|0,n[F++]=p+v|0,n[F++]=b+A|0,n[F++]=m+O|0,n[F++]=E+_|0,n[F++]=C+k|0,n[F++]=P+L|0}const mK=hK(wK,{counterRight:!1,counterLength:4,allowShortKeys:!1}),bK=new Uint8Array(16),SE=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(bK.subarray(r))},yK=new Uint8Array(32);function AE(t,e,r,n,i){const s=t(e,r,yK),o=gK.create(s);i&&SE(o,i),SE(o,n);const a=new Uint8Array(16),c=eK(a);xE(c,0,BigInt(i?i.length:0),!0),xE(c,8,BigInt(n.length),!0),o.update(a);const l=o.digest();return Uc(s,a),l}iK({blockSize:64,nonceLength:12,tagLength:16},(t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=CE(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=AE(t,e,r,a,n);return s.set(c,o),Uc(c),s},decrypt(i,s){s=CE(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=AE(t,e,r,o,n);if(!nK(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),Uc(c),s}}))(mK));class PE extends um{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,RV(e);const n=uf(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return Dc(this),this.iHash.update(e),this}digestInto(e){Dc(this),Yu(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const OE=(t,e,r)=>new PE(t,e).update(r).digest();OE.create=(t,e)=>new PE(t,e);function vK(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function EK(t,e,r){return t&e^~t&r}function CK(t,e,r){return t&e^t&r^e&r}class xK extends um{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=lm(this.buffer)}update(e){Dc(this);const{view:r,buffer:n,blockLen:i}=this;e=uf(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=lm(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Dc(this),cE(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;vK(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=lm(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%r&&e.buffer.set(n),e}}const $K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ro=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),no=new Uint32Array(64);class _K extends xK{constructor(){super(64,32,8,!1),this.A=ro[0]|0,this.B=ro[1]|0,this.C=ro[2]|0,this.D=ro[3]|0,this.E=ro[4]|0,this.F=ro[5]|0,this.G=ro[6]|0,this.H=ro[7]|0}get(){const{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)no[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){const h=no[d-15],f=no[d-2],g=Si(h,7)^Si(h,18)^h>>>3,w=Si(f,17)^Si(f,19)^f>>>10;no[d]=w+no[d-7]+g+no[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const h=Si(a,6)^Si(a,11)^Si(a,25),f=u+h+EK(a,c,l)+$K[d]+no[d]|0,g=(Si(n,2)^Si(n,13)^Si(n,22))+CK(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+g|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){no.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const IK=hE(()=>new _K);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hf=BigInt(0),pf=BigInt(1),SK=BigInt(2);function ea(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Xu(t){if(!ea(t))throw new Error("Uint8Array expected")}function Lc(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const AK=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Fc(t){Xu(t);let e="";for(let r=0;r<t.length;r++)e+=AK[t[r]];return e}function Mc(t){const e=t.toString(16);return e.length&1?"0"+e:e}function wm(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?hf:BigInt("0x"+t)}const as={_0:48,_9:57,A:65,F:70,a:97,f:102};function NE(t){if(t>=as._0&&t<=as._9)return t-as._0;if(t>=as.A&&t<=as.F)return t-(as.A-10);if(t>=as.a&&t<=as.f)return t-(as.a-10)}function jc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=NE(t.charCodeAt(s)),a=NE(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function ta(t){return wm(Fc(t))}function Qu(t){return Xu(t),wm(Fc(Uint8Array.from(t).reverse()))}function zc(t,e){return jc(t.toString(16).padStart(e*2,"0"))}function ff(t,e){return zc(t,e).reverse()}function PK(t){return jc(Mc(t))}function mn(t,e,r){let n;if(typeof e=="string")try{n=jc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ea(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function ed(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Xu(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}function OK(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function NK(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const mm=t=>typeof t=="bigint"&&hf<=t;function gf(t,e,r){return mm(t)&&mm(e)&&mm(r)&&e<=t&&t<r}function cs(t,e,r,n){if(!gf(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function TE(t){let e;for(e=0;t>hf;t>>=pf,e+=1);return e}function TK(t,e){return t>>BigInt(e)&pf}function kK(t,e,r){return t|(r?pf:hf)<<BigInt(e)}const bm=t=>(SK<<BigInt(t-1))-pf,ym=t=>new Uint8Array(t),kE=t=>Uint8Array.from(t);function RE(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=ym(t),i=ym(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...u)=>r(i,n,...u),c=(u=ym())=>{i=a(kE([0]),u),n=a(),u.length!==0&&(i=a(kE([1]),u),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<e;){n=a();const h=n.slice();d.push(h),u+=n.length}return ed(...d)};return(u,d)=>{o(),c(u);let h;for(;!(h=d(l()));)c();return o(),h}}const RK={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||ea(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function qc(t,e,r={}){const n=(i,s,o)=>{const a=RK[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))n(i,s,!1);for(const[i,s]of Object.entries(r))n(i,s,!0);return t}const DK=()=>{throw new Error("not implemented")};function vm(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}var BK=Object.freeze({__proto__:null,isBytes:ea,abytes:Xu,abool:Lc,bytesToHex:Fc,numberToHexUnpadded:Mc,hexToNumber:wm,hexToBytes:jc,bytesToNumberBE:ta,bytesToNumberLE:Qu,numberToBytesBE:zc,numberToBytesLE:ff,numberToVarBytesBE:PK,ensureBytes:mn,concatBytes:ed,equalBytes:OK,utf8ToBytes:NK,inRange:gf,aInRange:cs,bitLen:TE,bitGet:TK,bitSet:kK,bitMask:bm,createHmacDrbg:RE,validateObject:qc,notImplemented:DK,memoized:vm});const Qt=BigInt(0),It=BigInt(1),ra=BigInt(2),UK=BigInt(3),Em=BigInt(4),DE=BigInt(5),BE=BigInt(8);function Gr(t,e){const r=t%e;return r>=Qt?r:e+r}function UE(t,e,r){if(e<Qt)throw new Error("invalid exponent, negatives unsupported");if(r<=Qt)throw new Error("invalid modulus");if(r===It)return Qt;let n=It;for(;e>Qt;)e&It&&(n=n*t%r),t=t*t%r,e>>=It;return n}function ri(t,e,r){let n=t;for(;e-- >Qt;)n*=n,n%=r;return n}function Cm(t,e){if(t===Qt)throw new Error("invert: expected non-zero number");if(e<=Qt)throw new Error("invert: expected positive modulus, got "+e);let r=Gr(t,e),n=e,i=Qt,s=It;for(;r!==Qt;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==It)throw new Error("invert: does not exist");return Gr(i,e)}function LK(t){const e=(t-It)/ra;let r,n,i;for(r=t-It,n=0;r%ra===Qt;r/=ra,n++);for(i=ra;i<t&&UE(i,e,t)!==t-It;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+It)/Em;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const s=(r+It)/ra;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,l=o.pow(o.mul(o.ONE,i),r),u=o.pow(a,s),d=o.pow(a,r);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let h=1;for(let g=o.sqr(d);h<c&&!o.eql(g,o.ONE);h++)g=o.sqr(g);const f=o.pow(l,It<<BigInt(c-h-1));l=o.sqr(f),u=o.mul(u,f),d=o.mul(d,l),c=h}return u}}function FK(t){if(t%Em===UK){const e=(t+It)/Em;return function(r,n){const i=r.pow(n,e);if(!r.eql(r.sqr(i),n))throw new Error("Cannot find square root");return i}}if(t%BE===DE){const e=(t-DE)/BE;return function(r,n){const i=r.mul(n,ra),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,ra),s),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return LK(t)}const MK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jK(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=MK.reduce((n,i)=>(n[i]="function",n),e);return qc(t,r)}function zK(t,e,r){if(r<Qt)throw new Error("invalid exponent, negatives unsupported");if(r===Qt)return t.ONE;if(r===It)return e;let n=t.ONE,i=e;for(;r>Qt;)r&It&&(n=t.mul(n,i)),i=t.sqr(i),r>>=It;return n}function qK(t,e){const r=new Array(e.length),n=e.reduce((s,o,a)=>t.is0(o)?s:(r[a]=s,t.mul(s,o)),t.ONE),i=t.inv(n);return e.reduceRight((s,o,a)=>t.is0(o)?s:(r[a]=t.mul(s,r[a]),t.mul(s,o)),i),r}function LE(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function FE(t,e,r=!1,n={}){if(t<=Qt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=LE(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:i,BYTES:s,MASK:bm(i),ZERO:Qt,ONE:It,create:c=>Gr(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Qt<=c&&c<t},is0:c=>c===Qt,isOdd:c=>(c&It)===It,neg:c=>Gr(-c,t),eql:(c,l)=>c===l,sqr:c=>Gr(c*c,t),add:(c,l)=>Gr(c+l,t),sub:(c,l)=>Gr(c-l,t),mul:(c,l)=>Gr(c*l,t),pow:(c,l)=>zK(a,c,l),div:(c,l)=>Gr(c*Cm(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Cm(c,t),sqrt:n.sqrt||(c=>(o||(o=FK(t)),o(a,c))),invertBatch:c=>qK(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>r?ff(c,s):zc(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Qu(c):ta(c)}});return Object.freeze(a)}function ME(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function jE(t){const e=ME(t);return e+Math.ceil(e/2)}function HK(t,e,r=!1){const n=t.length,i=ME(e),s=jE(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?Qu(t):ta(t),a=Gr(o,e-It)+It;return r?ff(a,i):zc(a,i)}const zE=BigInt(0),wf=BigInt(1);function xm(t,e){const r=e.negate();return t?r:e}function qE(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $m(t,e){qE(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function WK(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function VK(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const _m=new WeakMap,HE=new WeakMap;function Im(t){return HE.get(t)||1}function KK(t,e){return{constTimeNegate:xm,hasPrecomputes(r){return Im(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>zE;)n&wf&&(i=i.add(s)),s=s.double(),n>>=wf;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=$m(n,e),o=[];let a=r,c=a;for(let l=0;l<i;l++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){const{windows:s,windowSize:o}=$m(r,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**r-1),u=2**r,d=BigInt(r);for(let h=0;h<s;h++){const f=h*o;let g=Number(i&l);i>>=d,g>o&&(g-=u,i+=wf);const w=f,p=f+Math.abs(g)-1,b=h%2!==0,m=g<0;g===0?c=c.add(xm(b,n[w])):a=a.add(xm(m,n[p]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=$m(r,e),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let d=0;d<o;d++){const h=d*a;if(i===zE)break;let f=Number(i&c);if(i>>=u,f>a&&(f-=l,i+=wf),f===0)continue;let g=n[h+Math.abs(f)-1];f<0&&(g=g.negate()),s=s.add(g)}return s},getPrecomputes(r,n,i){let s=_m.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&_m.set(n,i(s))),s},wNAFCached(r,n,i){const s=Im(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Im(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){qE(n,e),HE.set(r,n),_m.delete(r)}}}function GK(t,e,r,n){if(WK(r,t),VK(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=TE(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),l=Math.floor((e.BITS-1)/o)*o;let u=i;for(let d=l;d>=0;d-=o){c.fill(i);for(let f=0;f<n.length;f++){const g=n[f],w=Number(g>>BigInt(d)&BigInt(a));c[w]=c[w].add(r[f])}let h=i;for(let f=c.length-1,g=i;f>0;f--)g=g.add(c[f]),h=h.add(g);if(u=u.add(h),d!==0)for(let f=0;f<o;f++)u=u.double()}return u}function WE(t){return jK(t.Fp),qc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...LE(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Hc=BigInt(0),Sm=BigInt(1);function ZK(t){return qc(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function YK(t){const e=ZK(t),{P:r}=e,n=m=>Gr(m,r),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>UE(m,r-BigInt(2),r));function l(m,E,C){const P=n(m*(E-C));return E=n(E-P),C=n(C+P),[E,C]}const u=(e.a-BigInt(2))/BigInt(4);function d(m,E){cs("u",m,Hc,r),cs("scalar",E,Hc,r);const C=E,P=m;let S=Sm,I=Hc,N=m,$=Sm,D=Hc,T;for(let M=BigInt(i-1);M>=Hc;M--){const x=C>>M&Sm;D^=x,T=l(D,S,N),S=T[0],N=T[1],T=l(D,I,$),I=T[0],$=T[1],D=x;const y=S+I,v=n(y*y),A=S-I,O=n(A*A),_=v-O,k=N+$,L=N-$,F=n(L*y),H=n(k*A),q=F+H,W=F-H;N=n(q*q),$=n(P*n(W*W)),S=n(v*O),I=n(_*(v+n(u*_)))}T=l(D,S,N),S=T[0],N=T[1],T=l(D,I,$),I=T[0],$=T[1];const R=c(I);return n(S*R)}function h(m){return ff(n(m),s)}function f(m){const E=mn("u coordinate",m,s);return o===32&&(E[31]&=127),Qu(E)}function g(m){const E=mn("scalar",m),C=E.length;if(C!==s&&C!==o){let P=""+s+" or "+o;throw new Error("invalid scalar, expected "+P+" bytes, got "+C)}return Qu(a(E))}function w(m,E){const C=f(E),P=g(m),S=d(C,P);if(S===Hc)throw new Error("invalid private or public key received");return h(S)}const p=h(e.Gu);function b(m){return w(m,p)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(m,E)=>w(m,E),getPublicKey:m=>b(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:p}}const Am=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const JK=BigInt(1),VE=BigInt(2),XK=BigInt(3),QK=BigInt(5);BigInt(8);function eG(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Am,o=t*t%s*t%s,a=ri(o,VE,s)*o%s,c=ri(a,JK,s)*t%s,l=ri(c,QK,s)*c%s,u=ri(l,e,s)*l%s,d=ri(u,r,s)*u%s,h=ri(d,n,s)*d%s,f=ri(h,i,s)*h%s,g=ri(f,i,s)*h%s,w=ri(g,e,s)*l%s;return{pow_p_5_8:ri(w,VE,s)*t%s,b2:o}}function tG(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}YK({P:Am,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=Am,{pow_p_5_8:r,b2:n}=eG(t);return Gr(ri(r,XK,e)*n,e)},adjustScalarBytes:tG,randomBytes:pE});function KE(t){t.lowS!==void 0&&Lc("lowS",t.lowS),t.prehash!==void 0&&Lc("prehash",t.prehash)}function rG(t){const e=WE(t);qc(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:nG,hexToBytes:iG}=BK;class sG extends Error{constructor(e=""){super(e)}}const ls={Err:sG,_tlv:{encode:(t,e)=>{const{Err:r}=ls;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=Mc(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Mc(i.length/2|128):"";return Mc(t)+s+i+e},decode(t,e){const{Err:r}=ls;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=ls;if(t<us)throw new e("integer: negative integers are not allowed");let r=Mc(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=ls;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return nG(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=ls,i=typeof t=="string"?iG(t):t;Xu(i);const{v:s,l:o}=n.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=ls,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},us=BigInt(0),er=BigInt(1);BigInt(2);const GE=BigInt(3);BigInt(4);function oG(t){const e=rG(t),{Fp:r}=e,n=FE(e.n,e.nBitLength),i=e.toBytes||((w,p,b)=>{const m=p.toAffine();return ed(Uint8Array.from([4]),r.toBytes(m.x),r.toBytes(m.y))}),s=e.fromBytes||(w=>{const p=w.subarray(1),b=r.fromBytes(p.subarray(0,r.BYTES)),m=r.fromBytes(p.subarray(r.BYTES,2*r.BYTES));return{x:b,y:m}});function o(w){const{a:p,b}=e,m=r.sqr(w),E=r.mul(m,w);return r.add(r.add(E,r.mul(w,p)),b)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(w){return gf(w,er,e.n)}function c(w){const{allowedPrivateKeyLengths:p,nByteLength:b,wrapPrivateKey:m,n:E}=e;if(p&&typeof w!="bigint"){if(ea(w)&&(w=Fc(w)),typeof w!="string"||!p.includes(w.length))throw new Error("invalid private key");w=w.padStart(b*2,"0")}let C;try{C=typeof w=="bigint"?w:ta(mn("private key",w,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof w)}return m&&(C=Gr(C,E)),cs("private key",C,er,E),C}function l(w){if(!(w instanceof h))throw new Error("ProjectivePoint expected")}const u=vm((w,p)=>{const{px:b,py:m,pz:E}=w;if(r.eql(E,r.ONE))return{x:b,y:m};const C=w.is0();p==null&&(p=C?r.ONE:r.inv(E));const P=r.mul(b,p),S=r.mul(m,p),I=r.mul(E,p);if(C)return{x:r.ZERO,y:r.ZERO};if(!r.eql(I,r.ONE))throw new Error("invZ was invalid");return{x:P,y:S}}),d=vm(w=>{if(w.is0()){if(e.allowInfinityPoint&&!r.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:p,y:b}=w.toAffine();if(!r.isValid(p)||!r.isValid(b))throw new Error("bad point: x or y not FE");const m=r.sqr(b),E=o(p);if(!r.eql(m,E))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(p,b,m){if(this.px=p,this.py=b,this.pz=m,p==null||!r.isValid(p))throw new Error("x required");if(b==null||!r.isValid(b))throw new Error("y required");if(m==null||!r.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(p){const{x:b,y:m}=p||{};if(!p||!r.isValid(b)||!r.isValid(m))throw new Error("invalid affine point");if(p instanceof h)throw new Error("projective point not allowed");const E=C=>r.eql(C,r.ZERO);return E(b)&&E(m)?h.ZERO:new h(b,m,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){const b=r.invertBatch(p.map(m=>m.pz));return p.map((m,E)=>m.toAffine(b[E])).map(h.fromAffine)}static fromHex(p){const b=h.fromAffine(s(mn("pointHex",p)));return b.assertValidity(),b}static fromPrivateKey(p){return h.BASE.multiply(c(p))}static msm(p,b){return GK(h,n,p,b)}_setWindowSize(p){g.setWindowSize(this,p)}assertValidity(){d(this)}hasEvenY(){const{y:p}=this.toAffine();if(r.isOdd)return!r.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){l(p);const{px:b,py:m,pz:E}=this,{px:C,py:P,pz:S}=p,I=r.eql(r.mul(b,S),r.mul(C,E)),N=r.eql(r.mul(m,S),r.mul(P,E));return I&&N}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:p,b}=e,m=r.mul(b,GE),{px:E,py:C,pz:P}=this;let S=r.ZERO,I=r.ZERO,N=r.ZERO,$=r.mul(E,E),D=r.mul(C,C),T=r.mul(P,P),R=r.mul(E,C);return R=r.add(R,R),N=r.mul(E,P),N=r.add(N,N),S=r.mul(p,N),I=r.mul(m,T),I=r.add(S,I),S=r.sub(D,I),I=r.add(D,I),I=r.mul(S,I),S=r.mul(R,S),N=r.mul(m,N),T=r.mul(p,T),R=r.sub($,T),R=r.mul(p,R),R=r.add(R,N),N=r.add($,$),$=r.add(N,$),$=r.add($,T),$=r.mul($,R),I=r.add(I,$),T=r.mul(C,P),T=r.add(T,T),$=r.mul(T,R),S=r.sub(S,$),N=r.mul(T,D),N=r.add(N,N),N=r.add(N,N),new h(S,I,N)}add(p){l(p);const{px:b,py:m,pz:E}=this,{px:C,py:P,pz:S}=p;let I=r.ZERO,N=r.ZERO,$=r.ZERO;const D=e.a,T=r.mul(e.b,GE);let R=r.mul(b,C),M=r.mul(m,P),x=r.mul(E,S),y=r.add(b,m),v=r.add(C,P);y=r.mul(y,v),v=r.add(R,M),y=r.sub(y,v),v=r.add(b,E);let A=r.add(C,S);return v=r.mul(v,A),A=r.add(R,x),v=r.sub(v,A),A=r.add(m,E),I=r.add(P,S),A=r.mul(A,I),I=r.add(M,x),A=r.sub(A,I),$=r.mul(D,v),I=r.mul(T,x),$=r.add(I,$),I=r.sub(M,$),$=r.add(M,$),N=r.mul(I,$),M=r.add(R,R),M=r.add(M,R),x=r.mul(D,x),v=r.mul(T,v),M=r.add(M,x),x=r.sub(R,x),x=r.mul(D,x),v=r.add(v,x),R=r.mul(M,v),N=r.add(N,R),R=r.mul(A,v),I=r.mul(y,I),I=r.sub(I,R),R=r.mul(y,M),$=r.mul(A,$),$=r.add($,R),new h(I,N,$)}subtract(p){return this.add(p.negate())}is0(){return this.equals(h.ZERO)}wNAF(p){return g.wNAFCached(this,p,h.normalizeZ)}multiplyUnsafe(p){const{endo:b,n:m}=e;cs("scalar",p,us,m);const E=h.ZERO;if(p===us)return E;if(this.is0()||p===er)return this;if(!b||g.hasPrecomputes(this))return g.wNAFCachedUnsafe(this,p,h.normalizeZ);let{k1neg:C,k1:P,k2neg:S,k2:I}=b.splitScalar(p),N=E,$=E,D=this;for(;P>us||I>us;)P&er&&(N=N.add(D)),I&er&&($=$.add(D)),D=D.double(),P>>=er,I>>=er;return C&&(N=N.negate()),S&&($=$.negate()),$=new h(r.mul($.px,b.beta),$.py,$.pz),N.add($)}multiply(p){const{endo:b,n:m}=e;cs("scalar",p,er,m);let E,C;if(b){const{k1neg:P,k1:S,k2neg:I,k2:N}=b.splitScalar(p);let{p:$,f:D}=this.wNAF(S),{p:T,f:R}=this.wNAF(N);$=g.constTimeNegate(P,$),T=g.constTimeNegate(I,T),T=new h(r.mul(T.px,b.beta),T.py,T.pz),E=$.add(T),C=D.add(R)}else{const{p:P,f:S}=this.wNAF(p);E=P,C=S}return h.normalizeZ([E,C])[0]}multiplyAndAddUnsafe(p,b,m){const E=h.BASE,C=(S,I)=>I===us||I===er||!S.equals(E)?S.multiplyUnsafe(I):S.multiply(I),P=C(this,b).add(C(p,m));return P.is0()?void 0:P}toAffine(p){return u(this,p)}isTorsionFree(){const{h:p,isTorsionFree:b}=e;if(p===er)return!0;if(b)return b(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:p,clearCofactor:b}=e;return p===er?this:b?b(h,this):this.multiplyUnsafe(e.h)}toRawBytes(p=!0){return Lc("isCompressed",p),this.assertValidity(),i(h,this,p)}toHex(p=!0){return Lc("isCompressed",p),Fc(this.toRawBytes(p))}}h.BASE=new h(e.Gx,e.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const f=e.nBitLength,g=KK(h,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function aG(t){const e=WE(t);return qc(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function cG(t){const e=aG(t),{Fp:r,n}=e,i=r.BYTES+1,s=2*r.BYTES+1;function o(x){return Gr(x,n)}function a(x){return Cm(x,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=oG({...e,toBytes(x,y,v){const A=y.toAffine(),O=r.toBytes(A.x),_=ed;return Lc("isCompressed",v),v?_(Uint8Array.from([y.hasEvenY()?2:3]),O):_(Uint8Array.from([4]),O,r.toBytes(A.y))},fromBytes(x){const y=x.length,v=x[0],A=x.subarray(1);if(y===i&&(v===2||v===3)){const O=ta(A);if(!gf(O,er,r.ORDER))throw new Error("Point is not on curve");const _=u(O);let k;try{k=r.sqrt(_)}catch(F){const H=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+H)}const L=(k&er)===er;return(v&1)===1!==L&&(k=r.neg(k)),{x:O,y:k}}else if(y===s&&v===4){const O=r.fromBytes(A.subarray(0,r.BYTES)),_=r.fromBytes(A.subarray(r.BYTES,2*r.BYTES));return{x:O,y:_}}else{const O=i,_=s;throw new Error("invalid Point, expected length of "+O+", or uncompressed "+_+", got "+y)}}}),h=x=>Fc(zc(x,e.nByteLength));function f(x){const y=n>>er;return x>y}function g(x){return f(x)?o(-x):x}const w=(x,y,v)=>ta(x.slice(y,v));class p{constructor(y,v,A){this.r=y,this.s=v,this.recovery=A,this.assertValidity()}static fromCompact(y){const v=e.nByteLength;return y=mn("compactSignature",y,v*2),new p(w(y,0,v),w(y,v,2*v))}static fromDER(y){const{r:v,s:A}=ls.toSig(mn("DER",y));return new p(v,A)}assertValidity(){cs("r",this.r,er,n),cs("s",this.s,er,n)}addRecoveryBit(y){return new p(this.r,this.s,y)}recoverPublicKey(y){const{r:v,s:A,recovery:O}=this,_=S(mn("msgHash",y));if(O==null||![0,1,2,3].includes(O))throw new Error("recovery id invalid");const k=O===2||O===3?v+e.n:v;if(k>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(O&1)===0?"02":"03",F=c.fromHex(L+h(k)),H=a(k),q=o(-_*H),W=o(A*H),Y=c.BASE.multiplyAndAddUnsafe(F,q,W);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return jc(this.toDERHex())}toDERHex(){return ls.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return jc(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const b={isValidPrivateKey(x){try{return l(x),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const x=jE(e.n);return HK(e.randomBytes(x),e.n)},precompute(x=8,y=c.BASE){return y._setWindowSize(x),y.multiply(BigInt(3)),y}};function m(x,y=!0){return c.fromPrivateKey(x).toRawBytes(y)}function E(x){const y=ea(x),v=typeof x=="string",A=(y||v)&&x.length;return y?A===i||A===s:v?A===2*i||A===2*s:x instanceof c}function C(x,y,v=!0){if(E(x))throw new Error("first arg must be private key");if(!E(y))throw new Error("second arg must be public key");return c.fromHex(y).multiply(l(x)).toRawBytes(v)}const P=e.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");const y=ta(x),v=x.length*8-e.nBitLength;return v>0?y>>BigInt(v):y},S=e.bits2int_modN||function(x){return o(P(x))},I=bm(e.nBitLength);function N(x){return cs("num < 2^"+e.nBitLength,x,us,I),zc(x,e.nByteLength)}function $(x,y,v=D){if(["recovered","canonical"].some(re=>re in v))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:O}=e;let{lowS:_,prehash:k,extraEntropy:L}=v;_==null&&(_=!0),x=mn("msgHash",x),KE(v),k&&(x=mn("prehashed msgHash",A(x)));const F=S(x),H=l(y),q=[N(H),N(F)];if(L!=null&&L!==!1){const re=L===!0?O(r.BYTES):L;q.push(mn("extraEntropy",re))}const W=ed(...q),Y=F;function ae(re){const te=P(re);if(!d(te))return;const Ee=a(te),Ce=c.BASE.multiply(te).toAffine(),xe=o(Ce.x);if(xe===us)return;const _e=o(Ee*o(Y+xe*H));if(_e===us)return;let Ge=(Ce.x===xe?0:2)|Number(Ce.y&er),xr=_e;return _&&f(_e)&&(xr=g(_e),Ge^=1),new p(xe,xr,Ge)}return{seed:W,k2sig:ae}}const D={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function R(x,y,v=D){const{seed:A,k2sig:O}=$(x,y,v),_=e;return RE(_.hash.outputLen,_.nByteLength,_.hmac)(A,O)}c.BASE._setWindowSize(8);function M(x,y,v,A=T){const O=x;y=mn("msgHash",y),v=mn("publicKey",v);const{lowS:_,prehash:k,format:L}=A;if(KE(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const F=typeof O=="string"||ea(O),H=!F&&!L&&typeof O=="object"&&O!==null&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!F&&!H)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,W;try{if(H&&(q=new p(O.r,O.s)),F){try{L!=="compact"&&(q=p.fromDER(O))}catch(_e){if(!(_e instanceof ls.Err))throw _e}!q&&L!=="der"&&(q=p.fromCompact(O))}W=c.fromHex(v)}catch{return!1}if(!q||_&&q.hasHighS())return!1;k&&(y=e.hash(y));const{r:Y,s:ae}=q,re=S(y),te=a(ae),Ee=o(re*te),Ce=o(Y*te),xe=c.BASE.multiplyAndAddUnsafe(W,Ee,Ce)?.toAffine();return xe?o(xe.x)===Y:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:C,sign:R,verify:M,ProjectivePoint:c,Signature:p,utils:b}}function lG(t){return{hash:t,hmac:(e,...r)=>OE(t,e,HV(...r)),randomBytes:pE}}function uG(t,e){const r=n=>cG({...t,...lG(n)});return{...r(e),create:r}}const ZE=FE(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),dG=ZE.create(BigInt("-3")),hG=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");uG({a:dG,b:hG,Fp:ZE,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},IK);function pG(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,p=0,b=0,m=g.length;b!==m&&g[b]===0;)b++,w++;for(var E=(m-b)*u+1>>>0,C=new Uint8Array(E);b!==m;){for(var P=g[b],S=0,I=E-1;(P!==0||S<p)&&I!==-1;I--,S++)P+=256*C[I]>>>0,C[I]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");p=S,b++}for(var N=E-p;N!==E&&C[N]===0;)N++;for(var $=c.repeat(w);N<E;++N)$+=t.charAt(C[N]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var p=0,b=0;g[w]===c;)p++,w++;for(var m=(g.length-w)*l+1>>>0,E=new Uint8Array(m);g[w];){var C=r[g.charCodeAt(w)];if(C===255)return;for(var P=0,S=m-1;(C!==0||P<b)&&S!==-1;S--,P++)C+=a*E[S]>>>0,E[S]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");b=P,w++}if(g[w]!==" "){for(var I=m-b;I!==m&&E[I]===0;)I++;for(var N=new Uint8Array(p+(m-I)),$=p;I!==m;)N[$++]=E[I++];return N}}}function f(g){var w=h(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var fG=pG,gG=fG;const YE=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},wG=t=>new TextEncoder().encode(t),mG=t=>new TextDecoder().decode(t);class bG{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class yG{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return JE(this,e)}}class vG{constructor(e){this.decoders=e}or(e){return JE(this,e)}decode(e){const r=e[0],n=this.decoders[r];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 JE=(t,e)=>new vG({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class EG{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new bG(e,r,n),this.decoder=new yG(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const mf=({name:t,prefix:e,encode:r,decode:n})=>new EG(t,e,r,n),td=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=gG(r,e);return mf({prefix:t,name:e,encode:n,decode:s=>YE(i(s))})},CG=(t,e,r,n)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},xG=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},gr=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>mf({prefix:e,name:t,encode(i){return xG(i,n,r)},decode(i){return CG(i,n,r,t)}}),$G=mf({prefix:"\0",name:"identity",encode:t=>mG(t),decode:t=>wG(t)});var _G=Object.freeze({__proto__:null,identity:$G});const IG=gr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var SG=Object.freeze({__proto__:null,base2:IG});const AG=gr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var PG=Object.freeze({__proto__:null,base8:AG});const OG=td({prefix:"9",name:"base10",alphabet:"0123456789"});var NG=Object.freeze({__proto__:null,base10:OG});const TG=gr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kG=gr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var RG=Object.freeze({__proto__:null,base16:TG,base16upper:kG});const DG=gr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),BG=gr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),UG=gr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LG=gr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),FG=gr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),MG=gr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jG=gr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zG=gr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qG=gr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var HG=Object.freeze({__proto__:null,base32:DG,base32upper:BG,base32pad:UG,base32padupper:LG,base32hex:FG,base32hexupper:MG,base32hexpad:jG,base32hexpadupper:zG,base32z:qG});const WG=td({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),VG=td({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var KG=Object.freeze({__proto__:null,base36:WG,base36upper:VG});const GG=td({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ZG=td({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var YG=Object.freeze({__proto__:null,base58btc:GG,base58flickr:ZG});const JG=gr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XG=gr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QG=gr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eZ=gr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tZ=Object.freeze({__proto__:null,base64:JG,base64pad:XG,base64url:QG,base64urlpad:eZ});const XE=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),rZ=XE.reduce((t,e,r)=>(t[r]=e,t),[]),nZ=XE.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function iZ(t){return t.reduce((e,r)=>(e+=rZ[r],e),"")}function sZ(t){const e=[];for(const r of t){const n=nZ[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const oZ=mf({prefix:"\u{1F680}",name:"base256emoji",encode:iZ,decode:sZ});var aZ=Object.freeze({__proto__:null,base256emoji:oZ}),cZ=eC,QE=128,lZ=127,uZ=~lZ,dZ=Math.pow(2,31);function eC(t,e,r){e=e||[],r=r||0;for(var n=r;t>=dZ;)e[r++]=t&255|QE,t/=128;for(;t&uZ;)e[r++]=t&255|QE,t>>>=7;return e[r]=t|0,eC.bytes=r-n+1,e}var hZ=Pm,pZ=128,tC=127;function Pm(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Pm.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&tC)<<i:(o&tC)*Math.pow(2,i),i+=7}while(o>=pZ);return Pm.bytes=s-n,r}var fZ=Math.pow(2,7),gZ=Math.pow(2,14),wZ=Math.pow(2,21),mZ=Math.pow(2,28),bZ=Math.pow(2,35),yZ=Math.pow(2,42),vZ=Math.pow(2,49),EZ=Math.pow(2,56),CZ=Math.pow(2,63),xZ=function(t){return t<fZ?1:t<gZ?2:t<wZ?3:t<mZ?4:t<bZ?5:t<yZ?6:t<vZ?7:t<EZ?8:t<CZ?9:10},$Z={encode:cZ,decode:hZ,encodingLength:xZ},rC=$Z;const nC=(t,e,r=0)=>(rC.encode(t,e,r),e),iC=t=>rC.encodingLength(t),Om=(t,e)=>{const r=e.byteLength,n=iC(t),i=n+iC(r),s=new Uint8Array(i+r);return nC(t,s,0),nC(r,s,n),s.set(e,i),new _Z(t,r,e,s)};class _Z{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const sC=({name:t,code:e,encode:r})=>new IZ(t,e,r);class IZ{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Om(this.code,r):r.then(n=>Om(this.code,n))}else throw Error("Unknown type, must be binary type")}}const oC=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),SZ=sC({name:"sha2-256",code:18,encode:oC("SHA-256")}),AZ=sC({name:"sha2-512",code:19,encode:oC("SHA-512")});var PZ=Object.freeze({__proto__:null,sha256:SZ,sha512:AZ});const aC=0,OZ="identity",cC=YE;var NZ=Object.freeze({__proto__:null,identity:{code:aC,name:OZ,encode:cC,digest:t=>Om(aC,cC(t))}});new TextEncoder,new TextDecoder,{..._G,...SG,...PG,...NG,...RG,...HG,...KG,...YG,...tZ,...aZ},{...PZ,...NZ};const TZ="https://secure.walletconnect.org/sdk";typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const io={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},na=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Ft=at({...na}),ct={state:Ft,subscribeKey(t,e){return Rr(Ft,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=X.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){Ft.message=na.message,Ft.variant=na.variant,Ft.svg=na.svg,Ft.open=na.open,Ft.autoClose=na.autoClose},_showMessage({message:t,svg:e,variant:r="success",autoClose:n=na.autoClose}){Ft.open?(Ft.open=!1,setTimeout(()=>{Ft.message=t,Ft.variant=r,Ft.svg=e,Ft.open=!0,Ft.autoClose=n},150)):(Ft.message=t,Ft.variant=r,Ft.svg=e,Ft.open=!0,Ft.autoClose=n)}},so={getSIWX(){return G.state.siwx},async initializeIfEnabled(){const t=G.state.siwx,e=B.getActiveCaipAddress();if(!(t&&e))return;const[r,n,i]=e.split(":");if(B.checkIfSupportedNetwork(r))try{if((await t.getSessions(`${r}:${n}`,i)).length)return;await De.open({view:"SIWXSignMessage"})}catch(s){console.error("SIWXUtil:initializeIfEnabled",s),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await pe._getClient()?.disconnect().catch(console.error),ne.reset("Connect"),ct.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=G.state.siwx,e=X.getPlainAddress(B.getActiveCaipAddress()),r=B.getActiveCaipNetwork(),n=pe._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!r)throw new Error("No ActiveCaipNetwork or client found");if(!n)throw new Error("No ConnectionController client found");try{const i=await t.createMessage({chainId:r.caipNetworkId,accountAddress:e}),s=i.toString();oe.getConnectorId(r.chainNamespace)===de.CONNECTOR_ID.AUTH&&ne.pushTransactionStack({view:null,goBack:!1,replace:!0});const a=await n.signMessage(s);await t.addSession({data:i,message:s,signature:a}),De.close(),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){const s=this.getSIWXEventProperties();(!De.state.open||ne.state.view==="ApproveTransaction")&&await De.open({view:"SIWXSignMessage"}),s.isSmartAccount?ct.showError("This application might not support Smart Accounts"):ct.showError("Signature declined"),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:s}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){try{this.getSIWX()?.getRequired?.()?await pe.disconnect():De.close(),ne.reset("Connect"),Ae.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getSessions(){const t=G.state.siwx,e=X.getPlainAddress(B.getActiveCaipAddress()),r=B.getActiveCaipNetwork();return t&&e&&r?t.getSessions(r.caipNetworkId,e):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=ne.state.view==="ApproveTransaction",r=ne.state.view==="SIWXSignMessage";if(e||r)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:r}){const n=so.getSIWX(),i=new Set(e.map(a=>a.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const s=await n.createMessage({chainId:B.getActiveCaipNetwork()?.caipNetworkId||"",accountAddress:""}),o=await t.authenticate({nonce:s.nonce,domain:s.domain,uri:s.uri,exp:s.expirationTime,iat:s.issuedAt,nbf:s.notBefore,requestId:s.requestId,version:s.version,resources:s.resources,statement:s.statement,chainId:s.chainId,methods:r,chains:[s.chainId,...e.filter(a=>a!==s.chainId)]});if(ct.showLoading("Authenticating...",{autoClose:!1}),ge.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(i)[0]),o?.auths?.length){const a=o.auths.map(c=>{const l=t.client.formatAuthMessage({request:c.p,iss:c.p.iss});return{data:{...c.p,accountAddress:c.p.iss.split(":").slice(-1).join(""),chainId:c.p.iss.split(":").slice(2,4).join(":"),uri:c.p.aud,version:c.p.version||s.version,expirationTime:c.p.exp,issuedAt:c.p.iat,notBefore:c.p.nbf},message:l,signature:c.s.s,cacao:c}});try{await n.setSessions(a),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:so.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:so.getSIWXEventProperties()}),await t.disconnect().catch(console.error),c}finally{ct.hide()}}return!0},getSIWXEventProperties(){const t=B.state.activeChain;return{network:B.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:ge.state.preferredAccountTypes?.[t]===io.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}},pt=at({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),kZ={state:pt,subscribe(t){return Ir(pt,()=>t(pt))},setLastNetworkInView(t){pt.lastNetworkInView=t},async fetchTransactions(t,e){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");pt.loading=!0;try{const r=await ve.fetchTransactions({account:t,cursor:pt.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:B.state.activeCaipNetwork?.caipNetworkId}),n=this.filterSpamTransactions(r.data),i=this.filterByConnectedChain(n),s=[...pt.transactions,...i];pt.loading=!1,e==="coinbase"?pt.coinbaseTransactions=this.groupTransactionsByYearAndMonth(pt.coinbaseTransactions,r.data):(pt.transactions=s,pt.transactionsByYear=this.groupTransactionsByYearAndMonth(pt.transactionsByYear,i)),pt.empty=s.length===0,pt.next=r.next?r.next:void 0}catch{const n=B.state.activeChain;Ae.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:G.state.projectId,cursor:pt.next,isSmartAccount:ge.state.preferredAccountTypes?.[n]===io.ACCOUNT_TYPES.SMART_ACCOUNT}}),ct.showError("Failed to fetch transactions"),pt.loading=!1,pt.empty=!0,pt.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const r=t;return e.forEach(n=>{const i=new Date(n.metadata.minedAt).getFullYear(),s=new Date(n.metadata.minedAt).getMonth(),o=r[i]??{},c=(o[s]??[]).filter(l=>l.id!==n.id);r[i]={...o,[s]:[...c,n].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),r},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=B.state.activeCaipNetwork?.caipNetworkId;return t.filter(n=>n.metadata.chain===e)},clearCursor(){pt.next=void 0},resetTransactions(){pt.transactions=[],pt.transactionsByYear={},pt.lastNetworkInView=void 0,pt.loading=!1,pt.empty=!1,pt.next=void 0}},yt=at({wcError:!1,buffering:!1,status:"disconnected"});let Wc;const pe={state:yt,subscribeKey(t,e){return Rr(yt,t,e)},_getClient(){return yt._client},setClient(t){yt._client=Qo(t)},async connectWalletConnect(){if(X.isTelegram()||X.isSafari()&&X.isIos()){if(Wc){await Wc,Wc=void 0;return}if(!X.isPairingExpired(yt?.wcPairingExpiry)){const t=yt.wcUri;yt.wcUri=t;return}Wc=this._getClient()?.connectWalletConnect?.().catch(()=>{}),this.state.status="connecting",await Wc,Wc=void 0,yt.wcPairingExpiry=void 0,this.state.status="connected"}else await this._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,r=!0){await this._getClient()?.connectExternal?.(t),r&&B.setActiveNamespace(e)},async reconnectExternal(t){await this._getClient()?.reconnectExternal?.(t);const e=t.chain||B.state.activeChain;e&&oe.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){De.setLoading(!0,B.state.activeChain);const r=oe.getAuthConnector();r&&(ge.setPreferredAccountType(t,e),await r.provider.setPreferredAccount(t),he.setPreferredAccountTypes(ge.state.preferredAccountTypes??{[e]:t}),await this.reconnectExternal(r),De.setLoading(!1,B.state.activeChain),Ae.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:B.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return this._getClient()?.signMessage(t)},parseUnits(t,e){return this._getClient()?.parseUnits(t,e)},formatUnits(t,e){return this._getClient()?.formatUnits(t,e)},async sendTransaction(t){return this._getClient()?.sendTransaction(t)},async getCapabilities(t){return this._getClient()?.getCapabilities(t)},async grantPermissions(t){return this._getClient()?.grantPermissions(t)},async walletGetAssets(t){return this._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return this._getClient()?.estimateGas(t)},async writeContract(t){return this._getClient()?.writeContract(t)},async getEnsAddress(t){return this._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return this._getClient()?.getEnsAvatar(t)},checkInstalled(t){return this._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){yt.wcUri=void 0,yt.wcPairingExpiry=void 0,yt.wcLinking=void 0,yt.recentWallet=void 0,yt.status="disconnected",kZ.resetTransactions(),he.deleteWalletConnectDeepLink()},resetUri(){yt.wcUri=void 0,yt.wcPairingExpiry=void 0},finalizeWcConnection(){const{wcLinking:t,recentWallet:e}=pe.state;t&&he.setWalletConnectDeepLink(t),e&&he.setAppKitRecent(e),Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:ne.state.data?.wallet?.name||"Unknown"}})},setWcBasic(t){yt.wcBasic=t},setUri(t){yt.wcUri=t,yt.wcPairingExpiry=X.getPairingExpiry()},setWcLinking(t){yt.wcLinking=t},setWcError(t){yt.wcError=t,yt.buffering=!1},setRecentWallet(t){yt.recentWallet=t},setBuffering(t){yt.buffering=t},setStatus(t){yt.status=t},async disconnect(t){try{De.setLoading(!0,t),await so.clearSessions(),await B.disconnect(t),De.setLoading(!1,t),oe.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},Vc=at({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),ds={state:Vc,subscribe(t){return Ir(Vc,()=>t(Vc))},subscribeOpen(t){return Rr(Vc,"open",t)},set(t){Object.assign(Vc,{...Vc,...t})}};function rd(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function oo(t){return rd(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const lC="2.27.0";let Nm={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${lC}`};class Ne extends Error{constructor(e,r={}){const n=r.cause instanceof Ne?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof Ne&&r.cause.docsPath||r.docsPath,s=Nm.getDocsUrl?.({...r,docsPath:i}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Nm.version?[`Version: ${Nm.version}`]:[]].join(`