@walletconnect/ethereum-provider 2.19.2-rc-0 → 2.19.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(R4(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 eu=function(t,e){return eu=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])},eu(t,e)};function J6(t,e){eu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var tu=function(){return tu=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},tu.apply(this,arguments)};function Q6(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 X6(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 eI(t,e){return function(r,n){e(r,n,t)}}function tI(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function rI(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(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function nI(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 iI(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function sI(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ru(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 F0(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 oI(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F0(arguments[e]));return t}function aI(){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 ks(t){return this instanceof ks?(this.v=t,this):new ks(t)}function cI(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(d){n[d]&&(i[d]=function(p){return new Promise(function(f,g){s.push([d,p,f,g])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof ks?Promise.resolve(d.value.v).then(l,u):h(s[0][2],d)}function l(d){a("next",d)}function u(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function lI(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:ks(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function uI(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 ru=="function"?ru(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 hI(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function dI(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 fI(t){return t&&t.__esModule?t:{default:t}}function pI(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function gI(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 mI=Object.freeze({__proto__:null,__extends:J6,get __assign(){return tu},__rest:Q6,__decorate:X6,__param:eI,__metadata:tI,__awaiter:rI,__generator:nI,__createBinding:iI,__exportStar:sI,__values:ru,__read:F0,__spread:oI,__spreadArrays:aI,__await:ks,__asyncGenerator:cI,__asyncDelegator:lI,__asyncValues:uI,__makeTemplateObject:hI,__importStar:dI,__importDefault:fI,__classPrivateFieldGet:pI,__classPrivateFieldSet:gI}),wI=Gh(mI),xr={},k0;function yI(){if(k0)return xr;k0=1,Object.defineProperty(xr,"__esModule",{value:!0}),xr.isBrowserCryptoAvailable=xr.getSubtleCrypto=xr.getBrowerCrypto=void 0;function t(){return ct?.crypto||ct?.msCrypto||{}}xr.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}xr.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return xr.isBrowserCryptoAvailable=r,xr}var Ir={},q0;function bI(){if(q0)return Ir;q0=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.isBrowser=Ir.isNode=Ir.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ir.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ir.isNode=e;function r(){return!t()&&!e()}return Ir.isBrowser=r,Ir}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=wI;e.__exportStar(yI(),t),e.__exportStar(bI(),t)})(j0);function tr(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function xn(t=6){return BigInt(tr(t))}function Kr(t,e,r){return{id:r||tr(),jsonrpc:"2.0",method:t,params:e}}function fa(t,e){return{id:t,jsonrpc:"2.0",result:e}}function pa(t,e,r){return{id:t,jsonrpc:"2.0",error:vI(e,r)}}function vI(t,e){return typeof t>"u"?M0(B0):(typeof t=="string"&&(t=Object.assign(Object.assign({},M0(Xl)),{message:t})),typeof e<"u"&&(t.data=e),Z6(t.code)&&(t=Y6(t.code)),t)}class EI{}class _I extends EI{constructor(){super()}}class $I extends _I{constructor(e){super()}}const xI="^https?:",II="^wss?:";function OI(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function z0(t,e){const r=OI(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function H0(t){return z0(t,xI)}function V0(t){return z0(t,II)}function SI(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function W0(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function nu(t){return W0(t)&&"method"in t}function ga(t){return W0(t)&&(rr(t)||Pt(t))}function rr(t){return"result"in t}function Pt(t){return"error"in t}class Dt extends $I{constructor(e){super(e),this.events=new Ve.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(Kr(e.method,e.params||[],e.id||xn().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=>{Pt(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),ga(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 AI=()=>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"),CI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",K0=t=>t.split("?")[0],G0=10,PI=AI();class DI{constructor(e){if(this.url=e,this.events=new Ve.exports.EventEmitter,this.registering=!1,!V0(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(gr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!V0(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=j0.isReactNative()?void 0:{rejectUnauthorized:!SI(e)},s=new PI(e,[],i);CI()?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"?fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=pa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return U0(e,K0(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>G0&&this.events.setMaxListeners(G0)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${K0(this.url)}`));return this.events.emit("register_error",r),r}}var TI=Object.defineProperty,Z0=Object.getOwnPropertySymbols,RI=Object.prototype.hasOwnProperty,NI=Object.prototype.propertyIsEnumerable,Y0=(t,e,r)=>e in t?TI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,st=(t,e)=>{for(var r in e||(e={}))RI.call(e,r)&&Y0(t,r,e[r]);if(Z0)for(var r of Z0(e))NI.call(e,r)&&Y0(t,r,e[r]);return t};const J0="wc",Q0=2,ma="core",nr=`${J0}@2:${ma}:`,BI={name:ma,logger:"error"},LI={database:":memory:"},MI="crypto",X0="client_ed25519_seed",UI=j.ONE_DAY,jI="keychain",FI="0.3",kI="messages",qI="0.3",em=j.SIX_HOURS,zI="publisher",tm="irn",HI="error",rm="wss://relay.walletconnect.org",VI="relayer",Fe={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"},WI="_subscription",Tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},KI=.1,iu="2.19.2-rc-0",ye={link_mode:"link_mode",relay:"relay"},wa={inbound:"inbound",outbound:"outbound"},GI="0.3",ZI="WALLETCONNECT_CLIENT_ID",nm="WALLETCONNECT_LINK_MODE_APPS",_t={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},YI="subscription",JI="0.3",QI="pairing",XI="0.3",qs={wc_pairingDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:j.ONE_DAY,prompt:!1,tag:0},res:{ttl:j.ONE_DAY,prompt:!1,tag:0}}},In={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},zt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},eO="history",tO="0.3",rO="expirer",Rt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},nO="0.3",iO="verify-api",sO="https://verify.walletconnect.com",im="https://verify.walletconnect.org",zs=im,oO=`${zs}/v3`,aO=[sO,im],cO="echo",lO="https://echo.walletconnect.com",ir={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"},Or={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"},Ht={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"},On={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"},Sn={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"},Hs={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"},uO=.1,hO="event-client",dO=86400,fO="https://pulse.walletconnect.org/batch";function pO(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 h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,m=0,w=0,y=f.length;w!==y&&f[w]===0;)w++,g++;for(var E=(y-w)*u+1>>>0,_=new Uint8Array(E);w!==y;){for(var O=f[w],S=0,x=E-1;(O!==0||S<m)&&x!==-1;x--,S++)O+=256*_[x]>>>0,_[x]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");m=S,w++}for(var P=E-m;P!==E&&_[P]===0;)P++;for(var $=c.repeat(g);P<E;++P)$+=t.charAt(_[P]);return $}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var m=0,w=0;f[g]===c;)m++,g++;for(var y=(f.length-g)*l+1>>>0,E=new Uint8Array(y);f[g];){var _=r[f.charCodeAt(g)];if(_===255)return;for(var O=0,S=y-1;(_!==0||O<w)&&S!==-1;S--,O++)_+=a*E[S]>>>0,E[S]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=O,g++}if(f[g]!==" "){for(var x=y-w;x!==y&&E[x]===0;)x++;for(var P=new Uint8Array(m+(y-x)),$=m;x!==y;)P[$++]=E[x++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var gO=pO,mO=gO;const sm=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")},wO=t=>new TextEncoder().encode(t),yO=t=>new TextDecoder().decode(t);class bO{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 vO{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 om(this,e)}}class EO{constructor(e){this.decoders=e}or(e){return om(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 om=(t,e)=>new EO(st(st({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class _O{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new bO(e,r,n),this.decoder=new vO(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ya=({name:t,prefix:e,encode:r,decode:n})=>new _O(t,e,r,n),Vs=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=mO(r,e);return ya({prefix:t,name:e,encode:n,decode:s=>sm(i(s))})},$O=(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 h=i[t[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},xO=(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},Ye=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ya({prefix:e,name:t,encode(i){return xO(i,n,r)},decode(i){return $O(i,n,r,t)}}),IO=ya({prefix:"\0",name:"identity",encode:t=>yO(t),decode:t=>wO(t)});var OO=Object.freeze({__proto__:null,identity:IO});const SO=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var AO=Object.freeze({__proto__:null,base2:SO});const CO=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var PO=Object.freeze({__proto__:null,base8:CO});const DO=Vs({prefix:"9",name:"base10",alphabet:"0123456789"});var TO=Object.freeze({__proto__:null,base10:DO});const RO=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),NO=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var BO=Object.freeze({__proto__:null,base16:RO,base16upper:NO});const LO=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),MO=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),UO=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jO=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),FO=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kO=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qO=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zO=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),HO=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var VO=Object.freeze({__proto__:null,base32:LO,base32upper:MO,base32pad:UO,base32padupper:jO,base32hex:FO,base32hexupper:kO,base32hexpad:qO,base32hexpadupper:zO,base32z:HO});const WO=Vs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),KO=Vs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var GO=Object.freeze({__proto__:null,base36:WO,base36upper:KO});const ZO=Vs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YO=Vs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var JO=Object.freeze({__proto__:null,base58btc:ZO,base58flickr:YO});const QO=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XO=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),eS=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tS=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rS=Object.freeze({__proto__:null,base64:QO,base64pad:XO,base64url:eS,base64urlpad:tS});const am=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}"),nS=am.reduce((t,e,r)=>(t[r]=e,t),[]),iS=am.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function sS(t){return t.reduce((e,r)=>(e+=nS[r],e),"")}function oS(t){const e=[];for(const r of t){const n=iS[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const aS=ya({prefix:"\u{1F680}",name:"base256emoji",encode:sS,decode:oS});var cS=Object.freeze({__proto__:null,base256emoji:aS}),lS=lm,cm=128,uS=127,hS=~uS,dS=Math.pow(2,31);function lm(t,e,r){e=e||[],r=r||0;for(var n=r;t>=dS;)e[r++]=t&255|cm,t/=128;for(;t&hS;)e[r++]=t&255|cm,t>>>=7;return e[r]=t|0,lm.bytes=r-n+1,e}var fS=su,pS=128,um=127;function su(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw su.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&um)<<i:(o&um)*Math.pow(2,i),i+=7}while(o>=pS);return su.bytes=s-n,r}var gS=Math.pow(2,7),mS=Math.pow(2,14),wS=Math.pow(2,21),yS=Math.pow(2,28),bS=Math.pow(2,35),vS=Math.pow(2,42),ES=Math.pow(2,49),_S=Math.pow(2,56),$S=Math.pow(2,63),xS=function(t){return t<gS?1:t<mS?2:t<wS?3:t<yS?4:t<bS?5:t<vS?6:t<ES?7:t<_S?8:t<$S?9:10},IS={encode:lS,decode:fS,encodingLength:xS},hm=IS;const dm=(t,e,r=0)=>(hm.encode(t,e,r),e),fm=t=>hm.encodingLength(t),ou=(t,e)=>{const r=e.byteLength,n=fm(t),i=n+fm(r),s=new Uint8Array(i+r);return dm(t,s,0),dm(r,s,n),s.set(e,i),new OS(t,r,e,s)};class OS{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const pm=({name:t,code:e,encode:r})=>new SS(t,e,r);class SS{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?ou(this.code,r):r.then(n=>ou(this.code,n))}else throw Error("Unknown type, must be binary type")}}const gm=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),AS=pm({name:"sha2-256",code:18,encode:gm("SHA-256")}),CS=pm({name:"sha2-512",code:19,encode:gm("SHA-512")});var PS=Object.freeze({__proto__:null,sha256:AS,sha512:CS});const mm=0,DS="identity",wm=sm;var TS=Object.freeze({__proto__:null,identity:{code:mm,name:DS,encode:wm,digest:t=>ou(mm,wm(t))}});new TextEncoder,new TextDecoder;const ym=st(st(st(st(st(st(st(st(st(st({},OO),AO),PO),TO),BO),VO),GO),JO),rS),cS);st(st({},PS),TS);function RS(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function bm(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const vm=bm("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),au=bm("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=RS(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),NS=st({utf8:vm,"utf-8":vm,hex:ym.base16,latin1:au,ascii:au,binary:au},ym);function BS(t,e="utf8"){const r=NS[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 LS=Object.defineProperty,MS=(t,e,r)=>e in t?LS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sr=(t,e,r)=>MS(t,typeof e!="symbol"?e+"":e,r);class US{constructor(e,r){this.core=e,this.logger=r,sr(this,"keychain",new Map),sr(this,"name",jI),sr(this,"version",FI),sr(this,"initialized",!1),sr(this,"storagePrefix",nr),sr(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),sr(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),sr(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),sr(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=F("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),sr(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=it(r,this.name)}get context(){return pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,dl(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?fl(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jS=Object.defineProperty,FS=(t,e,r)=>e in t?jS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Je=(t,e,r)=>FS(t,typeof e!="symbol"?e+"":e,r);class kS{constructor(e,r,n){this.core=e,this.logger=r,Je(this,"name",MI),Je(this,"keychain"),Je(this,"randomSessionIdentifier",kl()),Je(this,"initialized",!1),Je(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Je(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Je(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=xp(i);return $p(s.publicKey)}),Je(this,"generateKeyPair",()=>{this.isInitialized();const i=$$();return this.setPrivateKey(i.publicKey,i.privateKey)}),Je(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=xp(s),a=this.randomSessionIdentifier;return await g_(a,i,UI,o)}),Je(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=x$(a,s);return this.setSymKey(c,o)}),Je(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ea(i);return await this.keychain.set(o,i),o}),Je(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Je(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Je(this,"encode",async(i,s,o)=>{this.isInitialized();const a=a0(o),c=gr(s);if(l0(a))return S$(c,o?.encoding);if(c0(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const l=this.getSymKey(i),{type:u,senderPublicKey:h}=a;return I$({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})}),Je(this,"decode",async(i,s,o)=>{this.isInitialized();const a=C$(s,o);if(l0(a)){const c=A$(s,o?.encoding);return fn(c)}if(c0(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=O$({symKey:c,encoded:s,encoding:o?.encoding});return fn(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Je(this,"getPayloadType",(i,s=kt)=>{const o=Ds({encoded:i,encoding:s});return En(o.type)}),Je(this,"getPayloadSenderPublicKey",(i,s=kt)=>{const o=Ds({encoded:i,encoding:s});return o.senderPublicKey?ut(o.senderPublicKey,nt):void 0}),this.core=e,this.logger=it(r,this.name),this.keychain=n||new US(this.core,this.logger)}get context(){return pt(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(X0)}catch{e=kl(),await this.keychain.set(X0,e)}return BS(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var qS=Object.defineProperty,zS=Object.defineProperties,HS=Object.getOwnPropertyDescriptors,Em=Object.getOwnPropertySymbols,VS=Object.prototype.hasOwnProperty,WS=Object.prototype.propertyIsEnumerable,cu=(t,e,r)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KS=(t,e)=>{for(var r in e||(e={}))VS.call(e,r)&&cu(t,r,e[r]);if(Em)for(var r of Em(e))WS.call(e,r)&&cu(t,r,e[r]);return t},GS=(t,e)=>zS(t,HS(e)),$t=(t,e,r)=>cu(t,typeof e!="symbol"?e+"":e,r);class ZS extends D6{constructor(e,r){super(e,r),this.logger=e,this.core=r,$t(this,"messages",new Map),$t(this,"messagesWithoutClientAck",new Map),$t(this,"name",kI),$t(this,"version",qI),$t(this,"initialized",!1),$t(this,"storagePrefix",nr),$t(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}}}),$t(this,"set",async(n,i,s)=>{this.isInitialized();const o=Qt(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===wa.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,GS(KS({},c),{[o]:i}))}return await this.persist(),o}),$t(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),$t(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}),$t(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Qt(i);return typeof s[o]<"u"}),$t(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Qt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),$t(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=it(e,this.name),this.core=r}get context(){return pt(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,dl(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,dl(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?fl(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?fl(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YS=Object.defineProperty,JS=Object.defineProperties,QS=Object.getOwnPropertyDescriptors,_m=Object.getOwnPropertySymbols,XS=Object.prototype.hasOwnProperty,eA=Object.prototype.propertyIsEnumerable,lu=(t,e,r)=>e in t?YS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ba=(t,e)=>{for(var r in e||(e={}))XS.call(e,r)&&lu(t,r,e[r]);if(_m)for(var r of _m(e))eA.call(e,r)&&lu(t,r,e[r]);return t},uu=(t,e)=>JS(t,QS(e)),Vt=(t,e,r)=>lu(t,typeof e!="symbol"?e+"":e,r);class tA extends T6{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Vt(this,"events",new Ve.exports.EventEmitter),Vt(this,"name",zI),Vt(this,"queue",new Map),Vt(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),Vt(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Vt(this,"needsTransportRestart",!1),Vt(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||em,c=ta(s),l=s?.prompt||!1,u=s?.tag||0,h=s?.id||xn().toString(),d={topic:n,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${u}`;try{const f=new Promise(async g=>{const m=({id:y})=>{d.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(Fe.publish,m),g(d))};this.relayer.events.on(Fe.publish,m);const w=kr(new Promise((y,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:l,tag:u,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(y).catch(_=>{this.logger.warn(_,_?.message),E(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${u}`);try{await w,this.events.removeListener(Fe.publish,m)}catch(y){this.queue.set(h,uu(ba({},d),{attempt:1})),this.logger.warn(y,y?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await kr(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),Vt(this,"on",(n,i)=>{this.events.on(n,i)}),Vt(this,"once",(n,i)=>{this.events.once(n,i)}),Vt(this,"off",(n,i)=>{this.events.off(n,i)}),Vt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=it(r,this.name),this.registerEventListeners()}get context(){return pt(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=em,prompt:l,tag:u,id:h,attestation:d,tvf:p}=e,f={method:Ts(ta().protocol).publish,params:ba({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:d},p),id:h};Ze((r=f.params)==null?void 0:r.prompt)&&((n=f.params)==null||delete n.prompt),Ze((i=f.params)==null?void 0:i.tag)&&((s=f.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const g=await this.relayer.request(f);return this.relayer.events.emit(Fe.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,uu(ba({},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(uu(ba({},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(vi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(Fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var rA=Object.defineProperty,nA=(t,e,r)=>e in t?rA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$i=(t,e,r)=>nA(t,typeof e!="symbol"?e+"":e,r);class iA{constructor(){$i(this,"map",new Map),$i(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),$i(this,"get",e=>this.map.get(e)||[]),$i(this,"exists",(e,r)=>this.get(e).includes(r)),$i(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)}),$i(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var sA=Object.defineProperty,oA=Object.defineProperties,aA=Object.getOwnPropertyDescriptors,$m=Object.getOwnPropertySymbols,cA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,hu=(t,e,r)=>e in t?sA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ws=(t,e)=>{for(var r in e||(e={}))cA.call(e,r)&&hu(t,r,e[r]);if($m)for(var r of $m(e))lA.call(e,r)&&hu(t,r,e[r]);return t},du=(t,e)=>oA(t,aA(e)),pe=(t,e,r)=>hu(t,typeof e!="symbol"?e+"":e,r);class uA extends B6{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,pe(this,"subscriptions",new Map),pe(this,"topicMap",new iA),pe(this,"events",new Ve.exports.EventEmitter),pe(this,"name",YI),pe(this,"version",JI),pe(this,"pending",new Map),pe(this,"cached",[]),pe(this,"initialized",!1),pe(this,"storagePrefix",nr),pe(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),pe(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),pe(this,"clientId"),pe(this,"batchSubscribeTopicsLimit",500),pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),pe(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=ta(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}}),pe(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),pe(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),pe(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),pe(this,"on",(n,i)=>{this.events.on(n,i)}),pe(this,"once",(n,i)=>{this.events.once(n,i)}),pe(this,"off",(n,i)=>{this.events.off(n,i)}),pe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),pe(this,"start",async()=>{await this.onConnect()}),pe(this,"stop",async()=>{await this.onDisconnect()}),pe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),pe(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)}),pe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(vi.pulse,async()=>{await this.checkPending()}),this.events.on(_t.created,async n=>{const i=_t.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(_t.deleted,async n=>{const i=_t.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=it(r,this.name),this.clientId=""}get context(){return pt(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=ta(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=he("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===ye.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Ts(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===ye.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},j.toMiliseconds(j.ONE_SECOND)),a;const c=new Promise(async u=>{const h=d=>{d.topic===e&&(this.events.removeListener(_t.created,h),u(d.id))};this.events.on(_t.created,h);try{const d=await kr(new Promise((p,f)=>{this.relayer.request(s).catch(g=>{this.logger.warn(g,g?.message),f(g)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(_t.created,h),u(d)}catch{}}),l=await kr(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(Fe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ts(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 kr(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(Fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Ts(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 kr(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(Fe.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Ts(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,du(Ws({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Ws({},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,Ws({},r)),this.topicMap.set(r.topic,e),this.events.emit(_t.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}=F("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(_t.deleted,du(Ws({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_t.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(_t.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=F("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=>du(Ws({},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 d4(j.toMiliseconds(j.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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Qt(e+await this.getClientId())}}var hA=Object.defineProperty,xm=Object.getOwnPropertySymbols,dA=Object.prototype.hasOwnProperty,fA=Object.prototype.propertyIsEnumerable,fu=(t,e,r)=>e in t?hA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Im=(t,e)=>{for(var r in e||(e={}))dA.call(e,r)&&fu(t,r,e[r]);if(xm)for(var r of xm(e))fA.call(e,r)&&fu(t,r,e[r]);return t},se=(t,e,r)=>fu(t,typeof e!="symbol"?e+"":e,r);class pA extends R6{constructor(e){super(e),se(this,"protocol","wc"),se(this,"version",2),se(this,"core"),se(this,"logger"),se(this,"events",new Ve.exports.EventEmitter),se(this,"provider"),se(this,"messages"),se(this,"subscriber"),se(this,"publisher"),se(this,"name",VI),se(this,"transportExplicitlyClosed",!1),se(this,"initialized",!1),se(this,"connectionAttemptInProgress",!1),se(this,"relayUrl"),se(this,"projectId"),se(this,"packageName"),se(this,"bundleId"),se(this,"hasExperiencedNetworkDisruption",!1),se(this,"pingTimeout"),se(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),se(this,"reconnectTimeout"),se(this,"connectPromise"),se(this,"reconnectInProgress",!1),se(this,"requestsInFlight",[]),se(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),se(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||xn().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}}),se(this,"resetPingTimeout",()=>{qo()&&(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))}),se(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),se(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Fe.connect)}),se(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),se(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Fe.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),se(this,"registerProviderListeners",()=>{this.provider.on(Tt.payload,this.onPayloadHandler),this.provider.on(Tt.connect,this.onConnectHandler),this.provider.on(Tt.disconnect,this.onDisconnectHandler),this.provider.on(Tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?it(e.logger,this.name):Xt(da({level:e.logger||HI})),this.messages=new ZS(this.logger,e.core),this.subscriber=new uA(this,this.logger),this.publisher=new tA(this,this.logger),this.relayUrl=e?.relayUrl||rm,this.projectId=e.projectId,Y5()?this.packageName=Yp():J5()&&(this.bundleId=Yp()),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 pt(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:ye.relay},wa.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(_t.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(_t.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,Im({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||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 kr(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 b0())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=Te(j.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Fe.message,e),await this.recordMessageEvent(e,wa.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(Tt.disconnect,s),await kr(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(Tt.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(Tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Tt.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,j.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(qo())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 Dt(new DI(r4({sdkVersion:iu,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}),nu(e)){if(!e.method.endsWith(WI))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:ye.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Im({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ga(e)&&this.events.emit(Fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,wa.inbound),this.events.emit(Fe.message,e))}async acknowledgePayload(e){const r=fa(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Tt.payload,this.onPayloadHandler),this.provider.off(Tt.connect,this.onConnectHandler),this.provider.off(Tt.disconnect,this.onDisconnectHandler),this.provider.off(Tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await b0();px(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(Fe.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},j.toMiliseconds(KI)))))}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function gA(){}function Om(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 Sm(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Am(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const mA="[object RegExp]",wA="[object String]",yA="[object Number]",bA="[object Boolean]",Cm="[object Arguments]",vA="[object Symbol]",EA="[object Date]",_A="[object Map]",$A="[object Set]",xA="[object Array]",IA="[object Function]",OA="[object ArrayBuffer]",pu="[object Object]",SA="[object Error]",AA="[object DataView]",CA="[object Uint8Array]",PA="[object Uint8ClampedArray]",DA="[object Uint16Array]",TA="[object Uint32Array]",RA="[object BigUint64Array]",NA="[object Int8Array]",BA="[object Int16Array]",LA="[object Int32Array]",MA="[object BigInt64Array]",UA="[object Float32Array]",jA="[object Float64Array]";function FA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function kA(t,e,r){return Ks(t,e,void 0,void 0,void 0,void 0,r)}function Ks(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 Gs(t,e,s,o)}return Gs(t,e,s,o)}function Gs(t,e,r,n){if(Object.is(t,e))return!0;let i=Am(t),s=Am(e);if(i===Cm&&(i=pu),s===Cm&&(s=pu),i!==s)return!1;switch(i){case wA:return t.toString()===e.toString();case yA:{const c=t.valueOf(),l=e.valueOf();return FA(c,l)}case bA:case EA:case vA:return Object.is(t.valueOf(),e.valueOf());case mA:return t.source===e.source&&t.flags===e.flags;case IA: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 _A:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Ks(l,e.get(c),c,t,e,r,n))return!1;return!0}case $A:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],d=l.findIndex(p=>Ks(h,p,void 0,t,e,r,n));if(d===-1)return!1;l.splice(d,1)}return!0}case xA:case CA:case PA:case DA:case TA:case RA:case NA:case BA:case LA:case MA:case UA:case jA:{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(!Ks(t[c],e[c],c,t,e,r,n))return!1;return!0}case OA:return t.byteLength!==e.byteLength?!1:Gs(new Uint8Array(t),new Uint8Array(e),r,n);case AA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Gs(new Uint8Array(t),new Uint8Array(e),r,n);case SA:return t.name===e.name&&t.message===e.message;case pu:{if(!(Gs(t.constructor,e.constructor,r,n)||Om(t)&&Om(e)))return!1;const c=[...Object.keys(t),...Sm(t)],l=[...Object.keys(e),...Sm(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Ks(d,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function qA(t,e){return kA(t,e,gA)}var zA=Object.defineProperty,Pm=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,VA=Object.prototype.propertyIsEnumerable,gu=(t,e,r)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dm=(t,e)=>{for(var r in e||(e={}))HA.call(e,r)&&gu(t,r,e[r]);if(Pm)for(var r of Pm(e))VA.call(e,r)&&gu(t,r,e[r]);return t},gt=(t,e,r)=>gu(t,typeof e!="symbol"?e+"":e,r);class An extends N6{constructor(e,r,n,i=nr,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,gt(this,"map",new Map),gt(this,"version",GI),gt(this,"cached",[]),gt(this,"initialized",!1),gt(this,"getKey"),gt(this,"storagePrefix",nr),gt(this,"recentlyDeleted",[]),gt(this,"recentlyDeletedLimit",200),gt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ze(o)?this.map.set(this.getKey(o),o):V$(o)?this.map.set(o.id,o):W$(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),gt(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())}),gt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),gt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>qA(a[c],o[c]))):this.values)),gt(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=Dm(Dm({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),gt(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=it(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return pt(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}=F("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=F("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}=F("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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WA=Object.defineProperty,KA=(t,e,r)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>KA(t,typeof e!="symbol"?e+"":e,r);class GA{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",QI),ee(this,"version",XI),ee(this,"events",new Ve.exports),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",nr),ee(this,"ignoredPayloadTypes",[$r]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),ee(this,"create",async n=>{this.isInitialized();const i=kl(),s=await this.core.crypto.setSymKey(i),o=Te(j.FIVE_MINUTES),a={protocol:tm},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},l=h0({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(In.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}}),ee(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[ir.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=u0(n.uri);i.props.properties.topic=s,i.addTrace(ir.pairing_uri_validation_success),i.addTrace(ir.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(ir.existing_pairing),u.active)throw i.setError(Or.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(ir.pairing_not_expired)}const h=c||Te(j.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(s,h),await this.pairings.set(s,d),i.addTrace(ir.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(In.create,d),i.addTrace(ir.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(ir.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Or.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(Or.subscribe_pairing_topic_failure),p}return i.addTrace(ir.subscribe_pairing_topic_success),d}),ee(this,"activate",async({topic:n})=>{this.isInitialized();const i=Te(j.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),ee(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}=mn();this.events.once(le("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),ee(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(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",he("USER_DISCONNECTED")),await this.deletePairing(i))}),ee(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return h0({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(n,i,s)=>{const o=Kr(i,s),a=await this.core.crypto.encode(n,o),c=qs[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),ee(this,"sendResult",async(n,i,s)=>{const o=fa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=qs[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(n,i,s)=>{const o=pa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=qs[c]?qs[c].res:qs.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,he("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),ee(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>qr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),ee(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)}}),ee(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)}}),ee(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(In.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{rr(i)?this.events.emit(le("pairing_ping",s),{}):Pt(i)&&this.events.emit(le("pairing_ping",s),{error:i.error})},500)}),ee(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(In.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=he("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)}}),ee(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(he("WC_METHOD_UNSUPPORTED",n))}),ee(this,"isValidPair",(n,i)=>{var s;if(!dt(n)){const{message:a}=F("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(Or.malformed_pairing_uri),new Error(a)}if(!H$(n.uri)){const{message:a}=F("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(Or.malformed_pairing_uri),new Error(a)}const o=u0(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Or.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Or.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Or.pairing_expired);const{message:a}=F("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async n=>{if(!dt(n)){const{message:s}=F("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),ee(this,"isValidDisconnect",async n=>{if(!dt(n)){const{message:s}=F("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),ee(this,"isValidPairingTopic",async n=>{if(!Ae(n,!1)){const{message:i}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(qr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=F("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=it(r,this.name),this.pairings=new An(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Fe.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==ye.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);nu(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ga(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(Rt.expired,async e=>{const{topic:r}=eg(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(In.expire,{topic:r}))})}}var ZA=Object.defineProperty,YA=(t,e,r)=>e in t?ZA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qe=(t,e,r)=>YA(t,typeof e!="symbol"?e+"":e,r);class JA extends P6{constructor(e,r){super(e,r),this.core=e,this.logger=r,Qe(this,"records",new Map),Qe(this,"events",new Ve.exports.EventEmitter),Qe(this,"name",eO),Qe(this,"version",tO),Qe(this,"cached",[]),Qe(this,"initialized",!1),Qe(this,"storagePrefix",nr),Qe(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)}),Qe(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:Te(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(zt.created,o)}),Qe(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=Pt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(zt.updated,i))}),Qe(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))),Qe(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(zt.deleted,s)}}),this.persist()}),Qe(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Qe(this,"on",(n,i)=>{this.events.on(n,i)}),Qe(this,"once",(n,i)=>{this.events.once(n,i)}),Qe(this,"off",(n,i)=>{this.events.off(n,i)}),Qe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=it(r,this.name)}get context(){return pt(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:Kr(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}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(zt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=F("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(zt.created,e=>{const r=zt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(zt.updated,e=>{const r=zt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(zt.deleted,e=>{const r=zt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(vi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{j.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(zt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var QA=Object.defineProperty,XA=(t,e,r)=>e in t?QA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,et=(t,e,r)=>XA(t,typeof e!="symbol"?e+"":e,r);class eC extends L6{constructor(e,r){super(e,r),this.core=e,this.logger=r,et(this,"expirations",new Map),et(this,"events",new Ve.exports.EventEmitter),et(this,"name",rO),et(this,"version",nO),et(this,"cached",[]),et(this,"initialized",!1),et(this,"storagePrefix",nr),et(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)}),et(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),et(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(Rt.created,{target:s,expiration:o})}),et(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),et(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(Rt.deleted,{target:i,expiration:s})}}),et(this,"on",(n,i)=>{this.events.on(n,i)}),et(this,"once",(n,i)=>{this.events.once(n,i)}),et(this,"off",(n,i)=>{this.events.off(n,i)}),et(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=it(r,this.name)}get context(){return pt(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 n4(e);if(typeof e=="number")return i4(e);const{message:r}=F("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(Rt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=F("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}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;j.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Rt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(vi.pulse,()=>this.checkExpirations()),this.events.on(Rt.created,e=>{const r=Rt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Rt.expired,e=>{const r=Rt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Rt.deleted,e=>{const r=Rt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var tC=Object.defineProperty,rC=(t,e,r)=>e in t?tC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ce=(t,e,r)=>rC(t,typeof e!="symbol"?e+"":e,r);class nC extends M6{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,Ce(this,"name",iO),Ce(this,"abortController"),Ce(this,"isDevEnv"),Ce(this,"verifyUrlV3",oO),Ce(this,"storagePrefix",nr),Ce(this,"version",Q0),Ce(this,"publicKey"),Ce(this,"fetchPromise"),Ce(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&j.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ce(this,"register",async i=>{if(!ys()||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=ss(),u=this.startAbortTimer(j.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",m),l.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",f,{signal:this.abortController.signal});const m=w=>{if(w.data&&typeof w.data=="string")try{const y=JSON.parse(w.data);if(y.type==="verify_attestation"){if(al(y.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",m),d(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};l.body.appendChild(g),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(l){this.logger.warn(l)}return""}),Ce(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(al(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)}),Ce(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(j.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}),Ce(this,"getVerifyUrl",i=>{let s=i||zs;return aO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${zs}`),s=zs),s}),Ce(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(j.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)}}),Ce(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ce(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ce(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")}}),Ce(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ce(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}),Ce(this,"validateAttestation",(i,s)=>{const o=D$(i,s.publicKey),a={hasExpired:j.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=it(r,this.name),this.abortController=new AbortController,this.isDevEnv=pl(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return pt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var iC=Object.defineProperty,sC=(t,e,r)=>e in t?iC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tm=(t,e,r)=>sC(t,typeof e!="symbol"?e+"":e,r);class oC extends U6{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Tm(this,"context",cO),Tm(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${lO}/${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=it(r,this.context)}}var aC=Object.defineProperty,Rm=Object.getOwnPropertySymbols,cC=Object.prototype.hasOwnProperty,lC=Object.prototype.propertyIsEnumerable,mu=(t,e,r)=>e in t?aC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zs=(t,e)=>{for(var r in e||(e={}))cC.call(e,r)&&mu(t,r,e[r]);if(Rm)for(var r of Rm(e))lC.call(e,r)&&mu(t,r,e[r]);return t},ke=(t,e,r)=>mu(t,typeof e!="symbol"?e+"":e,r);class uC extends j6{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,ke(this,"context",hO),ke(this,"storagePrefix",nr),ke(this,"storageVersion",uO),ke(this,"events",new Map),ke(this,"shouldPersist",!1),ke(this,"init",async()=>{if(!pl())try{const i={eventId:rg(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Qp(this.core.relayer.protocol,this.core.relayer.version,iu)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),ke(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=rg(),u=this.core.projectId||"",h=Date.now(),d=Zs({eventId:l,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),ke(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 Zs(Zs({},a),this.setMethods(a.eventId))}),ke(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),ke(this,"setEventListeners",()=>{this.core.heartbeat.on(vi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(i.timestamp)>dO&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),ke(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),ke(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)}),ke(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)}),ke(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ke(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,Zs(Zs({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),ke(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)}}),ke(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${fO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${iu}${s}`,{method:"POST",body:JSON.stringify(i)})}),ke(this,"getAppDomain",()=>Jp().url),this.logger=it(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 hC=Object.defineProperty,Nm=Object.getOwnPropertySymbols,dC=Object.prototype.hasOwnProperty,fC=Object.prototype.propertyIsEnumerable,wu=(t,e,r)=>e in t?hC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bm=(t,e)=>{for(var r in e||(e={}))dC.call(e,r)&&wu(t,r,e[r]);if(Nm)for(var r of Nm(e))fC.call(e,r)&&wu(t,r,e[r]);return t},we=(t,e,r)=>wu(t,typeof e!="symbol"?e+"":e,r);class yu extends O6{constructor(e){var r;super(e),we(this,"protocol",J0),we(this,"version",Q0),we(this,"name",ma),we(this,"relayUrl"),we(this,"projectId"),we(this,"customStoragePrefix"),we(this,"events",new Ve.exports.EventEmitter),we(this,"logger"),we(this,"heartbeat"),we(this,"relayer"),we(this,"crypto"),we(this,"storage"),we(this,"history"),we(this,"expirer"),we(this,"pairing"),we(this,"verify"),we(this,"echoClient"),we(this,"linkModeSupportedApps"),we(this,"eventClient"),we(this,"initialized",!1),we(this,"logChunkController"),we(this,"on",(a,c)=>this.events.on(a,c)),we(this,"once",(a,c)=>this.events.once(a,c)),we(this,"off",(a,c)=>this.events.off(a,c)),we(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),we(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:ye.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||rm,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=da({level:typeof e?.logger=="string"&&e.logger?e.logger:BI.logger,name:ma}),{logger:s,chunkLoggerController:o}=$6({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=it(s,this.name),this.heartbeat=new Wl,this.crypto=new kS(this,this.logger,e?.keychain),this.history=new JA(this,this.logger),this.expirer=new eC(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Zx(Bm(Bm({},LI),e?.storageOptions)),this.relayer=new pA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new GA(this,this.logger),this.verify=new nC(this,this.logger,this.storage),this.echoClient=new oC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new uC(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new yu(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(ZI,n),r}get context(){return pt(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(nm,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(nm)||[],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 pC=yu,Lm="wc",Mm=2,Um="client",bu=`${Lm}@${Mm}:${Um}:`,vu={name:Um,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},jm="WALLETCONNECT_DEEPLINK_CHOICE",gC="proposal",Fm="Proposal expired",mC="session",xi=j.SEVEN_DAYS,wC="engine",qe={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1114},res:{ttl:j.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:j.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:j.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1119}}},Eu={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},or={idle:"IDLE",active:"ACTIVE"},km={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},yC="request",bC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],vC="wc",EC="auth",_C="authKeys",$C="pairingTopics",xC="requests",va=`${vC}@${1.5}:${EC}:`,Ea=`${va}:PUB_KEY`;var IC=Object.defineProperty,OC=Object.defineProperties,SC=Object.getOwnPropertyDescriptors,qm=Object.getOwnPropertySymbols,AC=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,_u=(t,e,r)=>e in t?IC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e)=>{for(var r in e||(e={}))AC.call(e,r)&&_u(t,r,e[r]);if(qm)for(var r of qm(e))CC.call(e,r)&&_u(t,r,e[r]);return t},ot=(t,e)=>OC(t,SC(e)),L=(t,e,r)=>_u(t,typeof e!="symbol"?e+"":e,r);class PC extends z6{constructor(e){super(e),L(this,"name",wC),L(this,"events",new Ve.exports),L(this,"initialized",!1),L(this,"requestQueue",{state:or.idle,queue:[]}),L(this,"sessionRequestQueue",{state:or.idle,queue:[]}),L(this,"requestQueueDelay",j.ONE_SECOND),L(this,"expectedPairingMethodMap",new Map),L(this,"recentlyDeletedMap",new Map),L(this,"recentlyDeletedLimit",200),L(this,"relayMessageCache",[]),L(this,"pendingSessions",new Map),L(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(qe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay)))}),L(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=ot(ge({},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,h,d=!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."),d=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),S}if(!u||!d){const{topic:S,uri:x}=await this.client.core.pairing.create();u=S,h=x}if(!u){const{message:S}=F("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(S)}const p=await this.client.core.crypto.generateKeyPair(),f=qe.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,g=Te(f),m=ot(ge(ge({requiredNamespaces:s,optionalNamespaces:o,relays:l??[{protocol:tm}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:tr()}),w=le("session_connect",m.id),{reject:y,resolve:E,done:_}=mn(f,Fm),O=({id:S})=>{S===m.id&&(this.client.events.off("proposal_expire",O),this.pendingSessions.delete(m.id),this.events.emit(w,{error:{message:Fm,code:0}}))};return this.client.events.on("proposal_expire",O),this.events.once(w,({error:S,session:x})=>{this.client.events.off("proposal_expire",O),S?y(S):x&&E(x)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0,clientRpcId:m.id}),await this.setProposal(m.id,m),{uri:h,approval:_}}),L(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}}),L(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:[Ht.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch($){throw o.setError(On.no_internet_connection),$}try{await this.isValidProposalId(r?.id)}catch($){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(On.proposal_not_found),$}try{await this.isValidApprove(r)}catch($){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(On.session_approve_namespace_validation_failure),$}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:m,optionalNamespaces:w}=p;let y=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:f});y||(y=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ht.session_approve_started,properties:{topic:f,trace:[Ht.session_approve_started,Ht.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),_=g.publicKey,O=await this.client.core.crypto.generateSharedKey(E,_),S=ge(ge(ge({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:Te(xi)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),x=ye.relay;y.addTrace(Ht.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:x})}catch($){throw y.setError(On.subscribe_session_topic_failure),$}y.addTrace(Ht.subscribe_session_topic_success);const P=ot(ge({},S),{topic:O,requiredNamespaces:m,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:S.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:E,transportType:ye.relay});await this.client.session.set(O,P),y.addTrace(Ht.store_session);try{y.addTrace(Ht.publishing_session_settle),await this.sendRequest({topic:O,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch($=>{throw y?.setError(On.session_settle_publish_failure),$}),y.addTrace(Ht.session_settle_publish_success),y.addTrace(Ht.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch($=>{throw y?.setError(On.session_approve_publish_failure),$}),y.addTrace(Ht.session_approve_publish_success)}catch($){throw this.client.logger.error($),this.client.session.delete(O,he("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),$}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.client.proposal.delete(a,he("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(O,Te(xi)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),L(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:qe.wc_sessionPropose.reject}),await this.client.proposal.delete(n,he("USER_DISCONNECTED")))}),L(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=mn(),c=tr(),l=xn().toString(),u=this.client.session.get(n).namespaces;return this.events.once(le("session_update",c),({error:h})=>{h?a(h):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(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:u}),a(h)}),{acknowledged:s}}),L(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=tr(),{done:s,resolve:o,reject:a}=mn();return this.events.once(le("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,Te(xi)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),L(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=qe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===ye.relay&&await this.confirmOnlineStateOrThrow();const c=tr(),l=xn().toString(),{done:u,resolve:h,reject:d}=mn(o,"Request expired. Please try again.");this.events.once(le("session_request",c),({error:w,result:y})=>{w?d(w):h(y)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:p,params:{request:ot(ge({},i),{expiryTimestamp:Te(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await u();const g={request:ot(ge({},i),{expiryTimestamp:Te(o)}),chainId:n},m=this.shouldSetTVF(p,g);return await Promise.all([new Promise(async w=>{await this.sendRequest(ge({clientRpcId:c,relayRpcId:l,topic:s,method:p,params:g,expiry:o,throwOnFailedPublish:!0},m&&{tvf:this.getTVFParams(c,g)})).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const E=await c4(this.client.core.storage,jm);await s4({id:c,topic:s,wcDeepLink:E})}w()}),u()]).then(w=>w[2])}),L(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===ye.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);rr(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):Pt(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),L(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=tr(),s=xn().toString(),{done:o,resolve:a,reject:c}=mn();this.events.once(le("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}))}),L(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=xn().toString(),a=tr();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),L(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:he("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}=F("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),L(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>q$(n,r)))),L(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),L(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?ye.link_mode:ye.relay;o===ye.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:d,exp:p,nbf:f,methods:g=[],expiry:m}=r,w=[...r.resources||[]],{topic:y,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:E}});const _=await this.client.core.crypto.generateKeyPair(),O=ea(_);if(await Promise.all([this.client.auth.authKeys.set(Ea,{responseTopic:O,publicKey:_}),this.client.auth.pairingTopics.set(O,{topic:O,pairingTopic:y})]),await this.client.core.relayer.subscribe(O,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),g.length>0){const{namespace:C}=oi(a[0]);let N=X4(C,"request",g);Wo(w)&&(N=t8(N,w.pop())),w.push(N)}const S=m&&m>qe.wc_sessionAuthenticate.req.ttl?m:qe.wc_sessionAuthenticate.req.ttl,x={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(S)},P={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:P,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(qe.wc_sessionPropose.req.ttl),id:tr()},{done:B,resolve:D,reject:R}=mn(S,"Request expired"),M=tr(),A=le("session_connect",$.id),b=le("session_request",M),v=async({error:C,session:N})=>{this.events.off(b,I),C?R(C):N&&D({session:N})},I=async C=>{var N,U,k;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),C.error){const Q=he("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===Q.code?void 0:(this.events.off(A,v),R(C.error.message))}await this.deleteProposal($.id),this.events.off(A,v);const{cacaos:H,responder:q}=C.result,W=[],G=[];for(const Q of H){await wg({cacao:Q,projectId:this.client.core.projectId})||(this.client.logger.error(Q,"Signature verification failed"),R(he("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Se}=Q,ve=Wo(Se.resources),_e=[vl(Se.iss)],He=Vo(Se.iss);if(ve){const Pe=vg(ve),Pr=Eg(ve);W.push(...Pe),_e.push(...Pr)}for(const Pe of _e)G.push(`${Pe}:${He}`)}const ce=await this.client.core.crypto.generateSharedKey(_,q.publicKey);let X;W.length>0&&(X={topic:ce,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:Te(xi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:d0([...new Set(W)],[...new Set(G)]),transportType:o},await this.client.core.relayer.subscribe(ce,{transportType:o}),await this.client.session.set(ce,X),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:q.metadata}),X=this.client.session.get(ce)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(U=q.metadata.redirect)!=null&&U.linkMode&&(k=q.metadata.redirect)!=null&&k.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ce,{transportType:ye.link_mode})),D({auths:H,session:X})};this.events.once(A,v),this.events.once(b,I);let T;try{if(s){const C=Kr("wc_sessionAuthenticate",x,M);this.client.core.history.set(y,C);const N=await this.client.core.crypto.encode("",C,{type:Cs,encoding:Wr});T=ra(n,y,N)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:x,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:$,expiry:qe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(C){throw this.events.off(A,v),this.events.off(b,I),C}return await this.setProposal($.id,$),await this.setAuthRequest(M,{request:ot(ge({},x),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:T??E,response:B}}),L(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Sn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw s.setError(Hs.no_internet_connection),m}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Hs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ye.relay;a===ye.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=ea(c),h={type:$r,receiverPublicKey:c,senderPublicKey:l},d=[],p=[];for(const m of i){if(!await wg({cacao:m,projectId:this.client.core.projectId})){s.setError(Hs.invalid_cacao);const O=he("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:O,encodeOpts:h}),new Error(O.message)}s.addTrace(Sn.cacaos_verified);const{p:w}=m,y=Wo(w.resources),E=[vl(w.iss)],_=Vo(w.iss);if(y){const O=vg(y),S=Eg(y);d.push(...O),E.push(...S)}for(const O of E)p.push(`${O}:${_}`)}const f=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Sn.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:f,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Te(xi),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:d0([...new Set(d)],[...new Set(p)]),transportType:a},s.addTrace(Sn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(m){throw s.setError(Hs.subscribe_authenticated_session_topic_failure),m}s.addTrace(Sn.subscribe_authenticated_session_topic_success),await this.client.session.set(f,g),s.addTrace(Sn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Sn.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw s.setError(Hs.authenticated_session_approve_publish_failure),m}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:g}}),L(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===ye.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ea(o),l={type:$r,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:l,rpcOpts:qe.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,he("USER_DISCONNECTED"))}),L(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return yg(n,i)}),L(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)}),L(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)}}),L(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,he("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(jm).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,he("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=or.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),L(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(On.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,he("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),L(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=or.idle,this.client.events.emit("session_request_expire",{id:r}))}),L(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)])}),L(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}))}),L(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,Te(qe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),L(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=ye.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})}),L(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||Te(qe.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})}),L(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h}=r,d=Kr(i,s,c);let p;const f=!!u;try{const w=f?Wr:kt;p=await this.client.core.crypto.encode(n,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),w}let g;if(bC.includes(i)){const w=Qt(JSON.stringify(d)),y=Qt(p);g=await this.client.core.verify.register({id:y,decryptedId:w})}const m=qe[i].req;if(m.attestation=g,o&&(m.ttl=o),a&&(m.id=a),this.client.core.history.set(n,d),f){const w=ra(u,n,p);await global.Linking.openURL(w,this.client.name)}else{const w=qe[i].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=ot(ge({},h),{correlationId:d.id}),l?(w.internal=ot(ge({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,w)):this.client.core.relayer.publish(n,p,w).catch(y=>this.client.logger.error(y))}return d.id}),L(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=fa(n,s);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?Wr:kt;u=await this.client.core.crypto.encode(i,l,ot(ge({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),f}let d,p;try{d=await this.client.core.history.get(i,n);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(n,f.params,s))}catch(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),f}if(h){const f=ra(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,g=qe[f].res;g.tvf=ot(ge({},p),{correlationId:n}),o?(g.internal=ot(ge({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(l)}),L(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=pa(n,s);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?Wr:kt;u=await this.client.core.crypto.encode(i,l,ot(ge({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=ra(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||qe[p].res;this.client.core.relayer.publish(i,u,f)}await this.client.core.history.resolve(l)}),L(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;qr(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=>{qr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),L(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),L(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),L(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===or.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=or.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=or.idle}),L(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}`)}}),L(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}`)}}),L(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=F("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),L(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)}),L(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(Or.proposal_listener_not_found)),this.isValidConnect(ge({},i.params));const u=a.expiryTimestamp||Te(qe.wc_sessionPropose.req.ttl),h=ge({id:c,pairingTopic:n,expiryTimestamp:u},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:Qt(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(ir.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:qe.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),L(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(rr(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 h=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(Pt(n)){await this.client.proposal.delete(s,he("USER_DISCONNECTED"));const o=le("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})}}),L(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:h,sessionConfig:d}=n.params,p=[...this.pendingSessions.values()].find(m=>m.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const f=this.client.proposal.get(p.proposalId),g=ot(ge(ge(ge({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:ye.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(le("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),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)}}),L(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;rr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(le("session_approve",i),{})):Pt(n)&&(await this.client.session.delete(r,he("USER_DISCONNECTED")),this.events.emit(le("session_approve",i),{error:n.error}))}),L(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Bs.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:he("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ge({topic:r},i));try{Bs.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 Bs.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)}}),L(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),L(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=le("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);rr(n)?this.events.emit(le("session_update",i),{}):Pt(n)&&this.events.emit(le("session_update",i),{error:n.error})}),L(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Te(xi)),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)}}),L(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=le("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);rr(n)?this.events.emit(le("session_extend",i),{}):Pt(n)&&this.events.emit(le("session_extend",i),{error:n.error})}),L(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)}}),L(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=le("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);rr(n)?this.events.emit(le("session_ping",i),{}):Pt(n)&&this.events.emit(le("session_ping",i),{error:n.error})},500)}),L(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(Fe.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:he("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),L(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:h,params:d}=a;try{await this.isValidRequest(ge({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:Qt(JSON.stringify(Kr("wc_sessionRequest",d,h))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),g={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(g),u===ye.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),L(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=le("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);rr(n)?this.events.emit(le("session_request",i),{result:n.result}):Pt(n)&&this.events.emit(le("session_request",i),{error:n.error})}),L(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Bs.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ge({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Bs.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),L(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),rr(n)?this.events.emit(le("session_request",i),{result:n.result}):Pt(n)&&this.events.emit(le("session_request",i),{error:n.error})}),L(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:h}=s.params,d=await this.getVerifyContext({attestationId:o,hash:Qt(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===ye.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:d})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:$r,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:p,rpcOpts:qe.wc_sessionAuthenticate.autoReject,appLink:d})}}),L(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),L(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=or.idle,this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay))}),L(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=le("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(le("session_request",s.request.id),{error:n})})}),L(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===or.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=or.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),L(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),L(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:Kr("wc_sessionPropose",ot(ge({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),L(this,"isValidConnect",async r=>{if(!dt(r)){const{message:l}=F("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(Ze(n)||await this.isValidPairingTopic(n),!ex(c,!0)){const{message:l}=F("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Ze(i)&&Ns(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Ze(s)&&Ns(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Ze(o)||this.validateSessionProps(o,"sessionProperties"),!Ze(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)}`)}}),L(this,"validateNamespaces",(r,n)=>{const i=X$(r,"connect()",n);if(i)throw new Error(i.message)}),L(this,"isValidApprove",async r=>{if(!dt(r))throw new Error(F("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=Hl(i,"approve()");if(l)throw new Error(l.message);const u=w0(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!Ae(s,!0)){const{message:h}=F("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Ze(o)||this.validateSessionProps(o,"sessionProperties"),!Ze(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),L(this,"isValidReject",async r=>{if(!dt(r)){const{message:s}=F("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!rx(i)){const{message:s}=F("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),L(this,"isValidSessionSettleRequest",r=>{if(!dt(r)){const{message:l}=F("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!g0(n)){const{message:l}=F("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=K$(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Hl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qr(o)){const{message:l}=F("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),L(this,"isValidUpdate",async r=>{if(!dt(r)){const{message:c}=F("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=Hl(i,"update()");if(o)throw new Error(o.message);const a=w0(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),L(this,"isValidExtend",async r=>{if(!dt(r)){const{message:i}=F("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),L(this,"isValidRequest",async r=>{if(!dt(r)){const{message:c}=F("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(!m0(a,s)){const{message:c}=F("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!nx(i)){const{message:c}=F("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!ox(a,s,i.method)){const{message:c}=F("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!ux(o,Eu)){const{message:c}=F("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Eu.min} and ${Eu.max}`);throw new Error(c)}}),L(this,"isValidRespond",async r=>{var n;if(!dt(r)){const{message:o}=F("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(!ix(s)){const{message:o}=F("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),L(this,"isValidPing",async r=>{if(!dt(r)){const{message:i}=F("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),L(this,"isValidEmit",async r=>{if(!dt(r)){const{message:a}=F("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(!m0(o,s)){const{message:a}=F("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!sx(i)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!ax(o,s,i.name)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),L(this,"isValidDisconnect",async r=>{if(!dt(r)){const{message:i}=F("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),L(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(!Ae(i,!1))throw new Error("uri is required parameter");if(!Ae(s,!1))throw new Error("domain is required parameter");if(!Ae(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>oi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=oi(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),L(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||zs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ye.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}),L(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=F("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),L(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),L(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)}}}),L(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=F("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),L(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,l,u,h,d;return!r||n!==ye.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&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),L(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),L(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=tg(r,"topic")||"",i=decodeURIComponent(tg(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:ye.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),L(this,"registerLinkModeListeners",async()=>{var r;if(pl()||Fr()&&(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)}}}),L(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(km).includes(i.method)}),L(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return ot(ge({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{}}),L(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}),L(this,"extractTxHashesFromResult",(r,n)=>{try{const i=km[r];if(typeof n=="string")return[n];const s=n[i.key];if(qt(s))return r==="solana_signAllTransactions"?s.map(o=>j4(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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Fe.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(Ea)?this.client.auth.authKeys.get(Ea):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===ye.link_mode?Wr:kt});nu(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Qt(n)})):ga(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(Rt.expired,async e=>{const{topic:r,id:n}=eg(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,F("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,F("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(In.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(In.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ae(e,!1)){const{message:r}=F("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}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=F("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ae(e,!1)){const{message:r}=F("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}=F("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=F("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=F("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(Ae(e,!1)){const{message:r}=F("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=F("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!tx(e)){const{message:r}=F("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=F("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=F("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class DC extends An{constructor(e,r){super(e,r,gC,bu),this.core=e,this.logger=r}}class TC extends An{constructor(e,r){super(e,r,mC,bu),this.core=e,this.logger=r}}class RC extends An{constructor(e,r){super(e,r,yC,bu,n=>n.id),this.core=e,this.logger=r}}class NC extends An{constructor(e,r){super(e,r,_C,va,()=>Ea),this.core=e,this.logger=r}}class BC extends An{constructor(e,r){super(e,r,$C,va),this.core=e,this.logger=r}}class LC extends An{constructor(e,r){super(e,r,xC,va,n=>n.id),this.core=e,this.logger=r}}var MC=Object.defineProperty,UC=(t,e,r)=>e in t?MC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$u=(t,e,r)=>UC(t,typeof e!="symbol"?e+"":e,r);class jC{constructor(e,r){this.core=e,this.logger=r,$u(this,"authKeys"),$u(this,"pairingTopics"),$u(this,"requests"),this.authKeys=new NC(this.core,this.logger),this.pairingTopics=new BC(this.core,this.logger),this.requests=new LC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var FC=Object.defineProperty,kC=(t,e,r)=>e in t?FC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>kC(t,typeof e!="symbol"?e+"":e,r);class xu extends q6{constructor(e){super(e),te(this,"protocol",Lm),te(this,"version",Mm),te(this,"name",vu.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new Ve.exports.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(n,i)=>this.events.on(n,i)),te(this,"once",(n,i)=>this.events.once(n,i)),te(this,"off",(n,i)=>this.events.off(n,i)),te(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),te(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),te(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),te(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||vu.name,this.metadata=X5(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xt(da({level:e?.logger||vu.logger}));this.core=e?.core||new pC(e),this.logger=it(r,this.name),this.session=new TC(this.core,this.logger),this.proposal=new DC(this.core,this.logger),this.pendingRequest=new RC(this.core,this.logger),this.engine=new PC(this),this.auth=new jC(this.core,this.logger)}static async init(e){const r=new xu(e);return await r.initialize(),r}get context(){return pt(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()},j.toMiliseconds(j.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Iu={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof ct<"u"&&ct,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 ct<"u"&&ct||{},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(b){return b&&DataView.prototype.isPrototypeOf(b)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(b){return b&&u.indexOf(Object.prototype.toString.call(b))>-1};function d(b){if(typeof b!="string"&&(b=String(b)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(b)||b==="")throw new TypeError('Invalid character in header field name: "'+b+'"');return b.toLowerCase()}function p(b){return typeof b!="string"&&(b=String(b)),b}function f(b){var v={next:function(){var I=b.shift();return{done:I===void 0,value:I}}};return c.iterable&&(v[Symbol.iterator]=function(){return v}),v}function g(b){this.map={},b instanceof g?b.forEach(function(v,I){this.append(I,v)},this):Array.isArray(b)?b.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):b&&Object.getOwnPropertyNames(b).forEach(function(v){this.append(v,b[v])},this)}g.prototype.append=function(b,v){b=d(b),v=p(v);var I=this.map[b];this.map[b]=I?I+", "+v:v},g.prototype.delete=function(b){delete this.map[d(b)]},g.prototype.get=function(b){return b=d(b),this.has(b)?this.map[b]:null},g.prototype.has=function(b){return this.map.hasOwnProperty(d(b))},g.prototype.set=function(b,v){this.map[d(b)]=p(v)},g.prototype.forEach=function(b,v){for(var I in this.map)this.map.hasOwnProperty(I)&&b.call(v,this.map[I],I,this)},g.prototype.keys=function(){var b=[];return this.forEach(function(v,I){b.push(I)}),f(b)},g.prototype.values=function(){var b=[];return this.forEach(function(v){b.push(v)}),f(b)},g.prototype.entries=function(){var b=[];return this.forEach(function(v,I){b.push([I,v])}),f(b)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function m(b){if(!b._noBody){if(b.bodyUsed)return Promise.reject(new TypeError("Already read"));b.bodyUsed=!0}}function w(b){return new Promise(function(v,I){b.onload=function(){v(b.result)},b.onerror=function(){I(b.error)}})}function y(b){var v=new FileReader,I=w(v);return v.readAsArrayBuffer(b),I}function E(b){var v=new FileReader,I=w(v),T=/charset=([A-Za-z0-9_-]+)/.exec(b.type),C=T?T[1]:"utf-8";return v.readAsText(b,C),I}function _(b){for(var v=new Uint8Array(b),I=new Array(v.length),T=0;T<v.length;T++)I[T]=String.fromCharCode(v[T]);return I.join("")}function O(b){if(b.slice)return b.slice(0);var v=new Uint8Array(b.byteLength);return v.set(new Uint8Array(b)),v.buffer}function S(){return this.bodyUsed=!1,this._initBody=function(b){this.bodyUsed=this.bodyUsed,this._bodyInit=b,b?typeof b=="string"?this._bodyText=b:c.blob&&Blob.prototype.isPrototypeOf(b)?this._bodyBlob=b:c.formData&&FormData.prototype.isPrototypeOf(b)?this._bodyFormData=b:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(b)?this._bodyText=b.toString():c.arrayBuffer&&c.blob&&l(b)?(this._bodyArrayBuffer=O(b.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(b)||h(b))?this._bodyArrayBuffer=O(b):this._bodyText=b=Object.prototype.toString.call(b):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof b=="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(b)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var b=m(this);if(b)return b;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 b=m(this);return b||(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(y);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var b=m(this);if(b)return b;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(_(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(B)}),this.json=function(){return this.text().then(JSON.parse)},this}var x=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function P(b){var v=b.toUpperCase();return x.indexOf(v)>-1?v:b}function $(b,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 I=v.body;if(b instanceof $){if(b.bodyUsed)throw new TypeError("Already read");this.url=b.url,this.credentials=b.credentials,v.headers||(this.headers=new g(b.headers)),this.method=b.method,this.mode=b.mode,this.signal=b.signal,!I&&b._bodyInit!=null&&(I=b._bodyInit,b.bodyUsed=!0)}else this.url=String(b);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new g(v.headers)),this.method=P(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal||function(){if("AbortController"in a){var N=new AbortController;return N.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(v.cache==="no-store"||v.cache==="no-cache")){var T=/([?&])_=[^&]*/;if(T.test(this.url))this.url=this.url.replace(T,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function B(b){var v=new FormData;return b.trim().split("&").forEach(function(I){if(I){var T=I.split("="),C=T.shift().replace(/\+/g," "),N=T.join("=").replace(/\+/g," ");v.append(decodeURIComponent(C),decodeURIComponent(N))}}),v}function D(b){var v=new g,I=b.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(T){return T.indexOf(`
39
+ ***************************************************************************** */var eu=function(t,e){return eu=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])},eu(t,e)};function J6(t,e){eu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var tu=function(){return tu=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},tu.apply(this,arguments)};function Q6(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 X6(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 eI(t,e){return function(r,n){e(r,n,t)}}function tI(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function rI(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(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function nI(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 iI(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function sI(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ru(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 F0(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 oI(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F0(arguments[e]));return t}function aI(){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 ks(t){return this instanceof ks?(this.v=t,this):new ks(t)}function cI(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(d){n[d]&&(i[d]=function(p){return new Promise(function(f,g){s.push([d,p,f,g])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof ks?Promise.resolve(d.value.v).then(l,u):h(s[0][2],d)}function l(d){a("next",d)}function u(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function lI(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:ks(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function uI(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 ru=="function"?ru(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 hI(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function dI(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 fI(t){return t&&t.__esModule?t:{default:t}}function pI(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function gI(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 mI=Object.freeze({__proto__:null,__extends:J6,get __assign(){return tu},__rest:Q6,__decorate:X6,__param:eI,__metadata:tI,__awaiter:rI,__generator:nI,__createBinding:iI,__exportStar:sI,__values:ru,__read:F0,__spread:oI,__spreadArrays:aI,__await:ks,__asyncGenerator:cI,__asyncDelegator:lI,__asyncValues:uI,__makeTemplateObject:hI,__importStar:dI,__importDefault:fI,__classPrivateFieldGet:pI,__classPrivateFieldSet:gI}),wI=Gh(mI),xr={},k0;function yI(){if(k0)return xr;k0=1,Object.defineProperty(xr,"__esModule",{value:!0}),xr.isBrowserCryptoAvailable=xr.getSubtleCrypto=xr.getBrowerCrypto=void 0;function t(){return ct?.crypto||ct?.msCrypto||{}}xr.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}xr.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return xr.isBrowserCryptoAvailable=r,xr}var Ir={},q0;function bI(){if(q0)return Ir;q0=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.isBrowser=Ir.isNode=Ir.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ir.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ir.isNode=e;function r(){return!t()&&!e()}return Ir.isBrowser=r,Ir}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=wI;e.__exportStar(yI(),t),e.__exportStar(bI(),t)})(j0);function tr(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function xn(t=6){return BigInt(tr(t))}function Kr(t,e,r){return{id:r||tr(),jsonrpc:"2.0",method:t,params:e}}function fa(t,e){return{id:t,jsonrpc:"2.0",result:e}}function pa(t,e,r){return{id:t,jsonrpc:"2.0",error:vI(e,r)}}function vI(t,e){return typeof t>"u"?M0(B0):(typeof t=="string"&&(t=Object.assign(Object.assign({},M0(Xl)),{message:t})),typeof e<"u"&&(t.data=e),Z6(t.code)&&(t=Y6(t.code)),t)}class EI{}class _I extends EI{constructor(){super()}}class $I extends _I{constructor(e){super()}}const xI="^https?:",II="^wss?:";function OI(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function z0(t,e){const r=OI(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function H0(t){return z0(t,xI)}function V0(t){return z0(t,II)}function SI(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function W0(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function nu(t){return W0(t)&&"method"in t}function ga(t){return W0(t)&&(rr(t)||Pt(t))}function rr(t){return"result"in t}function Pt(t){return"error"in t}class Dt extends $I{constructor(e){super(e),this.events=new Ve.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(Kr(e.method,e.params||[],e.id||xn().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=>{Pt(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),ga(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 AI=()=>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"),CI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",K0=t=>t.split("?")[0],G0=10,PI=AI();class DI{constructor(e){if(this.url=e,this.events=new Ve.exports.EventEmitter,this.registering=!1,!V0(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(gr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!V0(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=j0.isReactNative()?void 0:{rejectUnauthorized:!SI(e)},s=new PI(e,[],i);CI()?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"?fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=pa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return U0(e,K0(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>G0&&this.events.setMaxListeners(G0)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${K0(this.url)}`));return this.events.emit("register_error",r),r}}var TI=Object.defineProperty,Z0=Object.getOwnPropertySymbols,RI=Object.prototype.hasOwnProperty,NI=Object.prototype.propertyIsEnumerable,Y0=(t,e,r)=>e in t?TI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,st=(t,e)=>{for(var r in e||(e={}))RI.call(e,r)&&Y0(t,r,e[r]);if(Z0)for(var r of Z0(e))NI.call(e,r)&&Y0(t,r,e[r]);return t};const J0="wc",Q0=2,ma="core",nr=`${J0}@2:${ma}:`,BI={name:ma,logger:"error"},LI={database:":memory:"},MI="crypto",X0="client_ed25519_seed",UI=j.ONE_DAY,jI="keychain",FI="0.3",kI="messages",qI="0.3",em=j.SIX_HOURS,zI="publisher",tm="irn",HI="error",rm="wss://relay.walletconnect.org",VI="relayer",Fe={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"},WI="_subscription",Tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},KI=.1,iu="2.19.2",ye={link_mode:"link_mode",relay:"relay"},wa={inbound:"inbound",outbound:"outbound"},GI="0.3",ZI="WALLETCONNECT_CLIENT_ID",nm="WALLETCONNECT_LINK_MODE_APPS",_t={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},YI="subscription",JI="0.3",QI="pairing",XI="0.3",qs={wc_pairingDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:j.ONE_DAY,prompt:!1,tag:0},res:{ttl:j.ONE_DAY,prompt:!1,tag:0}}},In={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},zt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},eO="history",tO="0.3",rO="expirer",Rt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},nO="0.3",iO="verify-api",sO="https://verify.walletconnect.com",im="https://verify.walletconnect.org",zs=im,oO=`${zs}/v3`,aO=[sO,im],cO="echo",lO="https://echo.walletconnect.com",ir={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"},Or={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"},Ht={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"},On={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"},Sn={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"},Hs={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"},uO=.1,hO="event-client",dO=86400,fO="https://pulse.walletconnect.org/batch";function pO(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 h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,m=0,w=0,y=f.length;w!==y&&f[w]===0;)w++,g++;for(var E=(y-w)*u+1>>>0,_=new Uint8Array(E);w!==y;){for(var O=f[w],S=0,x=E-1;(O!==0||S<m)&&x!==-1;x--,S++)O+=256*_[x]>>>0,_[x]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");m=S,w++}for(var P=E-m;P!==E&&_[P]===0;)P++;for(var $=c.repeat(g);P<E;++P)$+=t.charAt(_[P]);return $}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var m=0,w=0;f[g]===c;)m++,g++;for(var y=(f.length-g)*l+1>>>0,E=new Uint8Array(y);f[g];){var _=r[f.charCodeAt(g)];if(_===255)return;for(var O=0,S=y-1;(_!==0||O<w)&&S!==-1;S--,O++)_+=a*E[S]>>>0,E[S]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=O,g++}if(f[g]!==" "){for(var x=y-w;x!==y&&E[x]===0;)x++;for(var P=new Uint8Array(m+(y-x)),$=m;x!==y;)P[$++]=E[x++];return P}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var gO=pO,mO=gO;const sm=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")},wO=t=>new TextEncoder().encode(t),yO=t=>new TextDecoder().decode(t);class bO{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 vO{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 om(this,e)}}class EO{constructor(e){this.decoders=e}or(e){return om(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 om=(t,e)=>new EO(st(st({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class _O{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new bO(e,r,n),this.decoder=new vO(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ya=({name:t,prefix:e,encode:r,decode:n})=>new _O(t,e,r,n),Vs=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=mO(r,e);return ya({prefix:t,name:e,encode:n,decode:s=>sm(i(s))})},$O=(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 h=i[t[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},xO=(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},Ye=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ya({prefix:e,name:t,encode(i){return xO(i,n,r)},decode(i){return $O(i,n,r,t)}}),IO=ya({prefix:"\0",name:"identity",encode:t=>yO(t),decode:t=>wO(t)});var OO=Object.freeze({__proto__:null,identity:IO});const SO=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var AO=Object.freeze({__proto__:null,base2:SO});const CO=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var PO=Object.freeze({__proto__:null,base8:CO});const DO=Vs({prefix:"9",name:"base10",alphabet:"0123456789"});var TO=Object.freeze({__proto__:null,base10:DO});const RO=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),NO=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var BO=Object.freeze({__proto__:null,base16:RO,base16upper:NO});const LO=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),MO=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),UO=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jO=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),FO=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kO=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qO=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zO=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),HO=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var VO=Object.freeze({__proto__:null,base32:LO,base32upper:MO,base32pad:UO,base32padupper:jO,base32hex:FO,base32hexupper:kO,base32hexpad:qO,base32hexpadupper:zO,base32z:HO});const WO=Vs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),KO=Vs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var GO=Object.freeze({__proto__:null,base36:WO,base36upper:KO});const ZO=Vs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YO=Vs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var JO=Object.freeze({__proto__:null,base58btc:ZO,base58flickr:YO});const QO=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XO=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),eS=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tS=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rS=Object.freeze({__proto__:null,base64:QO,base64pad:XO,base64url:eS,base64urlpad:tS});const am=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}"),nS=am.reduce((t,e,r)=>(t[r]=e,t),[]),iS=am.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function sS(t){return t.reduce((e,r)=>(e+=nS[r],e),"")}function oS(t){const e=[];for(const r of t){const n=iS[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const aS=ya({prefix:"\u{1F680}",name:"base256emoji",encode:sS,decode:oS});var cS=Object.freeze({__proto__:null,base256emoji:aS}),lS=lm,cm=128,uS=127,hS=~uS,dS=Math.pow(2,31);function lm(t,e,r){e=e||[],r=r||0;for(var n=r;t>=dS;)e[r++]=t&255|cm,t/=128;for(;t&hS;)e[r++]=t&255|cm,t>>>=7;return e[r]=t|0,lm.bytes=r-n+1,e}var fS=su,pS=128,um=127;function su(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw su.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&um)<<i:(o&um)*Math.pow(2,i),i+=7}while(o>=pS);return su.bytes=s-n,r}var gS=Math.pow(2,7),mS=Math.pow(2,14),wS=Math.pow(2,21),yS=Math.pow(2,28),bS=Math.pow(2,35),vS=Math.pow(2,42),ES=Math.pow(2,49),_S=Math.pow(2,56),$S=Math.pow(2,63),xS=function(t){return t<gS?1:t<mS?2:t<wS?3:t<yS?4:t<bS?5:t<vS?6:t<ES?7:t<_S?8:t<$S?9:10},IS={encode:lS,decode:fS,encodingLength:xS},hm=IS;const dm=(t,e,r=0)=>(hm.encode(t,e,r),e),fm=t=>hm.encodingLength(t),ou=(t,e)=>{const r=e.byteLength,n=fm(t),i=n+fm(r),s=new Uint8Array(i+r);return dm(t,s,0),dm(r,s,n),s.set(e,i),new OS(t,r,e,s)};class OS{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const pm=({name:t,code:e,encode:r})=>new SS(t,e,r);class SS{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?ou(this.code,r):r.then(n=>ou(this.code,n))}else throw Error("Unknown type, must be binary type")}}const gm=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),AS=pm({name:"sha2-256",code:18,encode:gm("SHA-256")}),CS=pm({name:"sha2-512",code:19,encode:gm("SHA-512")});var PS=Object.freeze({__proto__:null,sha256:AS,sha512:CS});const mm=0,DS="identity",wm=sm;var TS=Object.freeze({__proto__:null,identity:{code:mm,name:DS,encode:wm,digest:t=>ou(mm,wm(t))}});new TextEncoder,new TextDecoder;const ym=st(st(st(st(st(st(st(st(st(st({},OO),AO),PO),TO),BO),VO),GO),JO),rS),cS);st(st({},PS),TS);function RS(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function bm(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const vm=bm("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),au=bm("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=RS(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),NS=st({utf8:vm,"utf-8":vm,hex:ym.base16,latin1:au,ascii:au,binary:au},ym);function BS(t,e="utf8"){const r=NS[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 LS=Object.defineProperty,MS=(t,e,r)=>e in t?LS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sr=(t,e,r)=>MS(t,typeof e!="symbol"?e+"":e,r);class US{constructor(e,r){this.core=e,this.logger=r,sr(this,"keychain",new Map),sr(this,"name",jI),sr(this,"version",FI),sr(this,"initialized",!1),sr(this,"storagePrefix",nr),sr(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),sr(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),sr(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),sr(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=F("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),sr(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=it(r,this.name)}get context(){return pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,dl(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?fl(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jS=Object.defineProperty,FS=(t,e,r)=>e in t?jS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Je=(t,e,r)=>FS(t,typeof e!="symbol"?e+"":e,r);class kS{constructor(e,r,n){this.core=e,this.logger=r,Je(this,"name",MI),Je(this,"keychain"),Je(this,"randomSessionIdentifier",kl()),Je(this,"initialized",!1),Je(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Je(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Je(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=xp(i);return $p(s.publicKey)}),Je(this,"generateKeyPair",()=>{this.isInitialized();const i=$$();return this.setPrivateKey(i.publicKey,i.privateKey)}),Je(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=xp(s),a=this.randomSessionIdentifier;return await g_(a,i,UI,o)}),Je(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=x$(a,s);return this.setSymKey(c,o)}),Je(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ea(i);return await this.keychain.set(o,i),o}),Je(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Je(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Je(this,"encode",async(i,s,o)=>{this.isInitialized();const a=a0(o),c=gr(s);if(l0(a))return S$(c,o?.encoding);if(c0(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const l=this.getSymKey(i),{type:u,senderPublicKey:h}=a;return I$({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})}),Je(this,"decode",async(i,s,o)=>{this.isInitialized();const a=C$(s,o);if(l0(a)){const c=A$(s,o?.encoding);return fn(c)}if(c0(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=O$({symKey:c,encoded:s,encoding:o?.encoding});return fn(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Je(this,"getPayloadType",(i,s=kt)=>{const o=Ds({encoded:i,encoding:s});return En(o.type)}),Je(this,"getPayloadSenderPublicKey",(i,s=kt)=>{const o=Ds({encoded:i,encoding:s});return o.senderPublicKey?ut(o.senderPublicKey,nt):void 0}),this.core=e,this.logger=it(r,this.name),this.keychain=n||new US(this.core,this.logger)}get context(){return pt(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(X0)}catch{e=kl(),await this.keychain.set(X0,e)}return BS(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var qS=Object.defineProperty,zS=Object.defineProperties,HS=Object.getOwnPropertyDescriptors,Em=Object.getOwnPropertySymbols,VS=Object.prototype.hasOwnProperty,WS=Object.prototype.propertyIsEnumerable,cu=(t,e,r)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KS=(t,e)=>{for(var r in e||(e={}))VS.call(e,r)&&cu(t,r,e[r]);if(Em)for(var r of Em(e))WS.call(e,r)&&cu(t,r,e[r]);return t},GS=(t,e)=>zS(t,HS(e)),$t=(t,e,r)=>cu(t,typeof e!="symbol"?e+"":e,r);class ZS extends D6{constructor(e,r){super(e,r),this.logger=e,this.core=r,$t(this,"messages",new Map),$t(this,"messagesWithoutClientAck",new Map),$t(this,"name",kI),$t(this,"version",qI),$t(this,"initialized",!1),$t(this,"storagePrefix",nr),$t(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}}}),$t(this,"set",async(n,i,s)=>{this.isInitialized();const o=Qt(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===wa.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,GS(KS({},c),{[o]:i}))}return await this.persist(),o}),$t(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),$t(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}),$t(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Qt(i);return typeof s[o]<"u"}),$t(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Qt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),$t(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=it(e,this.name),this.core=r}get context(){return pt(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,dl(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,dl(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?fl(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?fl(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YS=Object.defineProperty,JS=Object.defineProperties,QS=Object.getOwnPropertyDescriptors,_m=Object.getOwnPropertySymbols,XS=Object.prototype.hasOwnProperty,eA=Object.prototype.propertyIsEnumerable,lu=(t,e,r)=>e in t?YS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ba=(t,e)=>{for(var r in e||(e={}))XS.call(e,r)&&lu(t,r,e[r]);if(_m)for(var r of _m(e))eA.call(e,r)&&lu(t,r,e[r]);return t},uu=(t,e)=>JS(t,QS(e)),Vt=(t,e,r)=>lu(t,typeof e!="symbol"?e+"":e,r);class tA extends T6{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Vt(this,"events",new Ve.exports.EventEmitter),Vt(this,"name",zI),Vt(this,"queue",new Map),Vt(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),Vt(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Vt(this,"needsTransportRestart",!1),Vt(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||em,c=ta(s),l=s?.prompt||!1,u=s?.tag||0,h=s?.id||xn().toString(),d={topic:n,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${u}`;try{const f=new Promise(async g=>{const m=({id:y})=>{d.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(Fe.publish,m),g(d))};this.relayer.events.on(Fe.publish,m);const w=kr(new Promise((y,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:l,tag:u,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(y).catch(_=>{this.logger.warn(_,_?.message),E(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${u}`);try{await w,this.events.removeListener(Fe.publish,m)}catch(y){this.queue.set(h,uu(ba({},d),{attempt:1})),this.logger.warn(y,y?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await kr(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),Vt(this,"on",(n,i)=>{this.events.on(n,i)}),Vt(this,"once",(n,i)=>{this.events.once(n,i)}),Vt(this,"off",(n,i)=>{this.events.off(n,i)}),Vt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=it(r,this.name),this.registerEventListeners()}get context(){return pt(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=em,prompt:l,tag:u,id:h,attestation:d,tvf:p}=e,f={method:Ts(ta().protocol).publish,params:ba({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:d},p),id:h};Ze((r=f.params)==null?void 0:r.prompt)&&((n=f.params)==null||delete n.prompt),Ze((i=f.params)==null?void 0:i.tag)&&((s=f.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const g=await this.relayer.request(f);return this.relayer.events.emit(Fe.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,uu(ba({},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(uu(ba({},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(vi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(Fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var rA=Object.defineProperty,nA=(t,e,r)=>e in t?rA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$i=(t,e,r)=>nA(t,typeof e!="symbol"?e+"":e,r);class iA{constructor(){$i(this,"map",new Map),$i(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),$i(this,"get",e=>this.map.get(e)||[]),$i(this,"exists",(e,r)=>this.get(e).includes(r)),$i(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)}),$i(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var sA=Object.defineProperty,oA=Object.defineProperties,aA=Object.getOwnPropertyDescriptors,$m=Object.getOwnPropertySymbols,cA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,hu=(t,e,r)=>e in t?sA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ws=(t,e)=>{for(var r in e||(e={}))cA.call(e,r)&&hu(t,r,e[r]);if($m)for(var r of $m(e))lA.call(e,r)&&hu(t,r,e[r]);return t},du=(t,e)=>oA(t,aA(e)),pe=(t,e,r)=>hu(t,typeof e!="symbol"?e+"":e,r);class uA extends B6{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,pe(this,"subscriptions",new Map),pe(this,"topicMap",new iA),pe(this,"events",new Ve.exports.EventEmitter),pe(this,"name",YI),pe(this,"version",JI),pe(this,"pending",new Map),pe(this,"cached",[]),pe(this,"initialized",!1),pe(this,"storagePrefix",nr),pe(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),pe(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),pe(this,"clientId"),pe(this,"batchSubscribeTopicsLimit",500),pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),pe(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=ta(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}}),pe(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),pe(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),pe(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),pe(this,"on",(n,i)=>{this.events.on(n,i)}),pe(this,"once",(n,i)=>{this.events.once(n,i)}),pe(this,"off",(n,i)=>{this.events.off(n,i)}),pe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),pe(this,"start",async()=>{await this.onConnect()}),pe(this,"stop",async()=>{await this.onDisconnect()}),pe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),pe(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)}),pe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(vi.pulse,async()=>{await this.checkPending()}),this.events.on(_t.created,async n=>{const i=_t.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(_t.deleted,async n=>{const i=_t.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=it(r,this.name),this.clientId=""}get context(){return pt(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=ta(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=he("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===ye.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Ts(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===ye.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},j.toMiliseconds(j.ONE_SECOND)),a;const c=new Promise(async u=>{const h=d=>{d.topic===e&&(this.events.removeListener(_t.created,h),u(d.id))};this.events.on(_t.created,h);try{const d=await kr(new Promise((p,f)=>{this.relayer.request(s).catch(g=>{this.logger.warn(g,g?.message),f(g)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(_t.created,h),u(d)}catch{}}),l=await kr(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(Fe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ts(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 kr(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(Fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Ts(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 kr(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(Fe.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Ts(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,du(Ws({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Ws({},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,Ws({},r)),this.topicMap.set(r.topic,e),this.events.emit(_t.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}=F("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(_t.deleted,du(Ws({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_t.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(_t.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=F("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=>du(Ws({},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 d4(j.toMiliseconds(j.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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Qt(e+await this.getClientId())}}var hA=Object.defineProperty,xm=Object.getOwnPropertySymbols,dA=Object.prototype.hasOwnProperty,fA=Object.prototype.propertyIsEnumerable,fu=(t,e,r)=>e in t?hA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Im=(t,e)=>{for(var r in e||(e={}))dA.call(e,r)&&fu(t,r,e[r]);if(xm)for(var r of xm(e))fA.call(e,r)&&fu(t,r,e[r]);return t},se=(t,e,r)=>fu(t,typeof e!="symbol"?e+"":e,r);class pA extends R6{constructor(e){super(e),se(this,"protocol","wc"),se(this,"version",2),se(this,"core"),se(this,"logger"),se(this,"events",new Ve.exports.EventEmitter),se(this,"provider"),se(this,"messages"),se(this,"subscriber"),se(this,"publisher"),se(this,"name",VI),se(this,"transportExplicitlyClosed",!1),se(this,"initialized",!1),se(this,"connectionAttemptInProgress",!1),se(this,"relayUrl"),se(this,"projectId"),se(this,"packageName"),se(this,"bundleId"),se(this,"hasExperiencedNetworkDisruption",!1),se(this,"pingTimeout"),se(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),se(this,"reconnectTimeout"),se(this,"connectPromise"),se(this,"reconnectInProgress",!1),se(this,"requestsInFlight",[]),se(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),se(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||xn().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}}),se(this,"resetPingTimeout",()=>{qo()&&(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))}),se(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),se(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Fe.connect)}),se(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),se(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Fe.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),se(this,"registerProviderListeners",()=>{this.provider.on(Tt.payload,this.onPayloadHandler),this.provider.on(Tt.connect,this.onConnectHandler),this.provider.on(Tt.disconnect,this.onDisconnectHandler),this.provider.on(Tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?it(e.logger,this.name):Xt(da({level:e.logger||HI})),this.messages=new ZS(this.logger,e.core),this.subscriber=new uA(this,this.logger),this.publisher=new tA(this,this.logger),this.relayUrl=e?.relayUrl||rm,this.projectId=e.projectId,Y5()?this.packageName=Yp():J5()&&(this.bundleId=Yp()),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 pt(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:ye.relay},wa.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(_t.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(_t.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,Im({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||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 kr(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 b0())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=Te(j.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Fe.message,e),await this.recordMessageEvent(e,wa.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(Tt.disconnect,s),await kr(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(Tt.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(Tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Tt.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,j.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(qo())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 Dt(new DI(r4({sdkVersion:iu,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}),nu(e)){if(!e.method.endsWith(WI))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:ye.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Im({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ga(e)&&this.events.emit(Fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,wa.inbound),this.events.emit(Fe.message,e))}async acknowledgePayload(e){const r=fa(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Tt.payload,this.onPayloadHandler),this.provider.off(Tt.connect,this.onConnectHandler),this.provider.off(Tt.disconnect,this.onDisconnectHandler),this.provider.off(Tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await b0();px(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(Fe.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},j.toMiliseconds(KI)))))}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function gA(){}function Om(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 Sm(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Am(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const mA="[object RegExp]",wA="[object String]",yA="[object Number]",bA="[object Boolean]",Cm="[object Arguments]",vA="[object Symbol]",EA="[object Date]",_A="[object Map]",$A="[object Set]",xA="[object Array]",IA="[object Function]",OA="[object ArrayBuffer]",pu="[object Object]",SA="[object Error]",AA="[object DataView]",CA="[object Uint8Array]",PA="[object Uint8ClampedArray]",DA="[object Uint16Array]",TA="[object Uint32Array]",RA="[object BigUint64Array]",NA="[object Int8Array]",BA="[object Int16Array]",LA="[object Int32Array]",MA="[object BigInt64Array]",UA="[object Float32Array]",jA="[object Float64Array]";function FA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function kA(t,e,r){return Ks(t,e,void 0,void 0,void 0,void 0,r)}function Ks(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 Gs(t,e,s,o)}return Gs(t,e,s,o)}function Gs(t,e,r,n){if(Object.is(t,e))return!0;let i=Am(t),s=Am(e);if(i===Cm&&(i=pu),s===Cm&&(s=pu),i!==s)return!1;switch(i){case wA:return t.toString()===e.toString();case yA:{const c=t.valueOf(),l=e.valueOf();return FA(c,l)}case bA:case EA:case vA:return Object.is(t.valueOf(),e.valueOf());case mA:return t.source===e.source&&t.flags===e.flags;case IA: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 _A:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Ks(l,e.get(c),c,t,e,r,n))return!1;return!0}case $A:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],d=l.findIndex(p=>Ks(h,p,void 0,t,e,r,n));if(d===-1)return!1;l.splice(d,1)}return!0}case xA:case CA:case PA:case DA:case TA:case RA:case NA:case BA:case LA:case MA:case UA:case jA:{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(!Ks(t[c],e[c],c,t,e,r,n))return!1;return!0}case OA:return t.byteLength!==e.byteLength?!1:Gs(new Uint8Array(t),new Uint8Array(e),r,n);case AA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Gs(new Uint8Array(t),new Uint8Array(e),r,n);case SA:return t.name===e.name&&t.message===e.message;case pu:{if(!(Gs(t.constructor,e.constructor,r,n)||Om(t)&&Om(e)))return!1;const c=[...Object.keys(t),...Sm(t)],l=[...Object.keys(e),...Sm(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Ks(d,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function qA(t,e){return kA(t,e,gA)}var zA=Object.defineProperty,Pm=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,VA=Object.prototype.propertyIsEnumerable,gu=(t,e,r)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dm=(t,e)=>{for(var r in e||(e={}))HA.call(e,r)&&gu(t,r,e[r]);if(Pm)for(var r of Pm(e))VA.call(e,r)&&gu(t,r,e[r]);return t},gt=(t,e,r)=>gu(t,typeof e!="symbol"?e+"":e,r);class An extends N6{constructor(e,r,n,i=nr,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,gt(this,"map",new Map),gt(this,"version",GI),gt(this,"cached",[]),gt(this,"initialized",!1),gt(this,"getKey"),gt(this,"storagePrefix",nr),gt(this,"recentlyDeleted",[]),gt(this,"recentlyDeletedLimit",200),gt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ze(o)?this.map.set(this.getKey(o),o):V$(o)?this.map.set(o.id,o):W$(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),gt(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())}),gt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),gt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>qA(a[c],o[c]))):this.values)),gt(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=Dm(Dm({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),gt(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=it(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return pt(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}=F("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=F("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}=F("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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WA=Object.defineProperty,KA=(t,e,r)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>KA(t,typeof e!="symbol"?e+"":e,r);class GA{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",QI),ee(this,"version",XI),ee(this,"events",new Ve.exports),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",nr),ee(this,"ignoredPayloadTypes",[$r]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),ee(this,"create",async n=>{this.isInitialized();const i=kl(),s=await this.core.crypto.setSymKey(i),o=Te(j.FIVE_MINUTES),a={protocol:tm},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},l=h0({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(In.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}}),ee(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[ir.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=u0(n.uri);i.props.properties.topic=s,i.addTrace(ir.pairing_uri_validation_success),i.addTrace(ir.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(ir.existing_pairing),u.active)throw i.setError(Or.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(ir.pairing_not_expired)}const h=c||Te(j.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(s,h),await this.pairings.set(s,d),i.addTrace(ir.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(In.create,d),i.addTrace(ir.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(ir.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Or.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(Or.subscribe_pairing_topic_failure),p}return i.addTrace(ir.subscribe_pairing_topic_success),d}),ee(this,"activate",async({topic:n})=>{this.isInitialized();const i=Te(j.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),ee(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}=mn();this.events.once(le("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),ee(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(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",he("USER_DISCONNECTED")),await this.deletePairing(i))}),ee(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return h0({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(n,i,s)=>{const o=Kr(i,s),a=await this.core.crypto.encode(n,o),c=qs[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),ee(this,"sendResult",async(n,i,s)=>{const o=fa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=qs[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(n,i,s)=>{const o=pa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=qs[c]?qs[c].res:qs.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,he("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),ee(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>qr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),ee(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)}}),ee(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)}}),ee(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(In.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{rr(i)?this.events.emit(le("pairing_ping",s),{}):Pt(i)&&this.events.emit(le("pairing_ping",s),{error:i.error})},500)}),ee(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(In.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=he("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)}}),ee(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(he("WC_METHOD_UNSUPPORTED",n))}),ee(this,"isValidPair",(n,i)=>{var s;if(!dt(n)){const{message:a}=F("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(Or.malformed_pairing_uri),new Error(a)}if(!H$(n.uri)){const{message:a}=F("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(Or.malformed_pairing_uri),new Error(a)}const o=u0(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Or.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Or.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Or.pairing_expired);const{message:a}=F("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async n=>{if(!dt(n)){const{message:s}=F("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),ee(this,"isValidDisconnect",async n=>{if(!dt(n)){const{message:s}=F("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),ee(this,"isValidPairingTopic",async n=>{if(!Ae(n,!1)){const{message:i}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(qr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=F("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=it(r,this.name),this.pairings=new An(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Fe.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==ye.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);nu(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ga(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(Rt.expired,async e=>{const{topic:r}=eg(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(In.expire,{topic:r}))})}}var ZA=Object.defineProperty,YA=(t,e,r)=>e in t?ZA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qe=(t,e,r)=>YA(t,typeof e!="symbol"?e+"":e,r);class JA extends P6{constructor(e,r){super(e,r),this.core=e,this.logger=r,Qe(this,"records",new Map),Qe(this,"events",new Ve.exports.EventEmitter),Qe(this,"name",eO),Qe(this,"version",tO),Qe(this,"cached",[]),Qe(this,"initialized",!1),Qe(this,"storagePrefix",nr),Qe(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)}),Qe(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:Te(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(zt.created,o)}),Qe(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=Pt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(zt.updated,i))}),Qe(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))),Qe(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(zt.deleted,s)}}),this.persist()}),Qe(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Qe(this,"on",(n,i)=>{this.events.on(n,i)}),Qe(this,"once",(n,i)=>{this.events.once(n,i)}),Qe(this,"off",(n,i)=>{this.events.off(n,i)}),Qe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=it(r,this.name)}get context(){return pt(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:Kr(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}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(zt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=F("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(zt.created,e=>{const r=zt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(zt.updated,e=>{const r=zt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(zt.deleted,e=>{const r=zt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(vi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{j.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(zt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var QA=Object.defineProperty,XA=(t,e,r)=>e in t?QA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,et=(t,e,r)=>XA(t,typeof e!="symbol"?e+"":e,r);class eC extends L6{constructor(e,r){super(e,r),this.core=e,this.logger=r,et(this,"expirations",new Map),et(this,"events",new Ve.exports.EventEmitter),et(this,"name",rO),et(this,"version",nO),et(this,"cached",[]),et(this,"initialized",!1),et(this,"storagePrefix",nr),et(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)}),et(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),et(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(Rt.created,{target:s,expiration:o})}),et(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),et(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(Rt.deleted,{target:i,expiration:s})}}),et(this,"on",(n,i)=>{this.events.on(n,i)}),et(this,"once",(n,i)=>{this.events.once(n,i)}),et(this,"off",(n,i)=>{this.events.off(n,i)}),et(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=it(r,this.name)}get context(){return pt(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 n4(e);if(typeof e=="number")return i4(e);const{message:r}=F("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(Rt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=F("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}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;j.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Rt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(vi.pulse,()=>this.checkExpirations()),this.events.on(Rt.created,e=>{const r=Rt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Rt.expired,e=>{const r=Rt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Rt.deleted,e=>{const r=Rt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var tC=Object.defineProperty,rC=(t,e,r)=>e in t?tC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ce=(t,e,r)=>rC(t,typeof e!="symbol"?e+"":e,r);class nC extends M6{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,Ce(this,"name",iO),Ce(this,"abortController"),Ce(this,"isDevEnv"),Ce(this,"verifyUrlV3",oO),Ce(this,"storagePrefix",nr),Ce(this,"version",Q0),Ce(this,"publicKey"),Ce(this,"fetchPromise"),Ce(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&j.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ce(this,"register",async i=>{if(!ys()||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=ss(),u=this.startAbortTimer(j.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",m),l.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",f,{signal:this.abortController.signal});const m=w=>{if(w.data&&typeof w.data=="string")try{const y=JSON.parse(w.data);if(y.type==="verify_attestation"){if(al(y.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",m),d(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};l.body.appendChild(g),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(l){this.logger.warn(l)}return""}),Ce(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(al(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)}),Ce(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(j.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}),Ce(this,"getVerifyUrl",i=>{let s=i||zs;return aO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${zs}`),s=zs),s}),Ce(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(j.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)}}),Ce(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ce(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ce(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")}}),Ce(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ce(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}),Ce(this,"validateAttestation",(i,s)=>{const o=D$(i,s.publicKey),a={hasExpired:j.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=it(r,this.name),this.abortController=new AbortController,this.isDevEnv=pl(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return pt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var iC=Object.defineProperty,sC=(t,e,r)=>e in t?iC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tm=(t,e,r)=>sC(t,typeof e!="symbol"?e+"":e,r);class oC extends U6{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Tm(this,"context",cO),Tm(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${lO}/${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=it(r,this.context)}}var aC=Object.defineProperty,Rm=Object.getOwnPropertySymbols,cC=Object.prototype.hasOwnProperty,lC=Object.prototype.propertyIsEnumerable,mu=(t,e,r)=>e in t?aC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zs=(t,e)=>{for(var r in e||(e={}))cC.call(e,r)&&mu(t,r,e[r]);if(Rm)for(var r of Rm(e))lC.call(e,r)&&mu(t,r,e[r]);return t},ke=(t,e,r)=>mu(t,typeof e!="symbol"?e+"":e,r);class uC extends j6{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,ke(this,"context",hO),ke(this,"storagePrefix",nr),ke(this,"storageVersion",uO),ke(this,"events",new Map),ke(this,"shouldPersist",!1),ke(this,"init",async()=>{if(!pl())try{const i={eventId:rg(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Qp(this.core.relayer.protocol,this.core.relayer.version,iu)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),ke(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=rg(),u=this.core.projectId||"",h=Date.now(),d=Zs({eventId:l,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),ke(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 Zs(Zs({},a),this.setMethods(a.eventId))}),ke(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),ke(this,"setEventListeners",()=>{this.core.heartbeat.on(vi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(i.timestamp)>dO&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),ke(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),ke(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)}),ke(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)}),ke(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ke(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,Zs(Zs({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),ke(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)}}),ke(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${fO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${iu}${s}`,{method:"POST",body:JSON.stringify(i)})}),ke(this,"getAppDomain",()=>Jp().url),this.logger=it(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 hC=Object.defineProperty,Nm=Object.getOwnPropertySymbols,dC=Object.prototype.hasOwnProperty,fC=Object.prototype.propertyIsEnumerable,wu=(t,e,r)=>e in t?hC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bm=(t,e)=>{for(var r in e||(e={}))dC.call(e,r)&&wu(t,r,e[r]);if(Nm)for(var r of Nm(e))fC.call(e,r)&&wu(t,r,e[r]);return t},we=(t,e,r)=>wu(t,typeof e!="symbol"?e+"":e,r);class yu extends O6{constructor(e){var r;super(e),we(this,"protocol",J0),we(this,"version",Q0),we(this,"name",ma),we(this,"relayUrl"),we(this,"projectId"),we(this,"customStoragePrefix"),we(this,"events",new Ve.exports.EventEmitter),we(this,"logger"),we(this,"heartbeat"),we(this,"relayer"),we(this,"crypto"),we(this,"storage"),we(this,"history"),we(this,"expirer"),we(this,"pairing"),we(this,"verify"),we(this,"echoClient"),we(this,"linkModeSupportedApps"),we(this,"eventClient"),we(this,"initialized",!1),we(this,"logChunkController"),we(this,"on",(a,c)=>this.events.on(a,c)),we(this,"once",(a,c)=>this.events.once(a,c)),we(this,"off",(a,c)=>this.events.off(a,c)),we(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),we(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:ye.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||rm,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=da({level:typeof e?.logger=="string"&&e.logger?e.logger:BI.logger,name:ma}),{logger:s,chunkLoggerController:o}=$6({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=it(s,this.name),this.heartbeat=new Wl,this.crypto=new kS(this,this.logger,e?.keychain),this.history=new JA(this,this.logger),this.expirer=new eC(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Zx(Bm(Bm({},LI),e?.storageOptions)),this.relayer=new pA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new GA(this,this.logger),this.verify=new nC(this,this.logger,this.storage),this.echoClient=new oC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new uC(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new yu(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(ZI,n),r}get context(){return pt(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(nm,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(nm)||[],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 pC=yu,Lm="wc",Mm=2,Um="client",bu=`${Lm}@${Mm}:${Um}:`,vu={name:Um,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},jm="WALLETCONNECT_DEEPLINK_CHOICE",gC="proposal",Fm="Proposal expired",mC="session",xi=j.SEVEN_DAYS,wC="engine",qe={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1114},res:{ttl:j.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:j.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:j.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1119}}},Eu={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},or={idle:"IDLE",active:"ACTIVE"},km={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},yC="request",bC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],vC="wc",EC="auth",_C="authKeys",$C="pairingTopics",xC="requests",va=`${vC}@${1.5}:${EC}:`,Ea=`${va}:PUB_KEY`;var IC=Object.defineProperty,OC=Object.defineProperties,SC=Object.getOwnPropertyDescriptors,qm=Object.getOwnPropertySymbols,AC=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,_u=(t,e,r)=>e in t?IC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e)=>{for(var r in e||(e={}))AC.call(e,r)&&_u(t,r,e[r]);if(qm)for(var r of qm(e))CC.call(e,r)&&_u(t,r,e[r]);return t},ot=(t,e)=>OC(t,SC(e)),L=(t,e,r)=>_u(t,typeof e!="symbol"?e+"":e,r);class PC extends z6{constructor(e){super(e),L(this,"name",wC),L(this,"events",new Ve.exports),L(this,"initialized",!1),L(this,"requestQueue",{state:or.idle,queue:[]}),L(this,"sessionRequestQueue",{state:or.idle,queue:[]}),L(this,"requestQueueDelay",j.ONE_SECOND),L(this,"expectedPairingMethodMap",new Map),L(this,"recentlyDeletedMap",new Map),L(this,"recentlyDeletedLimit",200),L(this,"relayMessageCache",[]),L(this,"pendingSessions",new Map),L(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(qe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay)))}),L(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=ot(ge({},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,h,d=!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."),d=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),S}if(!u||!d){const{topic:S,uri:x}=await this.client.core.pairing.create();u=S,h=x}if(!u){const{message:S}=F("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(S)}const p=await this.client.core.crypto.generateKeyPair(),f=qe.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,g=Te(f),m=ot(ge(ge({requiredNamespaces:s,optionalNamespaces:o,relays:l??[{protocol:tm}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:tr()}),w=le("session_connect",m.id),{reject:y,resolve:E,done:_}=mn(f,Fm),O=({id:S})=>{S===m.id&&(this.client.events.off("proposal_expire",O),this.pendingSessions.delete(m.id),this.events.emit(w,{error:{message:Fm,code:0}}))};return this.client.events.on("proposal_expire",O),this.events.once(w,({error:S,session:x})=>{this.client.events.off("proposal_expire",O),S?y(S):x&&E(x)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0,clientRpcId:m.id}),await this.setProposal(m.id,m),{uri:h,approval:_}}),L(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}}),L(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:[Ht.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch($){throw o.setError(On.no_internet_connection),$}try{await this.isValidProposalId(r?.id)}catch($){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(On.proposal_not_found),$}try{await this.isValidApprove(r)}catch($){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(On.session_approve_namespace_validation_failure),$}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:m,optionalNamespaces:w}=p;let y=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:f});y||(y=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ht.session_approve_started,properties:{topic:f,trace:[Ht.session_approve_started,Ht.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),_=g.publicKey,O=await this.client.core.crypto.generateSharedKey(E,_),S=ge(ge(ge({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:Te(xi)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),x=ye.relay;y.addTrace(Ht.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:x})}catch($){throw y.setError(On.subscribe_session_topic_failure),$}y.addTrace(Ht.subscribe_session_topic_success);const P=ot(ge({},S),{topic:O,requiredNamespaces:m,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:S.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:E,transportType:ye.relay});await this.client.session.set(O,P),y.addTrace(Ht.store_session);try{y.addTrace(Ht.publishing_session_settle),await this.sendRequest({topic:O,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch($=>{throw y?.setError(On.session_settle_publish_failure),$}),y.addTrace(Ht.session_settle_publish_success),y.addTrace(Ht.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch($=>{throw y?.setError(On.session_approve_publish_failure),$}),y.addTrace(Ht.session_approve_publish_success)}catch($){throw this.client.logger.error($),this.client.session.delete(O,he("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),$}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.client.proposal.delete(a,he("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(O,Te(xi)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),L(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:qe.wc_sessionPropose.reject}),await this.client.proposal.delete(n,he("USER_DISCONNECTED")))}),L(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=mn(),c=tr(),l=xn().toString(),u=this.client.session.get(n).namespaces;return this.events.once(le("session_update",c),({error:h})=>{h?a(h):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(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:u}),a(h)}),{acknowledged:s}}),L(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=tr(),{done:s,resolve:o,reject:a}=mn();return this.events.once(le("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,Te(xi)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),L(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=qe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===ye.relay&&await this.confirmOnlineStateOrThrow();const c=tr(),l=xn().toString(),{done:u,resolve:h,reject:d}=mn(o,"Request expired. Please try again.");this.events.once(le("session_request",c),({error:w,result:y})=>{w?d(w):h(y)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:p,params:{request:ot(ge({},i),{expiryTimestamp:Te(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await u();const g={request:ot(ge({},i),{expiryTimestamp:Te(o)}),chainId:n},m=this.shouldSetTVF(p,g);return await Promise.all([new Promise(async w=>{await this.sendRequest(ge({clientRpcId:c,relayRpcId:l,topic:s,method:p,params:g,expiry:o,throwOnFailedPublish:!0},m&&{tvf:this.getTVFParams(c,g)})).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const E=await c4(this.client.core.storage,jm);await s4({id:c,topic:s,wcDeepLink:E})}w()}),u()]).then(w=>w[2])}),L(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===ye.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);rr(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):Pt(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),L(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=tr(),s=xn().toString(),{done:o,resolve:a,reject:c}=mn();this.events.once(le("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}))}),L(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=xn().toString(),a=tr();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),L(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:he("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}=F("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),L(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>q$(n,r)))),L(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),L(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?ye.link_mode:ye.relay;o===ye.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:d,exp:p,nbf:f,methods:g=[],expiry:m}=r,w=[...r.resources||[]],{topic:y,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:E}});const _=await this.client.core.crypto.generateKeyPair(),O=ea(_);if(await Promise.all([this.client.auth.authKeys.set(Ea,{responseTopic:O,publicKey:_}),this.client.auth.pairingTopics.set(O,{topic:O,pairingTopic:y})]),await this.client.core.relayer.subscribe(O,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),g.length>0){const{namespace:C}=oi(a[0]);let N=X4(C,"request",g);Wo(w)&&(N=t8(N,w.pop())),w.push(N)}const S=m&&m>qe.wc_sessionAuthenticate.req.ttl?m:qe.wc_sessionAuthenticate.req.ttl,x={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(S)},P={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:P,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(qe.wc_sessionPropose.req.ttl),id:tr()},{done:B,resolve:D,reject:R}=mn(S,"Request expired"),M=tr(),A=le("session_connect",$.id),b=le("session_request",M),v=async({error:C,session:N})=>{this.events.off(b,I),C?R(C):N&&D({session:N})},I=async C=>{var N,U,k;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),C.error){const Q=he("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===Q.code?void 0:(this.events.off(A,v),R(C.error.message))}await this.deleteProposal($.id),this.events.off(A,v);const{cacaos:H,responder:q}=C.result,W=[],G=[];for(const Q of H){await wg({cacao:Q,projectId:this.client.core.projectId})||(this.client.logger.error(Q,"Signature verification failed"),R(he("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Se}=Q,ve=Wo(Se.resources),_e=[vl(Se.iss)],He=Vo(Se.iss);if(ve){const Pe=vg(ve),Pr=Eg(ve);W.push(...Pe),_e.push(...Pr)}for(const Pe of _e)G.push(`${Pe}:${He}`)}const ce=await this.client.core.crypto.generateSharedKey(_,q.publicKey);let X;W.length>0&&(X={topic:ce,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:Te(xi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:d0([...new Set(W)],[...new Set(G)]),transportType:o},await this.client.core.relayer.subscribe(ce,{transportType:o}),await this.client.session.set(ce,X),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:q.metadata}),X=this.client.session.get(ce)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(U=q.metadata.redirect)!=null&&U.linkMode&&(k=q.metadata.redirect)!=null&&k.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ce,{transportType:ye.link_mode})),D({auths:H,session:X})};this.events.once(A,v),this.events.once(b,I);let T;try{if(s){const C=Kr("wc_sessionAuthenticate",x,M);this.client.core.history.set(y,C);const N=await this.client.core.crypto.encode("",C,{type:Cs,encoding:Wr});T=ra(n,y,N)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:x,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:$,expiry:qe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(C){throw this.events.off(A,v),this.events.off(b,I),C}return await this.setProposal($.id,$),await this.setAuthRequest(M,{request:ot(ge({},x),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:T??E,response:B}}),L(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Sn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw s.setError(Hs.no_internet_connection),m}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Hs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ye.relay;a===ye.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=ea(c),h={type:$r,receiverPublicKey:c,senderPublicKey:l},d=[],p=[];for(const m of i){if(!await wg({cacao:m,projectId:this.client.core.projectId})){s.setError(Hs.invalid_cacao);const O=he("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:O,encodeOpts:h}),new Error(O.message)}s.addTrace(Sn.cacaos_verified);const{p:w}=m,y=Wo(w.resources),E=[vl(w.iss)],_=Vo(w.iss);if(y){const O=vg(y),S=Eg(y);d.push(...O),E.push(...S)}for(const O of E)p.push(`${O}:${_}`)}const f=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Sn.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:f,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Te(xi),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:d0([...new Set(d)],[...new Set(p)]),transportType:a},s.addTrace(Sn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(m){throw s.setError(Hs.subscribe_authenticated_session_topic_failure),m}s.addTrace(Sn.subscribe_authenticated_session_topic_success),await this.client.session.set(f,g),s.addTrace(Sn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Sn.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw s.setError(Hs.authenticated_session_approve_publish_failure),m}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:g}}),L(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===ye.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ea(o),l={type:$r,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:l,rpcOpts:qe.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,he("USER_DISCONNECTED"))}),L(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return yg(n,i)}),L(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)}),L(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)}}),L(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,he("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(jm).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,he("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=or.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),L(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(On.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,he("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),L(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=or.idle,this.client.events.emit("session_request_expire",{id:r}))}),L(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)])}),L(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}))}),L(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,Te(qe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),L(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=ye.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})}),L(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||Te(qe.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})}),L(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h}=r,d=Kr(i,s,c);let p;const f=!!u;try{const w=f?Wr:kt;p=await this.client.core.crypto.encode(n,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),w}let g;if(bC.includes(i)){const w=Qt(JSON.stringify(d)),y=Qt(p);g=await this.client.core.verify.register({id:y,decryptedId:w})}const m=qe[i].req;if(m.attestation=g,o&&(m.ttl=o),a&&(m.id=a),this.client.core.history.set(n,d),f){const w=ra(u,n,p);await global.Linking.openURL(w,this.client.name)}else{const w=qe[i].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=ot(ge({},h),{correlationId:d.id}),l?(w.internal=ot(ge({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,w)):this.client.core.relayer.publish(n,p,w).catch(y=>this.client.logger.error(y))}return d.id}),L(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=fa(n,s);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?Wr:kt;u=await this.client.core.crypto.encode(i,l,ot(ge({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),f}let d,p;try{d=await this.client.core.history.get(i,n);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(n,f.params,s))}catch(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),f}if(h){const f=ra(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,g=qe[f].res;g.tvf=ot(ge({},p),{correlationId:n}),o?(g.internal=ot(ge({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(l)}),L(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=pa(n,s);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?Wr:kt;u=await this.client.core.crypto.encode(i,l,ot(ge({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=ra(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||qe[p].res;this.client.core.relayer.publish(i,u,f)}await this.client.core.history.resolve(l)}),L(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;qr(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=>{qr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),L(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),L(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),L(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===or.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=or.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=or.idle}),L(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}`)}}),L(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}`)}}),L(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=F("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),L(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)}),L(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(Or.proposal_listener_not_found)),this.isValidConnect(ge({},i.params));const u=a.expiryTimestamp||Te(qe.wc_sessionPropose.req.ttl),h=ge({id:c,pairingTopic:n,expiryTimestamp:u},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:Qt(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(ir.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:qe.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),L(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(rr(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 h=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(Pt(n)){await this.client.proposal.delete(s,he("USER_DISCONNECTED"));const o=le("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})}}),L(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:h,sessionConfig:d}=n.params,p=[...this.pendingSessions.values()].find(m=>m.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const f=this.client.proposal.get(p.proposalId),g=ot(ge(ge(ge({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:ye.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(le("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),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)}}),L(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;rr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(le("session_approve",i),{})):Pt(n)&&(await this.client.session.delete(r,he("USER_DISCONNECTED")),this.events.emit(le("session_approve",i),{error:n.error}))}),L(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Bs.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:he("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ge({topic:r},i));try{Bs.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 Bs.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)}}),L(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),L(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=le("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);rr(n)?this.events.emit(le("session_update",i),{}):Pt(n)&&this.events.emit(le("session_update",i),{error:n.error})}),L(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Te(xi)),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)}}),L(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=le("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);rr(n)?this.events.emit(le("session_extend",i),{}):Pt(n)&&this.events.emit(le("session_extend",i),{error:n.error})}),L(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)}}),L(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=le("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);rr(n)?this.events.emit(le("session_ping",i),{}):Pt(n)&&this.events.emit(le("session_ping",i),{error:n.error})},500)}),L(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(Fe.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:he("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),L(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:h,params:d}=a;try{await this.isValidRequest(ge({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:Qt(JSON.stringify(Kr("wc_sessionRequest",d,h))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),g={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(g),u===ye.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),L(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=le("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);rr(n)?this.events.emit(le("session_request",i),{result:n.result}):Pt(n)&&this.events.emit(le("session_request",i),{error:n.error})}),L(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Bs.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ge({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Bs.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),L(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),rr(n)?this.events.emit(le("session_request",i),{result:n.result}):Pt(n)&&this.events.emit(le("session_request",i),{error:n.error})}),L(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:h}=s.params,d=await this.getVerifyContext({attestationId:o,hash:Qt(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===ye.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:d})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:$r,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:p,rpcOpts:qe.wc_sessionAuthenticate.autoReject,appLink:d})}}),L(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),L(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=or.idle,this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay))}),L(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=le("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(le("session_request",s.request.id),{error:n})})}),L(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===or.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=or.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),L(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),L(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:Kr("wc_sessionPropose",ot(ge({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),L(this,"isValidConnect",async r=>{if(!dt(r)){const{message:l}=F("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(Ze(n)||await this.isValidPairingTopic(n),!ex(c,!0)){const{message:l}=F("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Ze(i)&&Ns(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Ze(s)&&Ns(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Ze(o)||this.validateSessionProps(o,"sessionProperties"),!Ze(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)}`)}}),L(this,"validateNamespaces",(r,n)=>{const i=X$(r,"connect()",n);if(i)throw new Error(i.message)}),L(this,"isValidApprove",async r=>{if(!dt(r))throw new Error(F("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=Hl(i,"approve()");if(l)throw new Error(l.message);const u=w0(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!Ae(s,!0)){const{message:h}=F("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Ze(o)||this.validateSessionProps(o,"sessionProperties"),!Ze(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),L(this,"isValidReject",async r=>{if(!dt(r)){const{message:s}=F("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!rx(i)){const{message:s}=F("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),L(this,"isValidSessionSettleRequest",r=>{if(!dt(r)){const{message:l}=F("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!g0(n)){const{message:l}=F("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=K$(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Hl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qr(o)){const{message:l}=F("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),L(this,"isValidUpdate",async r=>{if(!dt(r)){const{message:c}=F("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=Hl(i,"update()");if(o)throw new Error(o.message);const a=w0(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),L(this,"isValidExtend",async r=>{if(!dt(r)){const{message:i}=F("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),L(this,"isValidRequest",async r=>{if(!dt(r)){const{message:c}=F("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(!m0(a,s)){const{message:c}=F("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!nx(i)){const{message:c}=F("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!ox(a,s,i.method)){const{message:c}=F("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!ux(o,Eu)){const{message:c}=F("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Eu.min} and ${Eu.max}`);throw new Error(c)}}),L(this,"isValidRespond",async r=>{var n;if(!dt(r)){const{message:o}=F("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(!ix(s)){const{message:o}=F("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),L(this,"isValidPing",async r=>{if(!dt(r)){const{message:i}=F("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),L(this,"isValidEmit",async r=>{if(!dt(r)){const{message:a}=F("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(!m0(o,s)){const{message:a}=F("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!sx(i)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!ax(o,s,i.name)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),L(this,"isValidDisconnect",async r=>{if(!dt(r)){const{message:i}=F("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),L(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(!Ae(i,!1))throw new Error("uri is required parameter");if(!Ae(s,!1))throw new Error("domain is required parameter");if(!Ae(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>oi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=oi(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),L(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||zs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ye.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}),L(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=F("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),L(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),L(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)}}}),L(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=F("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),L(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,l,u,h,d;return!r||n!==ye.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&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),L(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),L(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=tg(r,"topic")||"",i=decodeURIComponent(tg(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:ye.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),L(this,"registerLinkModeListeners",async()=>{var r;if(pl()||Fr()&&(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)}}}),L(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(km).includes(i.method)}),L(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return ot(ge({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{}}),L(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}),L(this,"extractTxHashesFromResult",(r,n)=>{try{const i=km[r];if(typeof n=="string")return[n];const s=n[i.key];if(qt(s))return r==="solana_signAllTransactions"?s.map(o=>j4(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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Fe.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(Ea)?this.client.auth.authKeys.get(Ea):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===ye.link_mode?Wr:kt});nu(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Qt(n)})):ga(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(Rt.expired,async e=>{const{topic:r,id:n}=eg(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,F("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,F("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(In.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(In.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ae(e,!1)){const{message:r}=F("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}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=F("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ae(e,!1)){const{message:r}=F("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}=F("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=F("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=F("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(Ae(e,!1)){const{message:r}=F("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=F("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!tx(e)){const{message:r}=F("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=F("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=F("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class DC extends An{constructor(e,r){super(e,r,gC,bu),this.core=e,this.logger=r}}class TC extends An{constructor(e,r){super(e,r,mC,bu),this.core=e,this.logger=r}}class RC extends An{constructor(e,r){super(e,r,yC,bu,n=>n.id),this.core=e,this.logger=r}}class NC extends An{constructor(e,r){super(e,r,_C,va,()=>Ea),this.core=e,this.logger=r}}class BC extends An{constructor(e,r){super(e,r,$C,va),this.core=e,this.logger=r}}class LC extends An{constructor(e,r){super(e,r,xC,va,n=>n.id),this.core=e,this.logger=r}}var MC=Object.defineProperty,UC=(t,e,r)=>e in t?MC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$u=(t,e,r)=>UC(t,typeof e!="symbol"?e+"":e,r);class jC{constructor(e,r){this.core=e,this.logger=r,$u(this,"authKeys"),$u(this,"pairingTopics"),$u(this,"requests"),this.authKeys=new NC(this.core,this.logger),this.pairingTopics=new BC(this.core,this.logger),this.requests=new LC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var FC=Object.defineProperty,kC=(t,e,r)=>e in t?FC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>kC(t,typeof e!="symbol"?e+"":e,r);class xu extends q6{constructor(e){super(e),te(this,"protocol",Lm),te(this,"version",Mm),te(this,"name",vu.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new Ve.exports.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(n,i)=>this.events.on(n,i)),te(this,"once",(n,i)=>this.events.once(n,i)),te(this,"off",(n,i)=>this.events.off(n,i)),te(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),te(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),te(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),te(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),te(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||vu.name,this.metadata=X5(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xt(da({level:e?.logger||vu.logger}));this.core=e?.core||new pC(e),this.logger=it(r,this.name),this.session=new TC(this.core,this.logger),this.proposal=new DC(this.core,this.logger),this.pendingRequest=new RC(this.core,this.logger),this.engine=new PC(this),this.auth=new jC(this.core,this.logger)}static async init(e){const r=new xu(e);return await r.initialize(),r}get context(){return pt(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()},j.toMiliseconds(j.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Iu={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof ct<"u"&&ct,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 ct<"u"&&ct||{},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(b){return b&&DataView.prototype.isPrototypeOf(b)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(b){return b&&u.indexOf(Object.prototype.toString.call(b))>-1};function d(b){if(typeof b!="string"&&(b=String(b)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(b)||b==="")throw new TypeError('Invalid character in header field name: "'+b+'"');return b.toLowerCase()}function p(b){return typeof b!="string"&&(b=String(b)),b}function f(b){var v={next:function(){var I=b.shift();return{done:I===void 0,value:I}}};return c.iterable&&(v[Symbol.iterator]=function(){return v}),v}function g(b){this.map={},b instanceof g?b.forEach(function(v,I){this.append(I,v)},this):Array.isArray(b)?b.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):b&&Object.getOwnPropertyNames(b).forEach(function(v){this.append(v,b[v])},this)}g.prototype.append=function(b,v){b=d(b),v=p(v);var I=this.map[b];this.map[b]=I?I+", "+v:v},g.prototype.delete=function(b){delete this.map[d(b)]},g.prototype.get=function(b){return b=d(b),this.has(b)?this.map[b]:null},g.prototype.has=function(b){return this.map.hasOwnProperty(d(b))},g.prototype.set=function(b,v){this.map[d(b)]=p(v)},g.prototype.forEach=function(b,v){for(var I in this.map)this.map.hasOwnProperty(I)&&b.call(v,this.map[I],I,this)},g.prototype.keys=function(){var b=[];return this.forEach(function(v,I){b.push(I)}),f(b)},g.prototype.values=function(){var b=[];return this.forEach(function(v){b.push(v)}),f(b)},g.prototype.entries=function(){var b=[];return this.forEach(function(v,I){b.push([I,v])}),f(b)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function m(b){if(!b._noBody){if(b.bodyUsed)return Promise.reject(new TypeError("Already read"));b.bodyUsed=!0}}function w(b){return new Promise(function(v,I){b.onload=function(){v(b.result)},b.onerror=function(){I(b.error)}})}function y(b){var v=new FileReader,I=w(v);return v.readAsArrayBuffer(b),I}function E(b){var v=new FileReader,I=w(v),T=/charset=([A-Za-z0-9_-]+)/.exec(b.type),C=T?T[1]:"utf-8";return v.readAsText(b,C),I}function _(b){for(var v=new Uint8Array(b),I=new Array(v.length),T=0;T<v.length;T++)I[T]=String.fromCharCode(v[T]);return I.join("")}function O(b){if(b.slice)return b.slice(0);var v=new Uint8Array(b.byteLength);return v.set(new Uint8Array(b)),v.buffer}function S(){return this.bodyUsed=!1,this._initBody=function(b){this.bodyUsed=this.bodyUsed,this._bodyInit=b,b?typeof b=="string"?this._bodyText=b:c.blob&&Blob.prototype.isPrototypeOf(b)?this._bodyBlob=b:c.formData&&FormData.prototype.isPrototypeOf(b)?this._bodyFormData=b:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(b)?this._bodyText=b.toString():c.arrayBuffer&&c.blob&&l(b)?(this._bodyArrayBuffer=O(b.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(b)||h(b))?this._bodyArrayBuffer=O(b):this._bodyText=b=Object.prototype.toString.call(b):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof b=="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(b)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var b=m(this);if(b)return b;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 b=m(this);return b||(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(y);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var b=m(this);if(b)return b;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(_(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(B)}),this.json=function(){return this.text().then(JSON.parse)},this}var x=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function P(b){var v=b.toUpperCase();return x.indexOf(v)>-1?v:b}function $(b,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 I=v.body;if(b instanceof $){if(b.bodyUsed)throw new TypeError("Already read");this.url=b.url,this.credentials=b.credentials,v.headers||(this.headers=new g(b.headers)),this.method=b.method,this.mode=b.mode,this.signal=b.signal,!I&&b._bodyInit!=null&&(I=b._bodyInit,b.bodyUsed=!0)}else this.url=String(b);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new g(v.headers)),this.method=P(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal||function(){if("AbortController"in a){var N=new AbortController;return N.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(v.cache==="no-store"||v.cache==="no-cache")){var T=/([?&])_=[^&]*/;if(T.test(this.url))this.url=this.url.replace(T,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function B(b){var v=new FormData;return b.trim().split("&").forEach(function(I){if(I){var T=I.split("="),C=T.shift().replace(/\+/g," "),N=T.join("=").replace(/\+/g," ");v.append(decodeURIComponent(C),decodeURIComponent(N))}}),v}function D(b){var v=new g,I=b.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(T){return T.indexOf(`
40
40
  `)===0?T.substr(1,T.length):T}).forEach(function(T){var C=T.split(":"),N=C.shift().trim();if(N){var U=C.join(":").trim();try{v.append(N,U)}catch(k){console.warn("Response "+k.message)}}}),v}S.call($.prototype);function R(b,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 g(v.headers),this.url=v.url||"",this._initBody(b)}S.call(R.prototype),R.prototype.clone=function(){return new R(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},R.error=function(){var b=new R(null,{status:200,statusText:""});return b.ok=!1,b.status=0,b.type="error",b};var M=[301,302,303,307,308];R.redirect=function(b,v){if(M.indexOf(v)===-1)throw new RangeError("Invalid status code");return new R(null,{status:v,headers:{location:b}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(v,I){this.message=v,this.name=I;var T=Error(v);this.stack=T.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function A(b,v){return new Promise(function(I,T){var C=new $(b,v);if(C.signal&&C.signal.aborted)return T(new o.DOMException("Aborted","AbortError"));var N=new XMLHttpRequest;function U(){N.abort()}N.onload=function(){var q={statusText:N.statusText,headers:D(N.getAllResponseHeaders()||"")};C.url.indexOf("file://")===0&&(N.status<200||N.status>599)?q.status=200:q.status=N.status,q.url="responseURL"in N?N.responseURL:q.headers.get("X-Request-URL");var W="response"in N?N.response:N.responseText;setTimeout(function(){I(new R(W,q))},0)},N.onerror=function(){setTimeout(function(){T(new TypeError("Network request failed"))},0)},N.ontimeout=function(){setTimeout(function(){T(new TypeError("Network request timed out"))},0)},N.onabort=function(){setTimeout(function(){T(new o.DOMException("Aborted","AbortError"))},0)};function k(q){try{return q===""&&a.location.href?a.location.href:q}catch{return q}}if(N.open(C.method,k(C.url),!0),C.credentials==="include"?N.withCredentials=!0:C.credentials==="omit"&&(N.withCredentials=!1),"responseType"in N&&(c.blob?N.responseType="blob":c.arrayBuffer&&(N.responseType="arraybuffer")),v&&typeof v.headers=="object"&&!(v.headers instanceof g||a.Headers&&v.headers instanceof a.Headers)){var H=[];Object.getOwnPropertyNames(v.headers).forEach(function(q){H.push(d(q)),N.setRequestHeader(q,p(v.headers[q]))}),C.headers.forEach(function(q,W){H.indexOf(W)===-1&&N.setRequestHeader(W,q)})}else C.headers.forEach(function(q,W){N.setRequestHeader(W,q)});C.signal&&(C.signal.addEventListener("abort",U),N.onreadystatechange=function(){N.readyState===4&&C.signal.removeEventListener("abort",U)}),N.send(typeof C._bodyInit>"u"?null:C._bodyInit)})}return A.polyfill=!0,a.fetch||(a.fetch=A,a.Headers=g,a.Request=$,a.Response=R),o.Headers=g,o.Request=$,o.Response=R,o.fetch=A,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})(Iu,Iu.exports);var zm=ty(Iu.exports),qC=Object.defineProperty,zC=Object.defineProperties,HC=Object.getOwnPropertyDescriptors,Hm=Object.getOwnPropertySymbols,VC=Object.prototype.hasOwnProperty,WC=Object.prototype.propertyIsEnumerable,Vm=(t,e,r)=>e in t?qC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wm=(t,e)=>{for(var r in e||(e={}))VC.call(e,r)&&Vm(t,r,e[r]);if(Hm)for(var r of Hm(e))WC.call(e,r)&&Vm(t,r,e[r]);return t},Km=(t,e)=>zC(t,HC(e));const KC={Accept:"application/json","Content-Type":"application/json"},GC="POST",Gm={headers:KC,method:GC},Zm=10;class Wt{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Ve.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!H0(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=gr(e),n=await(await zm(this.url,Km(Wm({},Gm),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!H0(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=gr({id:1,jsonrpc:"2.0",method:"test",params:[]});await zm(e,Km(Wm({},Gm),{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"?fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=pa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return U0(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Zm&&this.events.setMaxListeners(Zm)}}var ZC=Object.defineProperty,Ym=Object.getOwnPropertySymbols,YC=Object.prototype.hasOwnProperty,JC=Object.prototype.propertyIsEnumerable,Jm=(t,e,r)=>e in t?ZC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qm=(t,e)=>{for(var r in e||(e={}))YC.call(e,r)&&Jm(t,r,e[r]);if(Ym)for(var r of Ym(e))JC.call(e,r)&&Jm(t,r,e[r]);return t};const Xm="error",QC="wss://relay.walletconnect.org",XC="wc",eP="universal_provider",_a=`${XC}@2:${eP}:`,e1="https://rpc.walletconnect.org/v1/",Ii="generic",tP=`${e1}bundler`,Nt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function rP(){}function Ou(t){return t==null||typeof t!="object"&&typeof t!="function"}function Su(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function nP(t){if(Ou(t))return t;if(Array.isArray(t)||Su(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 t1(t){return typeof t=="object"&&t!==null}function r1(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function n1(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const iP="[object RegExp]",i1="[object String]",s1="[object Number]",o1="[object Boolean]",a1="[object Arguments]",sP="[object Symbol]",oP="[object Date]",aP="[object Map]",cP="[object Set]",lP="[object Array]",uP="[object ArrayBuffer]",hP="[object Object]",dP="[object DataView]",fP="[object Uint8Array]",pP="[object Uint8ClampedArray]",gP="[object Uint16Array]",mP="[object Uint32Array]",wP="[object Int8Array]",yP="[object Int16Array]",bP="[object Int32Array]",vP="[object Float32Array]",EP="[object Float64Array]";function _P(t,e){return Oi(t,void 0,t,new Map,e)}function Oi(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(Ou(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]=Oi(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,Oi(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(Oi(a,void 0,r,n,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Su(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Oi(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),Cn(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),Cn(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),Cn(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,Cn(o,t,r,n,i),o}if(typeof t=="object"&&$P(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),Cn(o,t,r,n,i),o}return t}function Cn(t,e,r=t,n,i){const s=[...Object.keys(e),...r1(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Oi(e[a],a,r,n,i))}}function $P(t){switch(n1(t)){case a1:case lP:case uP:case dP:case o1:case oP:case vP:case EP:case wP:case yP:case bP:case aP:case s1:case hP:case iP:case cP:case i1:case sP:case fP:case pP:case gP:case mP:return!0;default:return!1}}function xP(t,e){return _P(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 s1:case i1:case o1:{const a=new t.constructor(t?.valueOf());return Cn(a,t),a}case a1:{const a={};return Cn(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function c1(t){return xP(t)}function l1(t){return t!==null&&typeof t=="object"&&n1(t)==="[object Arguments]"}function IP(t){return Su(t)}function OP(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 SP(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=Au(i,o,n,new Map)}return i}function Au(t,e,r,n){var i;if(Ou(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return nP(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),...r1(e)];for(let o=0;o<s.length;o++){const a=s[o];let c=e[a],l=t[a];if(l1(c)&&(c=Qm({},c)),l1(l)&&(l=Qm({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=c1(c)),Array.isArray(c))if(typeof l=="object"&&l!=null){const h=[],d=Reflect.ownKeys(l);for(let p=0;p<d.length;p++){const f=d[p];h[f]=l[f]}l=h}else l=[];const u=r(l,c,a,t,e,n);u!=null?t[a]=u:Array.isArray(c)||t1(l)&&t1(c)?t[a]=Au(l,c,r,n):l==null&&OP(c)?t[a]=Au({},c,r,n):l==null&&IP(c)?t[a]=c1(c):(l===void 0||c!==void 0)&&(t[a]=c)}return t}function AP(t,...e){return SP(t,...e,rP)}var CP=Object.defineProperty,PP=Object.defineProperties,DP=Object.getOwnPropertyDescriptors,u1=Object.getOwnPropertySymbols,TP=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,h1=(t,e,r)=>e in t?CP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$a=(t,e)=>{for(var r in e||(e={}))TP.call(e,r)&&h1(t,r,e[r]);if(u1)for(var r of u1(e))RP.call(e,r)&&h1(t,r,e[r]);return t},NP=(t,e)=>PP(t,DP(e));function xt(t,e,r){var n;const i=oi(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${e1}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Pn(t){return t.includes(":")?t.split(":")[1]:t}function d1(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function BP(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 Cu(t={},e={}){const r=f1(t),n=f1(e);return AP(r,n)}function f1(t){var e,r,n,i;const s={};if(!Ns(t))return s;for(const[o,a]of Object.entries(t)){const c=ql(o)?[o]:a.chains,l=a.methods||[],u=a.events||[],h=a.rpcMap||{},d=Rs(o);s[d]=NP($a($a({},s[d]),a),{chains:zo(c,(e=s[d])==null?void 0:e.chains),methods:zo(l,(r=s[d])==null?void 0:r.methods),events:zo(u,(n=s[d])==null?void 0:n.events),rpcMap:$a($a({},h),(i=s[d])==null?void 0:i.rpcMap)})}return s}function p1(t){return t.includes(":")?t.split(":")[2]:t}function g1(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=ql(r)?[r]:n.chains?n.chains:d1(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function Pu(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 m1={},oe=t=>m1[t],Du=(t,e)=>{m1[t]=e};var LP=Object.defineProperty,MP=(t,e,r)=>e in t?LP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Si=(t,e,r)=>MP(t,typeof e!="symbol"?e+"":e,r);class UP{constructor(e){Si(this,"name","polkadot"),Si(this,"client"),Si(this,"httpProviders"),Si(this,"events"),Si(this,"namespace"),Si(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=Pn(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||xt(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("disableProviderPing")))}}var jP=Object.defineProperty,FP=Object.defineProperties,kP=Object.getOwnPropertyDescriptors,w1=Object.getOwnPropertySymbols,qP=Object.prototype.hasOwnProperty,zP=Object.prototype.propertyIsEnumerable,Tu=(t,e,r)=>e in t?jP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,y1=(t,e)=>{for(var r in e||(e={}))qP.call(e,r)&&Tu(t,r,e[r]);if(w1)for(var r of w1(e))zP.call(e,r)&&Tu(t,r,e[r]);return t},b1=(t,e)=>FP(t,kP(e)),Ai=(t,e,r)=>Tu(t,typeof e!="symbol"?e+"":e,r);class HP{constructor(e){Ai(this,"name","eip155"),Ai(this,"client"),Ai(this,"chainId"),Ai(this,"namespace"),Ai(this,"httpProviders"),Ai(this,"events"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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||xt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("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(Pn(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:b1(y1({},o.sessionProperties||{}),{capabilities:b1(y1({},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(Kr("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`${tP}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var VP=Object.defineProperty,WP=(t,e,r)=>e in t?VP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ci=(t,e,r)=>WP(t,typeof e!="symbol"?e+"":e,r);class KP{constructor(e){Ci(this,"name","solana"),Ci(this,"client"),Ci(this,"httpProviders"),Ci(this,"events"),Ci(this,"namespace"),Ci(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=Pn(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||xt(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("disableProviderPing")))}}var GP=Object.defineProperty,ZP=(t,e,r)=>e in t?GP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pi=(t,e,r)=>ZP(t,typeof e!="symbol"?e+"":e,r);class YP{constructor(e){Pi(this,"name","cosmos"),Pi(this,"client"),Pi(this,"httpProviders"),Pi(this,"events"),Pi(this,"namespace"),Pi(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=Pn(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||xt(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("disableProviderPing")))}}var JP=Object.defineProperty,QP=(t,e,r)=>e in t?JP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Di=(t,e,r)=>QP(t,typeof e!="symbol"?e+"":e,r);class XP{constructor(e){Di(this,"name","algorand"),Di(this,"client"),Di(this,"httpProviders"),Di(this,"events"),Di(this,"namespace"),Di(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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||xt(`${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(Nt.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||xt(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new Dt(new Wt(n,oe("disableProviderPing")))}}var e7=Object.defineProperty,t7=(t,e,r)=>e in t?e7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ti=(t,e,r)=>t7(t,typeof e!="symbol"?e+"":e,r);class r7{constructor(e){Ti(this,"name","cip34"),Ti(this,"client"),Ti(this,"httpProviders"),Ti(this,"events"),Ti(this,"namespace"),Ti(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=Pn(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 Dt(new Wt(n,oe("disableProviderPing")))}}var n7=Object.defineProperty,i7=(t,e,r)=>e in t?n7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ri=(t,e,r)=>i7(t,typeof e!="symbol"?e+"":e,r);class s7{constructor(e){Ri(this,"name","elrond"),Ri(this,"client"),Ri(this,"httpProviders"),Ri(this,"events"),Ri(this,"namespace"),Ri(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=Pn(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||xt(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("disableProviderPing")))}}var o7=Object.defineProperty,a7=(t,e,r)=>e in t?o7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ni=(t,e,r)=>a7(t,typeof e!="symbol"?e+"":e,r);class c7{constructor(e){Ni(this,"name","multiversx"),Ni(this,"client"),Ni(this,"httpProviders"),Ni(this,"events"),Ni(this,"namespace"),Ni(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=Pn(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||xt(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("disableProviderPing")))}}var l7=Object.defineProperty,u7=(t,e,r)=>e in t?l7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bi=(t,e,r)=>u7(t,typeof e!="symbol"?e+"":e,r);class h7{constructor(e){Bi(this,"name","near"),Bi(this,"client"),Bi(this,"httpProviders"),Bi(this,"events"),Bi(this,"namespace"),Bi(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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||xt(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Nt.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||xt(e,this.namespace);return typeof n>"u"?void 0:new Dt(new Wt(n,oe("disableProviderPing")))}}var d7=Object.defineProperty,f7=(t,e,r)=>e in t?d7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Li=(t,e,r)=>f7(t,typeof e!="symbol"?e+"":e,r);class p7{constructor(e){Li(this,"name","tezos"),Li(this,"client"),Li(this,"httpProviders"),Li(this,"events"),Li(this,"namespace"),Li(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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||xt(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Nt.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||xt(e,this.namespace);return typeof n>"u"?void 0:new Dt(new Wt(n))}}var g7=Object.defineProperty,m7=(t,e,r)=>e in t?g7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mi=(t,e,r)=>m7(t,typeof e!="symbol"?e+"":e,r);class w7{constructor(e){Mi(this,"name",Ii),Mi(this,"client"),Mi(this,"httpProviders"),Mi(this,"events"),Mi(this,"namespace"),Mi(this,"chainId"),this.namespace=e.namespace,this.events=oe("events"),this.client=oe("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(Nt.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=oi(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||xt(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dt(new Wt(n,oe("disableProviderPing")))}}var y7=Object.defineProperty,b7=Object.defineProperties,v7=Object.getOwnPropertyDescriptors,v1=Object.getOwnPropertySymbols,E7=Object.prototype.hasOwnProperty,_7=Object.prototype.propertyIsEnumerable,Ru=(t,e,r)=>e in t?y7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xa=(t,e)=>{for(var r in e||(e={}))E7.call(e,r)&&Ru(t,r,e[r]);if(v1)for(var r of v1(e))_7.call(e,r)&&Ru(t,r,e[r]);return t},Nu=(t,e)=>b7(t,v7(e)),Bt=(t,e,r)=>Ru(t,typeof e!="symbol"?e+"":e,r);class Bu{constructor(e){Bt(this,"client"),Bt(this,"namespaces"),Bt(this,"optionalNamespaces"),Bt(this,"sessionProperties"),Bt(this,"scopedProperties"),Bt(this,"events",new Ve.exports),Bt(this,"rpcProviders",{}),Bt(this,"session"),Bt(this,"providerOpts"),Bt(this,"logger"),Bt(this,"uri"),Bt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xt(da({level:e?.logger||Xm})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new Bu(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:xa({},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,fa(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:he("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=g1(this.session.namespaces);this.namespaces=Cu(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=g1(i.namespaces);return this.namespaces=Cu(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===Ii?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(qt(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 xu.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Xm,relayUrl:this.providerOpts.relayUrl||QC,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=>Rs(r)))];Du("client",this.client),Du("events",this.events),Du("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=BP(r,this.session),i=d1(n),s=Cu(this.namespaces,this.optionalNamespaces),o=Nu(xa({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new HP({namespace:o});break;case"algorand":this.rpcProviders[r]=new XP({namespace:o});break;case"solana":this.rpcProviders[r]=new KP({namespace:o});break;case"cosmos":this.rpcProviders[r]=new YP({namespace:o});break;case"polkadot":this.rpcProviders[r]=new UP({namespace:o});break;case"cip34":this.rpcProviders[r]=new r7({namespace:o});break;case"elrond":this.rpcProviders[r]=new s7({namespace:o});break;case"multiversx":this.rpcProviders[r]=new c7({namespace:o});break;case"near":this.rpcProviders[r]=new h7({namespace:o});break;case"tezos":this.rpcProviders[r]=new p7({namespace:o});break;default:this.rpcProviders[Ii]?this.rpcProviders[Ii].updateNamespace(o):this.rpcProviders[Ii]=new w7({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&&qt(o)&&this.events.emit("accountsChanged",o.map(p1))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Rs(o),l=Pu(o)!==Pu(a)?`${c}:${Pu(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=Nu(xa({},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",Nu(xa({},he("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Nt.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Ii]}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=>Rs(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=Rs(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(p1);if(!qt(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(`${_a}/${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(`${_a}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${_a}/${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(_a)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}}const $7=Bu,x7="wc",I7="ethereum_provider",O7=`${x7}@2:${I7}:`,S7="https://rpc.walletconnect.org/v1/",Ia=["eth_sendTransaction","personal_sign"],E1=["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"],Oa=["chainChanged","accountsChanged"],_1=["chainChanged","accountsChanged","message","disconnect","connect"];var A7=Object.defineProperty,C7=Object.defineProperties,P7=Object.getOwnPropertyDescriptors,$1=Object.getOwnPropertySymbols,D7=Object.prototype.hasOwnProperty,T7=Object.prototype.propertyIsEnumerable,Lu=(t,e,r)=>e in t?A7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ui=(t,e)=>{for(var r in e||(e={}))D7.call(e,r)&&Lu(t,r,e[r]);if($1)for(var r of $1(e))T7.call(e,r)&&Lu(t,r,e[r]);return t},Mu=(t,e)=>C7(t,P7(e)),It=(t,e,r)=>Lu(t,typeof e!="symbol"?e+"":e,r);function Sa(t){return Number(t[0].split(":")[1])}function Aa(t){return`0x${t.toString(16)}`}function R7(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!qt(e))throw new Error("Invalid chains");const c={chains:e,methods:n||Ia,events:s||Oa,rpcMap:Ui({},e.length?{[Sa(e)]:a[Sa(e)]}:{})},l=s?.filter(p=>!Oa.includes(p)),u=n?.filter(p=>!Ia.includes(p));if(!r&&!o&&!i&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=l?.length&&u?.length||!r,d={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:E1))],events:[...new Set(c.events.concat(o!=null&&o.length?o:_1))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class Ca{constructor(){It(this,"events",new Ve.exports.EventEmitter),It(this,"namespace","eip155"),It(this,"accounts",[]),It(this,"signer"),It(this,"chainId",1),It(this,"modal"),It(this,"rpc"),It(this,"STORAGE_KEY",O7),It(this,"on",(e,r)=>(this.events.on(e,r),this)),It(this,"once",(e,r)=>(this.events.once(e,r),this)),It(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),It(this,"off",(e,r)=>(this.events.off(e,r),this)),It(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Ca;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){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=R7(this.rpc);try{const i=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))}));const l=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Mu(Ui({namespaces:Ui({},r&&{[this.namespace]:r})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic,scopedProperties:l})).then(u=>{o(u)}).catch(u=>{a(new Error(u.message))})});if(!i)return;const s=Vp(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:Aa(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const n=await new Promise(async(s,o)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(c=>{!c.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Mu(Ui({},e),{chains:this.rpc.chains}),r).then(c=>{s(c)}).catch(c=>{o(new Error(c.message))})}),i=n.session;if(i){const s=Vp(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:Aa(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}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",Aa(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",Mu(Ui({},he("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({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",Aa(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||Ia:[],c=i.length?e?.events||Oa:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),d=e?.qrModalOptions||void 0;return{chains:i?.map(p=>this.formatChainId(p)),optionalChains:s.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,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?Sa(this.rpc.chains):Sa(this.rpc.optionalChains),this.signer=await $7.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{WalletConnectModal:n}=await Promise.resolve().then(function(){return rD});r=n}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(Ui({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}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&&qt(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&qt(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])||`${S7}?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 N7=Ca,B7=Symbol(),x1=Object.getPrototypeOf,Uu=new WeakMap,L7=t=>t&&(Uu.has(t)?Uu.get(t):x1(t)===Object.prototype||x1(t)===Array.prototype),M7=t=>L7(t)&&t[B7]||null,I1=(t,e=!0)=>{Uu.set(t,e)},ju=t=>typeof t=="object"&&t!==null,Gr=new WeakMap,Pa=new WeakSet,U7=(t=Object.is,e=(l,u)=>new Proxy(l,u),r=l=>ju(l)&&!Pa.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,h=n)=>{const d=i.get(l);if(d?.[0]===u)return d[1];const p=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return I1(p,!0),i.set(l,[u,p]),Reflect.ownKeys(l).forEach(f=>{if(Object.getOwnPropertyDescriptor(p,f))return;const g=Reflect.get(l,f),m={value:g,enumerable:!0,configurable:!0};if(Pa.has(g))I1(g,!1);else if(g instanceof Promise)delete m.value,m.get=()=>h(g);else if(Gr.has(g)){const[w,y]=Gr.get(g);m.value=s(w,y(),h)}Object.defineProperty(p,f,m)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],c=l=>{if(!ju(l))throw new Error("object required");const u=o.get(l);if(u)return u;let h=a[0];const d=new Set,p=($,B=++a[0])=>{h!==B&&(h=B,d.forEach(D=>D($,B)))};let f=a[1];const g=($=++a[1])=>(f!==$&&!d.size&&(f=$,w.forEach(([B])=>{const D=B[1]($);D>h&&(h=D)})),h),m=$=>(B,D)=>{const R=[...B];R[1]=[$,...R[1]],p(R,D)},w=new Map,y=($,B)=>{if(w.has($))throw new Error("prop listener already exists");if(d.size){const D=B[3](m($));w.set($,[B,D])}else w.set($,[B])},E=$=>{var B;const D=w.get($);D&&(w.delete($),(B=D[1])==null||B.call(D))},_=$=>(d.add($),d.size===1&&w.forEach(([D,R],M)=>{if(R)throw new Error("remove already exists");const A=D[3](m(M));w.set(M,[D,A])}),()=>{d.delete($),d.size===0&&w.forEach(([D,R],M)=>{R&&(R(),w.set(M,[D]))})}),O=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),x=e(O,{deleteProperty($,B){const D=Reflect.get($,B);E(B);const R=Reflect.deleteProperty($,B);return R&&p(["delete",[B],D]),R},set($,B,D,R){const M=Reflect.has($,B),A=Reflect.get($,B,R);if(M&&(t(A,D)||o.has(D)&&t(A,o.get(D))))return!0;E(B),ju(D)&&(D=M7(D)||D);let b=D;if(D instanceof Promise)D.then(v=>{D.status="fulfilled",D.value=v,p(["resolve",[B],v])}).catch(v=>{D.status="rejected",D.reason=v,p(["reject",[B],v])});else{!Gr.has(D)&&r(D)&&(b=c(D));const v=!Pa.has(b)&&Gr.get(b);v&&y(B,v)}return Reflect.set($,B,b,R),p(["set",[B],D,A]),!0}});o.set(l,x);const P=[O,g,s,_];return Gr.set(x,P),Reflect.ownKeys(l).forEach($=>{const B=Object.getOwnPropertyDescriptor(l,$);"value"in B&&(x[$]=l[$],delete B.value,delete B.writable),Object.defineProperty(O,$,B)}),x})=>[c,Gr,Pa,t,e,r,n,i,s,o,a],[j7]=U7();function Zr(t={}){return j7(t)}function Dn(t,e,r){const n=Gr.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 F7(t,e){const r=Gr.get(t);r||console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}const ze=Zr({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),be={state:ze,subscribe(t){return Dn(ze,()=>t(ze))},push(t,e){t!==ze.view&&(ze.view=t,e&&(ze.data=e),ze.history.push(t))},reset(t){ze.view=t,ze.history=[t]},replace(t){ze.history.length>1&&(ze.history[ze.history.length-1]=t,ze.view=t)},goBack(){if(ze.history.length>1){ze.history.pop();const[t]=ze.history.slice(-1);ze.view=t}},setData(t){ze.data=t}},V={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return V.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return V.isMobile()&&(t.includes("iphone")||t.includes("ipad"))},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},isArray(t){return Array.isArray(t)&&t.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(t,e,r){if(V.isHttpUrl(t))return this.formatUniversalUrl(t,e,r);let n=t;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,r);const i=encodeURIComponent(e);return`${n}wc?uri=${i}`},formatUniversalUrl(t,e,r){if(!V.isHttpUrl(t))return this.formatNativeUrl(t,e,r);let n=t;if(n.startsWith("https://t.me")){const s=Buffer.from(e).toString("base64").replace(/[=]/g,"");n.endsWith("/")&&(n=n.slice(0,-1)),this.setWalletConnectDeepLink(n,r);const o=new URL(n);return o.searchParams.set("startapp",s),o.toString()}n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,r);const i=encodeURIComponent(e);return`${n}wc?uri=${i}`},async wait(t){return new Promise(e=>{setTimeout(e,t)})},openHref(t,e){const r=this.isTelegram()?"_blank":e;window.open(t,r,"noreferrer noopener")},setWalletConnectDeepLink(t,e){try{localStorage.setItem(V.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(t){try{const[e]=t.split("?");localStorage.setItem(V.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(V.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(V.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=be.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},k7=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),tt=Zr({enabled:k7,userSessionId:"",events:[],connectedWalletId:void 0}),O1={state:tt,subscribe(t){return Dn(tt.events,()=>t(F7(tt.events[tt.events.length-1])))},initialize(){tt.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(tt.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){tt.connectedWalletId=t},click(t){if(tt.enabled){const e={type:"CLICK",name:t.name,userSessionId:tt.userSessionId,timestamp:Date.now(),data:t};tt.events.push(e)}},track(t){if(tt.enabled){const e={type:"TRACK",name:t.name,userSessionId:tt.userSessionId,timestamp:Date.now(),data:t};tt.events.push(e)}},view(t){if(tt.enabled){const e={type:"VIEW",name:t.name,userSessionId:tt.userSessionId,timestamp:Date.now(),data:t};tt.events.push(e)}}},ar=Zr({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),Oe={state:ar,subscribe(t){return Dn(ar,()=>t(ar))},setChains(t){ar.chains=t},setWalletConnectUri(t){ar.walletConnectUri=t},setIsCustomDesktop(t){ar.isCustomDesktop=t},setIsCustomMobile(t){ar.isCustomMobile=t},setIsDataLoaded(t){ar.isDataLoaded=t},setIsUiLoaded(t){ar.isUiLoaded=t},setIsAuth(t){ar.isAuth=t}},Da=Zr({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),Ot={state:Da,subscribe(t){return Dn(Da,()=>t(Da))},setConfig(t){var e,r;O1.initialize(),Oe.setChains(t.chains),Oe.setIsAuth(!!t.enableAuthMode),Oe.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),Oe.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),V.setModalVersionInStorage(),Object.assign(Da,t)}};var q7=Object.defineProperty,S1=Object.getOwnPropertySymbols,z7=Object.prototype.hasOwnProperty,H7=Object.prototype.propertyIsEnumerable,A1=(t,e,r)=>e in t?q7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V7=(t,e)=>{for(var r in e||(e={}))z7.call(e,r)&&A1(t,r,e[r]);if(S1)for(var r of S1(e))H7.call(e,r)&&A1(t,r,e[r]);return t};const Fu="https://explorer-api.walletconnect.com",ku="wcm",qu="js-2.7.0";async function Ta(t,e){const r=V7({sdkType:ku,sdkVersion:qu},e),n=new URL(t,Fu);return n.searchParams.append("projectId",Ot.state.projectId),Object.entries(r).forEach(([s,o])=>{o&&n.searchParams.append(s,String(o))}),(await fetch(n)).json()}const Tn={async getDesktopListings(t){return Ta("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return Ta("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return Ta("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return Ta("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${Fu}/w3m/v1/getWalletImage/${t}?projectId=${Ot.state.projectId}&sdkType=${ku}&sdkVersion=${qu}`},getAssetImageUrl(t){return`${Fu}/w3m/v1/getAssetImage/${t}?projectId=${Ot.state.projectId}&sdkType=${ku}&sdkVersion=${qu}`}};var W7=Object.defineProperty,C1=Object.getOwnPropertySymbols,K7=Object.prototype.hasOwnProperty,G7=Object.prototype.propertyIsEnumerable,P1=(t,e,r)=>e in t?W7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z7=(t,e)=>{for(var r in e||(e={}))K7.call(e,r)&&P1(t,r,e[r]);if(C1)for(var r of C1(e))G7.call(e,r)&&P1(t,r,e[r]);return t};const D1=V.isMobile(),cr=Zr({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),mt={state:cr,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=Ot.state;if(t==="NONE"||e==="ALL"&&!t)return cr.recomendedWallets;if(V.isArray(t)){const n={recommendedIds:t.join(",")},{listings:i}=await Tn.getAllListings(n),s=Object.values(i);s.sort((o,a)=>{const c=t.indexOf(o.id),l=t.indexOf(a.id);return c-l}),cr.recomendedWallets=s}else{const{chains:r,isAuth:n}=Oe.state,i=r?.join(","),s=V.isArray(e),o={page:1,sdks:n?"auth_v1":void 0,entries:V.RECOMMENDED_WALLET_AMOUNT,chains:i,version:2,excludedIds:s?e.join(","):void 0},{listings:a}=D1?await Tn.getMobileListings(o):await Tn.getDesktopListings(o);cr.recomendedWallets=Object.values(a)}return cr.recomendedWallets},async getWallets(t){const e=Z7({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:n}=Ot.state,{recomendedWallets:i}=cr;if(n==="ALL")return cr.wallets;i.length?e.excludedIds=i.map(h=>h.id).join(","):V.isArray(r)&&(e.excludedIds=r.join(",")),V.isArray(n)&&(e.excludedIds=[e.excludedIds,n].filter(Boolean).join(",")),Oe.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:o}=t,{listings:a,total:c}=D1?await Tn.getMobileListings(e):await Tn.getDesktopListings(e),l=Object.values(a),u=o?"search":"wallets";return cr[u]={listings:[...cr[u].listings,...l],total:c,page:s??1},{listings:l,total:c}},getWalletImageUrl(t){return Tn.getWalletImageUrl(t)},getAssetImageUrl(t){return Tn.getAssetImageUrl(t)},resetSearch(){cr.search={listings:[],total:0,page:1}}},ji=Zr({open:!1}),Rn={state:ji,subscribe(t){return Dn(ji,()=>t(ji))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:n}=Oe.state;if(V.removeWalletConnectDeepLink(),Oe.setWalletConnectUri(t?.uri),Oe.setChains(t?.chains),be.reset("ConnectWallet"),r&&n)ji.open=!0,e();else{const i=setInterval(()=>{const s=Oe.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(i),ji.open=!0,e())},200)}})},close(){ji.open=!1}};var Y7=Object.defineProperty,T1=Object.getOwnPropertySymbols,J7=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,R1=(t,e,r)=>e in t?Y7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,X7=(t,e)=>{for(var r in e||(e={}))J7.call(e,r)&&R1(t,r,e[r]);if(T1)for(var r of T1(e))Q7.call(e,r)&&R1(t,r,e[r]);return t};function eD(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const Ys=Zr({themeMode:eD()?"dark":"light"}),Yr={state:Ys,subscribe(t){return Dn(Ys,()=>t(Ys))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(Ys.themeMode=e),r&&(Ys.themeVariables=X7({},r))}},Nn=Zr({open:!1,message:"",variant:"success"}),Jr={state:Nn,subscribe(t){return Dn(Nn,()=>t(Nn))},openToast(t,e){Nn.open=!0,Nn.message=t,Nn.variant=e},closeToast(){Nn.open=!1}};class tD{constructor(e){this.openModal=Rn.open,this.closeModal=Rn.close,this.subscribeModal=Rn.subscribe,this.setTheme=Yr.setThemeConfig,Yr.setThemeConfig(e),Ot.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return hN});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),Oe.setIsUiLoaded(!0)}}}var rD=Object.freeze({__proto__:null,WalletConnectModal:tD});/**
41
41
  * @license
42
42
  * Copyright 2019 Google LLC