@walletconnect/ethereum-provider 2.21.6 → 2.21.7
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 +2 -2
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -42,8 +42,8 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(cT(r)).toStr
|
|
|
42
42
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
43
43
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
44
44
|
PERFORMANCE OF THIS SOFTWARE.
|
|
45
|
-
***************************************************************************** */var V0=function(t,e){return V0=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])},V0(t,e)};function aP(t,e){V0(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var K0=function(){return K0=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},K0.apply(this,arguments)};function cP(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 lP(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 uP(t,e){return function(r,n){e(r,n,t)}}function dP(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function hP(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(d){o(d)}}function c(u){try{l(n.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function fP(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 pP(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function gP(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function G0(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 G3(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 wP(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(G3(arguments[e]));return t}function mP(){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 sl(t){return this instanceof sl?(this.v=t,this):new sl(t)}function bP(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(f){return new Promise(function(p,g){s.push([h,f,p,g])>1||a(h,f)})})}function a(h,f){try{c(n[h](f))}catch(p){d(s[0][3],p)}}function c(h){h.value instanceof sl?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function yP(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:sl(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function vP(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 G0=="function"?G0(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 CP(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function EP(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 xP(t){return t&&t.__esModule?t:{default:t}}function _P(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function AP(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 SP=Object.freeze({__proto__:null,__extends:aP,get __assign(){return K0},__rest:cP,__decorate:lP,__param:uP,__metadata:dP,__awaiter:hP,__generator:fP,__createBinding:pP,__exportStar:gP,__values:G0,__read:G3,__spread:wP,__spreadArrays:mP,__await:sl,__asyncGenerator:bP,__asyncDelegator:yP,__asyncValues:vP,__makeTemplateObject:CP,__importStar:EP,__importDefault:xP,__classPrivateFieldGet:_P,__classPrivateFieldSet:AP}),IP=Mg(SP),ui={},Z3;function TP(){if(Z3)return ui;Z3=1,Object.defineProperty(ui,"__esModule",{value:!0}),ui.isBrowserCryptoAvailable=ui.getSubtleCrypto=ui.getBrowerCrypto=void 0;function t(){return vt?.crypto||vt?.msCrypto||{}}ui.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}ui.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return ui.isBrowserCryptoAvailable=r,ui}var di={},Y3;function NP(){if(Y3)return di;Y3=1,Object.defineProperty(di,"__esModule",{value:!0}),di.isBrowser=di.isNode=di.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}di.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}di.isNode=e;function r(){return!t()&&!e()}return di.isBrowser=r,di}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=IP;e.__exportStar(TP(),t),e.__exportStar(NP(),t)})(K3);function Pn(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Xi(t=6){return BigInt(Pn(t))}function Dn(t,e,r){return{id:r||Pn(),jsonrpc:"2.0",method:t,params:e}}function ol(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Rd(t,e,r){return{id:t,jsonrpc:"2.0",error:$P(e,r)}}function $P(t,e){return typeof t>"u"?q3(W3):(typeof t=="string"&&(t=Object.assign(Object.assign({},q3(q0)),{message:t})),typeof e<"u"&&(t.data=e),sP(t.code)&&(t=oP(t.code)),t)}class OP{}class kP extends OP{constructor(){super()}}class PP extends kP{constructor(e){super()}}const DP="^https?:",BP="^wss?:";function RP(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function J3(t,e){const r=RP(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function X3(t){return J3(t,DP)}function Q3(t){return J3(t,BP)}function UP(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function ev(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Z0(t){return ev(t)&&"method"in t}function Ud(t){return ev(t)&&(Bn(t)||Gr(t))}function Bn(t){return"result"in t}function Gr(t){return"error"in t}class Zr extends PP{constructor(e){super(e),this.events=new Tt.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(Dn(e.method,e.params||[],e.id||Xi().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=>{Gr(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),Ud(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 LP=()=>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"),MP=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",tv=t=>t.split("?")[0],rv=10,FP=LP();class jP{constructor(e){if(this.url=e,this.events=new Tt.exports.EventEmitter,this.registering=!1,!Q3(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(ri(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Q3(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=K3.isReactNative()?void 0:{rejectUnauthorized:!UP(e)},s=new FP(e,[],i);MP()?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"?$s(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=Rd(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return V3(e,tv(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>rv&&this.events.setMaxListeners(rv)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${tv(this.url)}`));return this.events.emit("register_error",r),r}}var zP=Object.defineProperty,nv=Object.getOwnPropertySymbols,WP=Object.prototype.hasOwnProperty,HP=Object.prototype.propertyIsEnumerable,iv=(t,e,r)=>e in t?zP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e)=>{for(var r in e||(e={}))WP.call(e,r)&&iv(t,r,e[r]);if(nv)for(var r of nv(e))HP.call(e,r)&&iv(t,r,e[r]);return t};const sv="wc",ov=2,Ld="core",Rn=`${sv}@2:${Ld}:`,qP={name:Ld,logger:"error"},VP={database:":memory:"},KP="crypto",av="client_ed25519_seed",GP=ee.ONE_DAY,ZP="keychain",YP="0.3",JP="messages",XP="0.3",QP=ee.SIX_HOURS,eD="publisher",cv="irn",tD="error",lv="wss://relay.walletconnect.org",rD="relayer",ct={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"},nD="_subscription",Yr={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},iD=.1,Y0="2.21.6",it={link_mode:"link_mode",relay:"relay"},Md={inbound:"inbound",outbound:"outbound"},sD="0.3",oD="WALLETCONNECT_CLIENT_ID",uv="WALLETCONNECT_LINK_MODE_APPS",Or={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},aD="subscription",cD="0.3",lD="pairing",uD="0.3",al={wc_pairingDelete:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ee.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ee.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:0},res:{ttl:ee.ONE_DAY,prompt:!1,tag:0}}},Ws={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},mn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},dD="history",hD="0.3",fD="expirer",Jr={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},pD="0.3",gD="verify-api",wD="https://verify.walletconnect.com",dv="https://verify.walletconnect.org",cl=dv,mD=`${cl}/v3`,bD=[wD,dv],yD="echo",vD="https://echo.walletconnect.com",Un={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"},hi={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"},Qi={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"},ll={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"},Hs={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"},ul={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"},CD=.1,ED="event-client",xD=86400,_D="https://pulse.walletconnect.org/batch";function AD(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,b=0,C=0,x=p.length;C!==x&&p[C]===0;)C++,g++;for(var y=(x-C)*u+1>>>0,v=new Uint8Array(y);C!==x;){for(var _=p[C],O=0,B=y-1;(_!==0||O<b)&&B!==-1;B--,O++)_+=256*v[B]>>>0,v[B]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=O,C++}for(var R=y-b;R!==y&&v[R]===0;)R++;for(var E=c.repeat(g);R<y;++R)E+=t.charAt(v[R]);return E}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var b=0,C=0;p[g]===c;)b++,g++;for(var x=(p.length-g)*l+1>>>0,y=new Uint8Array(x);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var _=0,O=x-1;(v!==0||_<C)&&O!==-1;O--,_++)v+=a*y[O]>>>0,y[O]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");C=_,g++}if(p[g]!==" "){for(var B=x-C;B!==x&&y[B]===0;)B++;for(var R=new Uint8Array(b+(x-B)),E=b;B!==x;)R[E++]=y[B++];return R}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var SD=AD,ID=SD;const hv=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")},TD=t=>new TextEncoder().encode(t),ND=t=>new TextDecoder().decode(t);class $D{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 OD{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 fv(this,e)}}class kD{constructor(e){this.decoders=e}or(e){return fv(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 fv=(t,e)=>new kD(rr(rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class PD{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new $D(e,r,n),this.decoder=new OD(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Fd=({name:t,prefix:e,encode:r,decode:n})=>new PD(t,e,r,n),dl=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=ID(r,e);return Fd({prefix:t,name:e,encode:n,decode:s=>hv(i(s))})},DD=(t,e,r,n)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},BD=(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},Dt=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Fd({prefix:e,name:t,encode(i){return BD(i,n,r)},decode(i){return DD(i,n,r,t)}}),RD=Fd({prefix:"\0",name:"identity",encode:t=>ND(t),decode:t=>TD(t)});var UD=Object.freeze({__proto__:null,identity:RD});const LD=Dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var MD=Object.freeze({__proto__:null,base2:LD});const FD=Dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jD=Object.freeze({__proto__:null,base8:FD});const zD=dl({prefix:"9",name:"base10",alphabet:"0123456789"});var WD=Object.freeze({__proto__:null,base10:zD});const HD=Dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qD=Dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var VD=Object.freeze({__proto__:null,base16:HD,base16upper:qD});const KD=Dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),GD=Dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ZD=Dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),YD=Dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),JD=Dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),XD=Dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),QD=Dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),eB=Dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tB=Dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var rB=Object.freeze({__proto__:null,base32:KD,base32upper:GD,base32pad:ZD,base32padupper:YD,base32hex:JD,base32hexupper:XD,base32hexpad:QD,base32hexpadupper:eB,base32z:tB});const nB=dl({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),iB=dl({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sB=Object.freeze({__proto__:null,base36:nB,base36upper:iB});const oB=dl({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),aB=dl({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cB=Object.freeze({__proto__:null,base58btc:oB,base58flickr:aB});const lB=Dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),uB=Dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dB=Dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hB=Dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var fB=Object.freeze({__proto__:null,base64:lB,base64pad:uB,base64url:dB,base64urlpad:hB});const pv=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}"),pB=pv.reduce((t,e,r)=>(t[r]=e,t),[]),gB=pv.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function wB(t){return t.reduce((e,r)=>(e+=pB[r],e),"")}function mB(t){const e=[];for(const r of t){const n=gB[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const bB=Fd({prefix:"\u{1F680}",name:"base256emoji",encode:wB,decode:mB});var yB=Object.freeze({__proto__:null,base256emoji:bB}),vB=wv,gv=128,CB=127,EB=~CB,xB=Math.pow(2,31);function wv(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xB;)e[r++]=t&255|gv,t/=128;for(;t&EB;)e[r++]=t&255|gv,t>>>=7;return e[r]=t|0,wv.bytes=r-n+1,e}var _B=J0,AB=128,mv=127;function J0(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw J0.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&mv)<<i:(o&mv)*Math.pow(2,i),i+=7}while(o>=AB);return J0.bytes=s-n,r}var SB=Math.pow(2,7),IB=Math.pow(2,14),TB=Math.pow(2,21),NB=Math.pow(2,28),$B=Math.pow(2,35),OB=Math.pow(2,42),kB=Math.pow(2,49),PB=Math.pow(2,56),DB=Math.pow(2,63),BB=function(t){return t<SB?1:t<IB?2:t<TB?3:t<NB?4:t<$B?5:t<OB?6:t<kB?7:t<PB?8:t<DB?9:10},RB={encode:vB,decode:_B,encodingLength:BB},bv=RB;const yv=(t,e,r=0)=>(bv.encode(t,e,r),e),vv=t=>bv.encodingLength(t),X0=(t,e)=>{const r=e.byteLength,n=vv(t),i=n+vv(r),s=new Uint8Array(i+r);return yv(t,s,0),yv(r,s,n),s.set(e,i),new UB(t,r,e,s)};class UB{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Cv=({name:t,code:e,encode:r})=>new LB(t,e,r);class LB{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?X0(this.code,r):r.then(n=>X0(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Ev=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),MB=Cv({name:"sha2-256",code:18,encode:Ev("SHA-256")}),FB=Cv({name:"sha2-512",code:19,encode:Ev("SHA-512")});var jB=Object.freeze({__proto__:null,sha256:MB,sha512:FB});const xv=0,zB="identity",_v=hv;var WB=Object.freeze({__proto__:null,identity:{code:xv,name:zB,encode:_v,digest:t=>X0(xv,_v(t))}});new TextEncoder,new TextDecoder;const Av=rr(rr(rr(rr(rr(rr(rr(rr(rr(rr({},UD),MD),jD),WD),VD),rB),sB),cB),fB),yB);rr(rr({},jB),WB);function Sv(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function HB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Sv(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Iv(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Tv=Iv("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Q0=Iv("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=HB(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),qB=rr({utf8:Tv,"utf-8":Tv,hex:Av.base16,latin1:Q0,ascii:Q0,binary:Q0},Av);function VB(t,e="utf8"){const r=qB[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Sv(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var KB=Object.defineProperty,GB=(t,e,r)=>e in t?KB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ln=(t,e,r)=>GB(t,typeof e!="symbol"?e+"":e,r);class ZB{constructor(e,r){this.core=e,this.logger=r,Ln(this,"keychain",new Map),Ln(this,"name",ZP),Ln(this,"version",YP),Ln(this,"initialized",!1),Ln(this,"storagePrefix",Rn),Ln(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Ln(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Ln(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),Ln(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=te("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),Ln(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=tr(r,this.name)}get context(){return wr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,e0(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?t0(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YB=Object.defineProperty,JB=(t,e,r)=>e in t?YB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bt=(t,e,r)=>JB(t,typeof e!="symbol"?e+"":e,r);class XB{constructor(e,r,n){this.core=e,this.logger=r,Bt(this,"name",KP),Bt(this,"keychain"),Bt(this,"randomSessionIdentifier",P0()),Bt(this,"initialized",!1),Bt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Bt(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Bt(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=tb(i);return eb(s.publicKey)}),Bt(this,"generateKeyPair",()=>{this.isInitialized();const i=g$();return this.setPrivateKey(i.publicKey,i.privateKey)}),Bt(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=tb(s),a=this.randomSessionIdentifier;return await TA(a,i,GP,o)}),Bt(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=w$(a,s);return this.setSymKey(c,o)}),Bt(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||xd(i);return await this.keychain.set(o,i),o}),Bt(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Bt(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Bt(this,"encode",async(i,s,o)=>{this.isInitialized();const a=d3(o),c=ri(s);if(f3(a))return y$(c,o?.encoding);if(h3(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return m$({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Bt(this,"decode",async(i,s,o)=>{this.isInitialized();const a=C$(s,o);if(f3(a)){const c=v$(s,o?.encoding);return $s(c)}if(h3(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=b$({symKey:c,encoded:s,encoding:o?.encoding});return $s(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Bt(this,"getPayloadType",(i,s=fr)=>{const o=Jc({encoded:i,encoding:s});return Ms(o.type)}),Bt(this,"getPayloadSenderPublicKey",(i,s=fr)=>{const o=Jc({encoded:i,encoding:s});return o.senderPublicKey?lr(o.senderPublicKey,er):void 0}),this.core=e,this.logger=tr(r,this.name),this.keychain=n||new ZB(this.core,this.logger)}get context(){return wr(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(av)}catch{e=P0(),await this.keychain.set(av,e)}return VB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var QB=Object.defineProperty,eR=Object.defineProperties,tR=Object.getOwnPropertyDescriptors,Nv=Object.getOwnPropertySymbols,rR=Object.prototype.hasOwnProperty,nR=Object.prototype.propertyIsEnumerable,e1=(t,e,r)=>e in t?QB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iR=(t,e)=>{for(var r in e||(e={}))rR.call(e,r)&&e1(t,r,e[r]);if(Nv)for(var r of Nv(e))nR.call(e,r)&&e1(t,r,e[r]);return t},sR=(t,e)=>eR(t,tR(e)),kr=(t,e,r)=>e1(t,typeof e!="symbol"?e+"":e,r);class oR extends jk{constructor(e,r){super(e,r),this.logger=e,this.core=r,kr(this,"messages",new Map),kr(this,"messagesWithoutClientAck",new Map),kr(this,"name",JP),kr(this,"version",XP),kr(this,"initialized",!1),kr(this,"storagePrefix",Rn),kr(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}}}),kr(this,"set",async(n,i,s)=>{this.isInitialized();const o=Vr(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===Md.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,sR(iR({},c),{[o]:i}))}return await this.persist(),o}),kr(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),kr(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}),kr(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Vr(i);return typeof s[o]<"u"}),kr(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Vr(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),kr(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=tr(e,this.name),this.core=r}get context(){return wr(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,e0(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,e0(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?t0(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?t0(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aR=Object.defineProperty,cR=Object.defineProperties,lR=Object.getOwnPropertyDescriptors,$v=Object.getOwnPropertySymbols,uR=Object.prototype.hasOwnProperty,dR=Object.prototype.propertyIsEnumerable,t1=(t,e,r)=>e in t?aR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xo=(t,e)=>{for(var r in e||(e={}))uR.call(e,r)&&t1(t,r,e[r]);if($v)for(var r of $v(e))dR.call(e,r)&&t1(t,r,e[r]);return t},Ov=(t,e)=>cR(t,lR(e)),Xr=(t,e,r)=>t1(t,typeof e!="symbol"?e+"":e,r);class hR extends zk{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Xr(this,"events",new Tt.exports.EventEmitter),Xr(this,"name",eD),Xr(this,"queue",new Map),Xr(this,"publishTimeout",ee.toMiliseconds(ee.ONE_MINUTE)),Xr(this,"initialPublishTimeout",ee.toMiliseconds(ee.ONE_SECOND*15)),Xr(this,"needsTransportRestart",!1),Xr(this,"publish",async(n,i,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const d=s?.ttl||QP,h=s?.prompt||!1,f=s?.tag||0,p=s?.id||Xi().toString(),g=Ko(_d().protocol),b={id:p,method:s?.publishMethod||g.publish,params:Xo({topic:n,message:i,ttl:d,prompt:h,tag:f,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},C=`Failed to publish payload, please try again. id:${p} tag:${f}`;try{gt((o=b.params)==null?void 0:o.prompt)&&((a=b.params)==null||delete a.prompt),gt((c=b.params)==null?void 0:c.tag)&&((l=b.params)==null||delete l.tag);const x=new Promise(async y=>{const v=({id:O})=>{var B;((B=b.id)==null?void 0:B.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(ct.publish,v),y())};this.relayer.events.on(ct.publish,v);const _=In(new Promise((O,B)=>{this.rpcPublish(b,s).then(O).catch(R=>{this.logger.warn(R,R?.message),B(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${f}`);try{await _,this.events.removeListener(ct.publish,v)}catch(O){this.queue.set(p,{request:b,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:n,message:i,opts:s}}),await In(x,this.publishTimeout,C)}catch(x){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(x),(u=s?.internal)!=null&&u.throwOnFailedPublish)throw x}finally{this.queue.delete(p)}}),Xr(this,"publishCustom",async n=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:u={}}=n,{attestation:d,tvf:h,publishMethod:f,prompt:p,tag:g,ttl:b=ee.FIVE_MINUTES}=u,C=u.id||Xi().toString(),x=Ko(_d().protocol),y=f||x.publish,v={id:C,method:y,params:Xo(Ov(Xo({},l),{ttl:b,prompt:p,tag:g,attestation:d}),h)},_=`Failed to publish custom payload, please try again. id:${C} tag:${g}`;try{gt((i=v.params)==null?void 0:i.prompt)&&((s=v.params)==null||delete s.prompt),gt((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const O=new Promise(async B=>{const R=({id:$})=>{var S;((S=v.id)==null?void 0:S.toString())===$.toString()&&(this.removeRequestFromQueue($),this.relayer.events.removeListener(ct.publish,R),B())};this.relayer.events.on(ct.publish,R);const E=In(new Promise(($,S)=>{this.rpcPublish(v,u).then($).catch(D=>{this.logger.warn(D,D?.message),S(D)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${C} tag:${g}`);try{await E,this.events.removeListener(ct.publish,R)}catch($){this.queue.set(C,{request:v,opts:u,attempt:1}),this.logger.warn($,$?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:C,payload:l,opts:u}}),await In(O,this.publishTimeout,_)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(C)}}),Xr(this,"on",(n,i)=>{this.events.on(n,i)}),Xr(this,"once",(n,i)=>{this.events.once(n,i)}),Xr(this,"off",(n,i)=>{this.events.off(n,i)}),Xr(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=tr(r,this.name),this.registerEventListeners()}get context(){return wr(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(ct.publish,Xo(Xo({},e),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var n;const i=e.attempt+1;this.queue.set(r,Ov(Xo({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(js.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ct.connection_stalled);return}this.checkQueue()}),this.relayer.on(ct.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var fR=Object.defineProperty,pR=(t,e,r)=>e in t?fR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qo=(t,e,r)=>pR(t,typeof e!="symbol"?e+"":e,r);class gR{constructor(){Qo(this,"map",new Map),Qo(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Qo(this,"get",e=>this.map.get(e)||[]),Qo(this,"exists",(e,r)=>this.get(e).includes(r)),Qo(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)}),Qo(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var wR=Object.defineProperty,mR=Object.defineProperties,bR=Object.getOwnPropertyDescriptors,kv=Object.getOwnPropertySymbols,yR=Object.prototype.hasOwnProperty,vR=Object.prototype.propertyIsEnumerable,r1=(t,e,r)=>e in t?wR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hl=(t,e)=>{for(var r in e||(e={}))yR.call(e,r)&&r1(t,r,e[r]);if(kv)for(var r of kv(e))vR.call(e,r)&&r1(t,r,e[r]);return t},n1=(t,e)=>mR(t,bR(e)),Xe=(t,e,r)=>r1(t,typeof e!="symbol"?e+"":e,r);class CR extends qk{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Xe(this,"subscriptions",new Map),Xe(this,"topicMap",new gR),Xe(this,"events",new Tt.exports.EventEmitter),Xe(this,"name",aD),Xe(this,"version",cD),Xe(this,"pending",new Map),Xe(this,"cached",[]),Xe(this,"initialized",!1),Xe(this,"storagePrefix",Rn),Xe(this,"subscribeTimeout",ee.toMiliseconds(ee.ONE_MINUTE)),Xe(this,"initialSubscribeTimeout",ee.toMiliseconds(ee.ONE_SECOND*15)),Xe(this,"clientId"),Xe(this,"batchSubscribeTopicsLimit",500),Xe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Xe(this,"subscribe",async(n,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=_d(i),a={topic:n,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Xe(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),Xe(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),Xe(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),Xe(this,"on",(n,i)=>{this.events.on(n,i)}),Xe(this,"once",(n,i)=>{this.events.once(n,i)}),Xe(this,"off",(n,i)=>{this.events.off(n,i)}),Xe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),Xe(this,"start",async()=>{await this.onConnect()}),Xe(this,"stop",async()=>{await this.onDisconnect()}),Xe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Xe(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)}),Xe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(js.pulse,async()=>{await this.checkPending()}),this.events.on(Or.created,async n=>{const i=Or.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(Or.deleted,async n=>{const i=Or.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=tr(r,this.name),this.clientId=""}get context(){return wr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=_d(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=nt("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,s;const o=await this.getSubscriptionId(e);if((i=n?.internal)!=null&&i.skipSubscribe)return o;(!n||n?.transportType===it.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:Ko(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===it.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},ee.toMiliseconds(ee.ONE_SECOND)),o;const l=new Promise(async d=>{const h=f=>{f.topic===e&&(this.events.removeListener(Or.created,h),d(f.id))};this.events.on(Or.created,h);try{const f=await In(new Promise((p,g)=>{this.relayer.request(a).catch(b=>{this.logger.warn(b,b?.message),g(b)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Or.created,h),d(f)}catch{}}),u=await In(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ct.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ko(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 In(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(ct.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Ko(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 In(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(ct.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Ko(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,n1(hl({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,hl({},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,hl({},r)),this.topicMap.set(r.topic,e),this.events.emit(Or.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}=te("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(Or.deleted,n1(hl({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Or.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(Or.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){const{message:r}=te("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=>n1(hl({},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 UI(ee.toMiliseconds(ee.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}=te("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 Vr(e+await this.getClientId())}}var ER=Object.defineProperty,Pv=Object.getOwnPropertySymbols,xR=Object.prototype.hasOwnProperty,_R=Object.prototype.propertyIsEnumerable,i1=(t,e,r)=>e in t?ER(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dv=(t,e)=>{for(var r in e||(e={}))xR.call(e,r)&&i1(t,r,e[r]);if(Pv)for(var r of Pv(e))_R.call(e,r)&&i1(t,r,e[r]);return t},Re=(t,e,r)=>i1(t,typeof e!="symbol"?e+"":e,r);class AR extends Wk{constructor(e){super(e),Re(this,"protocol","wc"),Re(this,"version",2),Re(this,"core"),Re(this,"logger"),Re(this,"events",new Tt.exports.EventEmitter),Re(this,"provider"),Re(this,"messages"),Re(this,"subscriber"),Re(this,"publisher"),Re(this,"name",rD),Re(this,"transportExplicitlyClosed",!1),Re(this,"initialized",!1),Re(this,"connectionAttemptInProgress",!1),Re(this,"relayUrl"),Re(this,"projectId"),Re(this,"packageName"),Re(this,"bundleId"),Re(this,"hasExperiencedNetworkDisruption",!1),Re(this,"pingTimeout"),Re(this,"heartBeatTimeout",ee.toMiliseconds(ee.THIRTY_SECONDS+ee.FIVE_SECONDS)),Re(this,"reconnectTimeout"),Re(this,"connectPromise"),Re(this,"reconnectInProgress",!1),Re(this,"requestsInFlight",[]),Re(this,"connectTimeout",ee.toMiliseconds(ee.ONE_SECOND*15)),Re(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Xi().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}}),Re(this,"resetPingTimeout",()=>{od()&&(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))}),Re(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(ct.connect)}),Re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),Re(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(ct.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Re(this,"registerProviderListeners",()=>{this.provider.on(Yr.payload,this.onPayloadHandler),this.provider.on(Yr.connect,this.onConnectHandler),this.provider.on(Yr.disconnect,this.onDisconnectHandler),this.provider.on(Yr.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?tr(e.logger,this.name):On(nl({level:e.logger||tD})),this.messages=new oR(this.logger,e.core),this.subscriber=new CR(this,this.logger),this.publisher=new hR(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lv,CI()?this.packageName=jb():EI()&&(this.bundleId=jb()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return wr(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:it.relay},Md.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}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(Or.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Or.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,Dv({internal:{throwOnFailedPublish:o}},r)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await In(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,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 S3())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=ft(ee.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(ct.message,e),await this.recordMessageEvent(e,Md.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 connect"))};this.provider.once(Yr.disconnect,s),await In(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(Yr.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Yr.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Yr.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,ee.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(od())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 Zr(new jP(II({sdkVersion:Y0,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}),Z0(e)){if(!e.method.endsWith(nD))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:it.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Dv({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ud(e)&&this.events.emit(ct.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Md.inbound),this.events.emit(ct.message,e))}async acknowledgePayload(e){const r=ol(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Yr.payload,this.onPayloadHandler),this.provider.off(Yr.connect,this.onConnectHandler),this.provider.off(Yr.disconnect,this.onDisconnectHandler),this.provider.off(Yr.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await S3();pO(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))}),this.core.heartbeat.on(js.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&mO())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ct.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},ee.toMiliseconds(iD)))))}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function SR(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Bv(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Rv(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const IR="[object RegExp]",TR="[object String]",NR="[object Number]",$R="[object Boolean]",Uv="[object Arguments]",OR="[object Symbol]",kR="[object Date]",PR="[object Map]",DR="[object Set]",BR="[object Array]",RR="[object Function]",UR="[object ArrayBuffer]",s1="[object Object]",LR="[object Error]",MR="[object DataView]",FR="[object Uint8Array]",jR="[object Uint8ClampedArray]",zR="[object Uint16Array]",WR="[object Uint32Array]",HR="[object BigUint64Array]",qR="[object Int8Array]",VR="[object Int16Array]",KR="[object Int32Array]",GR="[object BigInt64Array]",ZR="[object Float32Array]",YR="[object Float64Array]";function JR(){}function Lv(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 XR(t,e,r){return fl(t,e,void 0,void 0,void 0,void 0,r)}function fl(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 pl(t,e,s,o)}return pl(t,e,s,o)}function pl(t,e,r,n){if(Object.is(t,e))return!0;let i=Rv(t),s=Rv(e);if(i===Uv&&(i=s1),s===Uv&&(s=s1),i!==s)return!1;switch(i){case TR:return t.toString()===e.toString();case NR:{const c=t.valueOf(),l=e.valueOf();return SR(c,l)}case $R:case kR:case OR:return Object.is(t.valueOf(),e.valueOf());case IR:return t.source===e.source&&t.flags===e.flags;case RR: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 PR:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!fl(l,e.get(c),c,t,e,r,n))return!1;return!0}case DR:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(f=>fl(d,f,void 0,t,e,r,n));if(h===-1)return!1;l.splice(h,1)}return!0}case BR:case FR:case jR:case zR:case WR:case HR:case qR:case VR:case KR:case GR:case ZR:case YR:{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(!fl(t[c],e[c],c,t,e,r,n))return!1;return!0}case UR:return t.byteLength!==e.byteLength?!1:pl(new Uint8Array(t),new Uint8Array(e),r,n);case MR:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:pl(new Uint8Array(t),new Uint8Array(e),r,n);case LR:return t.name===e.name&&t.message===e.message;case s1:{if(!(pl(t.constructor,e.constructor,r,n)||Lv(t)&&Lv(e)))return!1;const c=[...Object.keys(t),...Bv(t)],l=[...Object.keys(e),...Bv(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=t[d];if(!Object.hasOwn(e,d))return!1;const f=e[d];if(!fl(h,f,d,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function QR(t,e){return XR(t,e,JR)}var eU=Object.defineProperty,Mv=Object.getOwnPropertySymbols,tU=Object.prototype.hasOwnProperty,rU=Object.prototype.propertyIsEnumerable,o1=(t,e,r)=>e in t?eU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fv=(t,e)=>{for(var r in e||(e={}))tU.call(e,r)&&o1(t,r,e[r]);if(Mv)for(var r of Mv(e))rU.call(e,r)&&o1(t,r,e[r]);return t},mr=(t,e,r)=>o1(t,typeof e!="symbol"?e+"":e,r);class qs extends Hk{constructor(e,r,n,i=Rn,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,mr(this,"map",new Map),mr(this,"version",sD),mr(this,"cached",[]),mr(this,"initialized",!1),mr(this,"getKey"),mr(this,"storagePrefix",Rn),mr(this,"recentlyDeleted",[]),mr(this,"recentlyDeletedLimit",200),mr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!gt(o)?this.map.set(this.getKey(o),o):q$(o)?this.map.set(o.id,o):V$(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),mr(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())}),mr(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),mr(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>QR(a[c],o[c]))):this.values)),mr(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=Fv(Fv({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),mr(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=tr(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return wr(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}=te("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=te("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}=te("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}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nU=Object.defineProperty,iU=(t,e,r)=>e in t?nU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$e=(t,e,r)=>iU(t,typeof e!="symbol"?e+"":e,r);class sU{constructor(e,r){this.core=e,this.logger=r,$e(this,"name",lD),$e(this,"version",uD),$e(this,"events",new Tt.exports),$e(this,"pairings"),$e(this,"initialized",!1),$e(this,"storagePrefix",Rn),$e(this,"ignoredPayloadTypes",[li]),$e(this,"registeredMethods",[]),$e(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),$e(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),$e(this,"create",async n=>{this.isInitialized();const i=P0(),s=await this.core.crypto.setSymKey(i),o=ft(ee.FIVE_MINUTES),a={protocol:cv},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},l=g3({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(Ws.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:l}}),$e(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Un.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=p3(n.uri);i.props.properties.topic=s,i.addTrace(Un.pairing_uri_validation_success),i.addTrace(Un.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(Un.existing_pairing),u.active)throw i.setError(hi.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Un.pairing_not_expired)}const d=c||ft(ee.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(Un.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Ws.create,h),i.addTrace(Un.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Un.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(hi.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(hi.subscribe_pairing_topic_failure),f}return i.addTrace(Un.subscribe_pairing_topic_success),h}),$e(this,"activate",async({topic:n})=>{this.isInitialized();const i=ft(ee.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),$e(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}=Ds();this.events.once(ze("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),$e(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),$e(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),$e(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),$e(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",nt("USER_DISCONNECTED")),await this.deletePairing(i))}),$e(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return g3({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),$e(this,"sendRequest",async(n,i,s)=>{const o=Dn(i,s),a=await this.core.crypto.encode(n,o),c=al[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),$e(this,"sendResult",async(n,i,s)=>{const o=ol(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=al[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),$e(this,"sendError",async(n,i,s)=>{const o=Rd(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=al[c]?al[c].res:al.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),$e(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,nt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),$e(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>Mi(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),$e(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)}}),$e(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)}}),$e(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Ws.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),$e(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{Bn(i)?this.events.emit(ze("pairing_ping",s),{}):Gr(i)&&this.events.emit(ze("pairing_ping",s),{error:i.error})},500)}),$e(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Ws.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),$e(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=nt("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)}}),$e(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(nt("WC_METHOD_UNSUPPORTED",n))}),$e(this,"isValidPair",(n,i)=>{var s;if(!pr(n)){const{message:a}=te("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(hi.malformed_pairing_uri),new Error(a)}if(!H$(n.uri)){const{message:a}=te("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(hi.malformed_pairing_uri),new Error(a)}const o=p3(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=te("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(hi.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=te("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(hi.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&ee.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(hi.pairing_expired);const{message:a}=te("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),$e(this,"isValidPing",async n=>{if(!pr(n)){const{message:s}=te("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),$e(this,"isValidDisconnect",async n=>{if(!pr(n)){const{message:s}=te("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),$e(this,"isValidPairingTopic",async n=>{if(!ut(n,!1)){const{message:i}=te("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=te("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Mi(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=te("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=tr(r,this.name),this.pairings=new qs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return wr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ct.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==it.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);Z0(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):Ud(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(Jr.expired,async e=>{const{topic:r}=qb(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ws.expire,{topic:r}))})}}var oU=Object.defineProperty,aU=(t,e,r)=>e in t?oU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rt=(t,e,r)=>aU(t,typeof e!="symbol"?e+"":e,r);class cU extends Fk{constructor(e,r){super(e,r),this.core=e,this.logger=r,Rt(this,"records",new Map),Rt(this,"events",new Tt.exports.EventEmitter),Rt(this,"name",dD),Rt(this,"version",hD),Rt(this,"cached",[]),Rt(this,"initialized",!1),Rt(this,"storagePrefix",Rn),Rt(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)}),Rt(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:ft(ee.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(mn.created,o)}),Rt(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=Gr(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(mn.updated,i))}),Rt(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))),Rt(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(mn.deleted,s)}}),this.persist()}),Rt(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Rt(this,"on",(n,i)=>{this.events.on(n,i)}),Rt(this,"once",(n,i)=>{this.events.once(n,i)}),Rt(this,"off",(n,i)=>{this.events.off(n,i)}),Rt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=tr(r,this.name)}get context(){return wr(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:Dn(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}=te("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(mn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=te("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(mn.created,e=>{const r=mn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(mn.updated,e=>{const r=mn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(mn.deleted,e=>{const r=mn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(js.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{ee.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(mn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var lU=Object.defineProperty,uU=(t,e,r)=>e in t?lU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kt=(t,e,r)=>uU(t,typeof e!="symbol"?e+"":e,r);class dU extends Vk{constructor(e,r){super(e,r),this.core=e,this.logger=r,Kt(this,"expirations",new Map),Kt(this,"events",new Tt.exports.EventEmitter),Kt(this,"name",fD),Kt(this,"version",pD),Kt(this,"cached",[]),Kt(this,"initialized",!1),Kt(this,"storagePrefix",Rn),Kt(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)}),Kt(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Kt(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(Jr.created,{target:s,expiration:o})}),Kt(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),Kt(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(Jr.deleted,{target:i,expiration:s})}}),Kt(this,"on",(n,i)=>{this.events.on(n,i)}),Kt(this,"once",(n,i)=>{this.events.once(n,i)}),Kt(this,"off",(n,i)=>{this.events.off(n,i)}),Kt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=tr(r,this.name)}get context(){return wr(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 TI(e);if(typeof e=="number")return NI(e);const{message:r}=te("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(Jr.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=te("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}=te("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;ee.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Jr.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(js.pulse,()=>this.checkExpirations()),this.events.on(Jr.created,e=>{const r=Jr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Jr.expired,e=>{const r=Jr.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Jr.deleted,e=>{const r=Jr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var hU=Object.defineProperty,fU=(t,e,r)=>e in t?hU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dt=(t,e,r)=>fU(t,typeof e!="symbol"?e+"":e,r);class pU extends Kk{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,dt(this,"name",gD),dt(this,"abortController"),dt(this,"isDevEnv"),dt(this,"verifyUrlV3",mD),dt(this,"storagePrefix",Rn),dt(this,"version",ov),dt(this,"publicKey"),dt(this,"fetchPromise"),dt(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&ee.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),dt(this,"register",async i=>{if(!Fo()||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=vs(),u=this.startAbortTimer(ee.ONE_SECOND*5),d=await new Promise((h,f)=>{const p=()=>{window.removeEventListener("message",b),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const b=C=>{if(C.data&&typeof C.data=="string")try{const x=JSON.parse(C.data);if(x.type==="verify_attestation"){if(Vp(x.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",b),h(x.attestation===null?"":x.attestation)}}catch(x){this.logger.warn(x)}};l.body.appendChild(g),window.addEventListener("message",b,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),dt(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(Vp(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)}),dt(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(ee.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}),dt(this,"getVerifyUrl",i=>{let s=i||cl;return bD.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${cl}`),s=cl),s}),dt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(ee.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)}}),dt(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),dt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),dt(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")}}),dt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),dt(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}),dt(this,"validateAttestation",(i,s)=>{const o=x$(i,s.publicKey),a={hasExpired:ee.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=tr(r,this.name),this.abortController=new AbortController,this.isDevEnv=r0(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return wr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ee.toMiliseconds(e))}}var gU=Object.defineProperty,wU=(t,e,r)=>e in t?gU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jv=(t,e,r)=>wU(t,typeof e!="symbol"?e+"":e,r);class mU extends Gk{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,jv(this,"context",yD),jv(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${vD}/${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=tr(r,this.context)}}var bU=Object.defineProperty,zv=Object.getOwnPropertySymbols,yU=Object.prototype.hasOwnProperty,vU=Object.prototype.propertyIsEnumerable,a1=(t,e,r)=>e in t?bU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gl=(t,e)=>{for(var r in e||(e={}))yU.call(e,r)&&a1(t,r,e[r]);if(zv)for(var r of zv(e))vU.call(e,r)&&a1(t,r,e[r]);return t},_t=(t,e,r)=>a1(t,typeof e!="symbol"?e+"":e,r);class CU extends Zk{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,_t(this,"context",ED),_t(this,"storagePrefix",Rn),_t(this,"storageVersion",CD),_t(this,"events",new Map),_t(this,"shouldPersist",!1),_t(this,"init",async()=>{if(!r0())try{const i={eventId:Kb(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Wb(this.core.relayer.protocol,this.core.relayer.version,Y0)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),_t(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=Kb(),u=this.core.projectId||"",d=Date.now(),h=gl({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),_t(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 gl(gl({},a),this.setMethods(a.eventId))}),_t(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),_t(this,"setEventListeners",()=>{this.core.heartbeat.on(js.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{ee.fromMiliseconds(Date.now())-ee.fromMiliseconds(i.timestamp)>xD&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),_t(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),_t(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)}),_t(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)}),_t(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),_t(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,gl(gl({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),_t(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)}}),_t(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${_D}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Y0}${s}`,{method:"POST",body:JSON.stringify(i)})}),_t(this,"getAppDomain",()=>zb().url),this.logger=tr(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 EU=Object.defineProperty,Wv=Object.getOwnPropertySymbols,xU=Object.prototype.hasOwnProperty,_U=Object.prototype.propertyIsEnumerable,c1=(t,e,r)=>e in t?EU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hv=(t,e)=>{for(var r in e||(e={}))xU.call(e,r)&&c1(t,r,e[r]);if(Wv)for(var r of Wv(e))_U.call(e,r)&&c1(t,r,e[r]);return t},et=(t,e,r)=>c1(t,typeof e!="symbol"?e+"":e,r);class l1 extends Rk{constructor(e){var r;super(e),et(this,"protocol",sv),et(this,"version",ov),et(this,"name",Ld),et(this,"relayUrl"),et(this,"projectId"),et(this,"customStoragePrefix"),et(this,"events",new Tt.exports.EventEmitter),et(this,"logger"),et(this,"heartbeat"),et(this,"relayer"),et(this,"crypto"),et(this,"storage"),et(this,"history"),et(this,"expirer"),et(this,"pairing"),et(this,"verify"),et(this,"echoClient"),et(this,"linkModeSupportedApps"),et(this,"eventClient"),et(this,"initialized",!1),et(this,"logChunkController"),et(this,"on",(a,c)=>this.events.on(a,c)),et(this,"once",(a,c)=>this.events.once(a,c)),et(this,"off",(a,c)=>this.events.off(a,c)),et(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),et(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:it.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||lv,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=nl({level:typeof e?.logger=="string"&&e.logger?e.logger:qP.logger,name:Ld}),{logger:s,chunkLoggerController:o}=F3({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=tr(s,this.name),this.heartbeat=new L0,this.crypto=new XB(this,this.logger,e?.keychain),this.history=new cU(this,this.logger),this.expirer=new dU(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ok(Hv(Hv({},VP),e?.storageOptions)),this.relayer=new AR({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new sU(this,this.logger),this.verify=new pU(this,this.logger,this.storage),this.echoClient=new mU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new CU(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new l1(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(oD,n),r}get context(){return wr(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(uv,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(uv)||[],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 AU=l1,qv="wc",Vv=2,Kv="client",u1=`${qv}@${Vv}:${Kv}:`,d1={name:Kv,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Gv="WALLETCONNECT_DEEPLINK_CHOICE",SU="proposal",Zv="Proposal expired",IU="session",ea=ee.SEVEN_DAYS,TU="engine",Ut={wc_sessionPropose:{req:{ttl:ee.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ee.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ee.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ee.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ee.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1119}}},h1={min:ee.FIVE_MINUTES,max:ee.SEVEN_DAYS},Mn={idle:"IDLE",active:"ACTIVE"},NU={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},$U="request",OU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],kU="wc",PU="auth",DU="authKeys",BU="pairingTopics",RU="requests",jd=`${kU}@${1.5}:${PU}:`,zd=`${jd}:PUB_KEY`;var UU=Object.defineProperty,LU=Object.defineProperties,MU=Object.getOwnPropertyDescriptors,Yv=Object.getOwnPropertySymbols,FU=Object.prototype.hasOwnProperty,jU=Object.prototype.propertyIsEnumerable,f1=(t,e,r)=>e in t?UU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qe=(t,e)=>{for(var r in e||(e={}))FU.call(e,r)&&f1(t,r,e[r]);if(Yv)for(var r of Yv(e))jU.call(e,r)&&f1(t,r,e[r]);return t},Gt=(t,e)=>LU(t,MU(e)),q=(t,e,r)=>f1(t,typeof e!="symbol"?e+"":e,r);class zU extends Qk{constructor(e){super(e),q(this,"name",TU),q(this,"events",new Tt.exports),q(this,"initialized",!1),q(this,"requestQueue",{state:Mn.idle,queue:[]}),q(this,"sessionRequestQueue",{state:Mn.idle,queue:[]}),q(this,"emittedSessionRequests",new LI({limit:500})),q(this,"requestQueueDelay",ee.ONE_SECOND),q(this,"expectedPairingMethodMap",new Map),q(this,"recentlyDeletedMap",new Map),q(this,"recentlyDeletedLimit",200),q(this,"relayMessageCache",[]),q(this,"pendingSessions",new Map),q(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(Ut)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ee.toMiliseconds(this.requestQueueDelay)))}),q(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Gt(qe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=M$(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let u=i,d,h=!1;try{if(u){const O=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=O.active}}catch(O){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),O}if(!u||!h){const{topic:O,uri:B}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=O,d=B}if(!u){const{message:O}=te("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(O)}const f=await this.client.core.crypto.generateKeyPair(),p=Ut.wc_sessionPropose.req.ttl||ee.FIVE_MINUTES,g=ft(p),b=Gt(qe(qe({requiredNamespaces:s,optionalNamespaces:o,relays:l??[{protocol:cv}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Pn()}),C=ze("session_connect",b.id),{reject:x,resolve:y,done:v}=Ds(p,Zv),_=({id:O})=>{O===b.id&&(this.client.events.off("proposal_expire",_),this.pendingSessions.delete(b.id),this.events.emit(C,{error:{message:Zv,code:0}}))};return this.client.events.on("proposal_expire",_),this.events.once(C,({error:O,session:B})=>{this.client.events.off("proposal_expire",_),O?x(O):B&&y(B)}),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0}}}),await this.setProposal(b.id,b),{uri:d,approval:v}}),q(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}}),q(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:[Qi.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(ll.no_internet_connection),E}try{await this.isValidProposalId(r?.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(ll.proposal_not_found),E}try{await this.isValidApprove(r)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ll.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:b,optionalNamespaces:C}=f;let x=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:p});x||(x=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Qi.session_approve_started,properties:{topic:p,trace:[Qi.session_approve_started,Qi.session_namespaces_validation_success]}}));const y=await this.client.core.crypto.generateKeyPair(),v=g.publicKey,_=await this.client.core.crypto.generateSharedKey(y,v),O=qe(qe(qe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:y,metadata:this.client.metadata},expiry:ft(ea)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),B=it.relay;x.addTrace(Qi.subscribing_session_topic);try{await this.client.core.relayer.subscribe(_,{transportType:B,internal:{skipSubscribe:!0}})}catch(E){throw x.setError(ll.subscribe_session_topic_failure),E}x.addTrace(Qi.subscribe_session_topic_success);const R=Gt(qe({},O),{topic:_,requiredNamespaces:b,optionalNamespaces:C,pairingTopic:p,acknowledged:!1,self:O.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:y,transportType:it.relay});await this.client.session.set(_,R),x.addTrace(Qi.store_session);try{await this.sendApproveSession({sessionTopic:_,proposal:f,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:y},sessionSettleRequest:O,publishOpts:{internal:{throwOnFailedPublish:!0}}}),x.addTrace(Qi.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(_,nt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(_),E}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(_,ft(ea)),{topic:_,acknowledged:()=>Promise.resolve(this.client.session.get(_))}}),q(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:Ut.wc_sessionPropose.reject}),await this.deleteProposal(n)}),q(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=Ds(),c=Pn(),l=Xi().toString(),u=this.client.session.get(n).namespaces;return this.events.once(ze("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:u}),a(d)}),{acknowledged:s}}),q(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=Pn(),{done:s,resolve:o,reject:a}=Ds();return this.events.once(ze("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,ft(ea)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),q(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:n,request:i,topic:s,expiry:o=Ut.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===it.relay&&await this.confirmOnlineStateOrThrow();const c=Pn(),l=Xi().toString(),{done:u,resolve:d,reject:h}=Ds(o,"Request expired. Please try again.");this.events.once(ze("session_request",c),({error:b,result:C})=>{b?h(b):d(C)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:Gt(qe({},i),{expiryTimestamp:ft(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await u();const g={request:Gt(qe({},i),{expiryTimestamp:ft(o)}),chainId:n};return await Promise.all([new Promise(async b=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(C=>h(C)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var C;if(!((C=a.sessionConfig)!=null&&C.disableDeepLink)){const x=await PI(this.client.core.storage,Gv);await $I({id:c,topic:s,wcDeepLink:x})}b()}),u()]).then(b=>b[2])}),q(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===it.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Bn(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):Gr(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),q(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=Pn(),s=Xi().toString(),{done:o,resolve:a,reject:c}=Ds();this.events.once(ze("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}))}),q(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Xi().toString(),a=Pn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),q(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:nt("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}=te("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),q(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>z$(n,r)))),q(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),q(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?it.link_mode:it.relay;o===it.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:p,methods:g=[],expiry:b}=r,C=[...r.resources||[]],{topic:x,uri:y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:x,uri:y}});const v=await this.client.core.crypto.generateKeyPair(),_=xd(v);if(await Promise.all([this.client.auth.authKeys.set(zd,{responseTopic:_,publicKey:v}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:x})]),await this.client.core.relayer.subscribe(_,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${x}`),g.length>0){const{namespace:N}=ks(a[0]);let k=GT(N,"request",g);dd(C)&&(k=YT(k,C.pop())),C.push(k)}const O=b&&b>Ut.wc_sessionAuthenticate.req.ttl?b:Ut.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:p,resources:C},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:ft(O)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:x,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:ft(Ut.wc_sessionPropose.req.ttl),id:Pn()},{done:$,resolve:S,reject:D}=Ds(O,"Request expired"),U=Pn(),M=ze("session_connect",E.id),w=ze("session_request",U),m=async({error:N,session:k})=>{this.events.off(w,A),N?D(N):k&&S({session:k})},A=async N=>{var k,j,z;if(await this.deletePendingAuthRequest(U,{message:"fulfilled",code:0}),N.error){const ge=nt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return N.error.code===ge.code?void 0:(this.events.off(M,m),D(N.error.message))}await this.deleteProposal(E.id),this.events.off(M,m);const{cacaos:G,responder:H}=N.result,J=[],fe=[];for(const ge of G){await my({cacao:ge,projectId:this.client.core.projectId})||(this.client.logger.error(ge,"Signature verification failed"),D(nt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ee}=ge,He=dd(Ee.resources),yt=[p0(Ee.iss)],Ft=ud(Ee.iss);if(He){const ln=vy(He),Gn=Cy(He);J.push(...ln),yt.push(...Gn)}for(const ln of yt)fe.push(`${ln}:${Ft}`)}const ve=await this.client.core.crypto.generateSharedKey(v,H.publicKey);let Se;J.length>0&&(Se={topic:ve,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:H,controller:H.publicKey,expiry:ft(ea),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:x,namespaces:y3([...new Set(J)],[...new Set(fe)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,Se),x&&await this.client.core.pairing.updateMetadata({topic:x,metadata:H.metadata}),Se=this.client.session.get(ve)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(j=H.metadata.redirect)!=null&&j.linkMode&&(z=H.metadata.redirect)!=null&&z.universal&&n&&(this.client.core.addLinkModeSupportedApp(H.metadata.redirect.universal),this.client.session.update(ve,{transportType:it.link_mode})),S({auths:G,session:Se})};this.events.once(M,m),this.events.once(w,A);let T;try{if(s){const N=Dn("wc_sessionAuthenticate",B,U);this.client.core.history.set(x,N);const k=await this.client.core.crypto.encode("",N,{type:Zc,encoding:Ji});T=Ad(n,x,k)}else await Promise.all([this.sendRequest({topic:x,method:"wc_sessionAuthenticate",params:B,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:U}),this.sendRequest({topic:x,method:"wc_sessionPropose",params:E,expiry:Ut.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(N){throw this.events.off(M,m),this.events.off(w,A),N}return await this.setProposal(E.id,E),await this.setAuthRequest(U,{request:Gt(qe({},B),{verifyContext:{}}),pairingTopic:x,transportType:o}),{uri:T??y,response:$}}),q(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Hs.authenticated_session_approve_started]}});try{this.isInitialized()}catch(b){throw s.setError(ul.no_internet_connection),b}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(ul.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||it.relay;a===it.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=xd(c),d={type:li,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const b of i){if(!await my({cacao:b,projectId:this.client.core.projectId})){s.setError(ul.invalid_cacao);const _=nt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:_,encodeOpts:d}),new Error(_.message)}s.addTrace(Hs.cacaos_verified);const{p:C}=b,x=dd(C.resources),y=[p0(C.iss)],v=ud(C.iss);if(x){const _=vy(x),O=Cy(x);h.push(..._),y.push(...O)}for(const _ of y)f.push(`${_}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Hs.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ft(ea),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:y3([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Hs.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(b){throw s.setError(ul.subscribe_authenticated_session_topic_failure),b}s.addTrace(Hs.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Hs.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Hs.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(b){throw s.setError(ul.authenticated_session_approve_publish_failure),b}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}}),q(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===it.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=xd(o),l={type:li,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:l,rpcOpts:Ut.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),q(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return by(n,i)}),q(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)}),q(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)}}),q(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,nt("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(Gv).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,nt("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Mn.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),q(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(ll.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,nt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),q(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=Mn.idle,this.client.events.emit("session_request_expire",{id:r}))}),q(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)])}),q(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}))}),q(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,ft(Ut.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),q(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=it.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})}),q(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||ft(Ut.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})}),q(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=r,f=Dn(i,s,c);let p;const g=!!u;try{const x=g?Ji:fr;p=await this.client.core.crypto.encode(n,f,{encoding:x})}catch(x){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),x}let b;if(OU.includes(i)){const x=Vr(JSON.stringify(f)),y=Vr(p);b=await this.client.core.verify.register({id:y,decryptedId:x})}const C=qe(qe({},Ut[i].req),h);if(C.attestation=b,o&&(C.ttl=o),a&&(C.id=a),this.client.core.history.set(n,f),g){const x=Ad(u,n,p);await global.Linking.openURL(x,this.client.name)}else C.tvf=Gt(qe({},d),{correlationId:f.id}),l?(C.internal=Gt(qe({},C.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,C)):this.client.core.relayer.publish(n,p,C).catch(x=>this.client.logger.error(x));return f.id}),q(this,"sendProposeSession",async r=>{const{proposal:n,publishOpts:i}=r,s=Dn("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);const o=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:fr}),a=Vr(JSON.stringify(s)),c=Vr(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:Gt(qe({},i),{id:n.id,publishMethod:"wc_proposeSession",attestation:l})})}),q(this,"sendApproveSession",async r=>{const{sessionTopic:n,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=ol(s.id,i),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:fr}),u=Dn("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(n,u,{encoding:fr});this.client.core.history.set(n,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:Gt(qe({},a),{publishMethod:"wc_approveSession"})})}),q(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=ol(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?Ji:fr;u=await this.client.core.crypto.encode(i,l,Gt(qe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,f;try{h=await this.client.core.history.get(i,n);const p=h.request;try{f=this.getTVFParams(n,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),p}if(d){const p=Ad(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Ut[p].res;g.tvf=Gt(qe({},f),{correlationId:n}),o?(g.internal=Gt(qe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(b=>this.client.logger.error(b))}await this.client.core.history.resolve(l)}),q(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Rd(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?Ji:fr;u=await this.client.core.crypto.encode(i,l,Gt(qe({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,n)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),f}if(d){const f=Ad(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,p=a||Ut[f].res;this.client.core.relayer.publish(i,u,p)}await this.client.core.history.resolve(l)}),q(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;Mi(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=>{Mi(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),q(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),q(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),q(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Mn.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=Mn.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Mn.idle}),q(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}`)}}),q(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}`)}}),q(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=te("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),q(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)}),q(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(hi.proposal_listener_not_found)),this.isValidConnect(qe({},i.params));const u=a.expiryTimestamp||ft(Ut.wc_sessionPropose.req.ttl),d=qe({id:c,pairingTopic:n,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:Vr(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(Un.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:Ut.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),q(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(Bn(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:r,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:r})}else if(Gr(n)){await this.deleteProposal(s);const o=ze("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})}}),q(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=n.params,f=[...this.pendingSessions.values()].find(b=>b.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const p=this.client.proposal.get(f.proposalId),g=Gt(qe(qe(qe({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:it.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ze("session_connect",f.proposalId),{session:g}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:n.id,topic:r,result:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),q(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;Bn(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ze("session_approve",i),{})):Gr(n)&&(await this.client.session.delete(r,nt("USER_DISCONNECTED")),this.events.emit(ze("session_approve",i),{error:n.error}))}),q(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Xc.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:nt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(qe({topic:r},i));try{Xc.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Xc.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)}}),q(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),q(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=ze("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Bn(n)?this.events.emit(ze("session_update",i),{}):Gr(n)&&this.events.emit(ze("session_update",i),{error:n.error})}),q(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ft(ea)),await this.sendResult({id:i,topic:r,result:!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)}}),q(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=ze("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Bn(n)?this.events.emit(ze("session_extend",i),{}):Gr(n)&&this.events.emit(ze("session_extend",i),{error:n.error})}),q(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)}}),q(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=ze("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Bn(n)?this.events.emit(ze("session_ping",i),{}):Gr(n)&&this.events.emit(ze("session_ping",i),{error:n.error})},500)}),q(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(ct.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:nt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),q(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:d,params:h}=a;try{await this.isValidRequest(qe({topic:o},h));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Vr(JSON.stringify(Dn("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),u===it.link_mode&&(n=f.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),q(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=ze("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Bn(n)?this.events.emit(ze("session_request",i),{result:n.result}):Gr(n)&&this.events.emit(ze("session_request",i),{error:n.error})}),q(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Xc.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(qe({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Xc.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),q(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Bn(n)?this.events.emit(ze("session_request",i),{result:n.result}):Gr(n)&&this.events.emit(ze("session_request",i),{error:n.error})}),q(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:Vr(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===it.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:li,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Ut.wc_sessionAuthenticate.autoReject,appLink:h})}}),q(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),q(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Mn.idle,this.processSessionRequestQueue()},ee.toMiliseconds(this.requestQueueDelay))}),q(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=ze("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ze("session_request",s.request.id),{error:n})})}),q(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Mn.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),q(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Mn.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),q(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:Dn("wc_sessionPropose",Gt(qe({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),q(this,"isValidConnect",async r=>{if(!pr(r)){const{message:l}=te("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(gt(n)||await this.isValidPairingTopic(n),!eO(c,!0)){const{message:l}=te("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!gt(i)&&$n(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(!gt(s)&&$n(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),gt(o)||this.validateSessionProps(o,"sessionProperties"),!gt(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),q(this,"validateNamespaces",(r,n)=>{const i=Q$(r,"connect()",n);if(i)throw new Error(i.message)}),q(this,"isValidApprove",async r=>{if(!pr(r))throw new Error(te("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=B0(i,"approve()");if(l)throw new Error(l.message);const u=_3(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!ut(s,!0)){const{message:d}=te("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(gt(o)||this.validateSessionProps(o,"sessionProperties"),!gt(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),q(this,"isValidReject",async r=>{if(!pr(r)){const{message:s}=te("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!rO(i)){const{message:s}=te("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),q(this,"isValidSessionSettleRequest",r=>{if(!pr(r)){const{message:l}=te("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!E3(n)){const{message:l}=te("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=B0(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Mi(o)){const{message:l}=te("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),q(this,"isValidUpdate",async r=>{if(!pr(r)){const{message:c}=te("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=B0(i,"update()");if(o)throw new Error(o.message);const a=_3(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),q(this,"isValidExtend",async r=>{if(!pr(r)){const{message:i}=te("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),q(this,"isValidRequest",async r=>{if(!pr(r)){const{message:c}=te("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(!x3(a,s)){const{message:c}=te("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!nO(i)){const{message:c}=te("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!oO(a,s,i.method)){const{message:c}=te("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!uO(o,h1)){const{message:c}=te("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${h1.min} and ${h1.max}`);throw new Error(c)}}),q(this,"isValidRespond",async r=>{var n;if(!pr(r)){const{message:o}=te("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(!iO(s)){const{message:o}=te("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),q(this,"isValidPing",async r=>{if(!pr(r)){const{message:i}=te("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),q(this,"isValidEmit",async r=>{if(!pr(r)){const{message:a}=te("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(!x3(o,s)){const{message:a}=te("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!sO(i)){const{message:a}=te("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!aO(o,s,i.name)){const{message:a}=te("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),q(this,"isValidDisconnect",async r=>{if(!pr(r)){const{message:i}=te("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),q(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(!ut(i,!1))throw new Error("uri is required parameter");if(!ut(s,!1))throw new Error("domain is required parameter");if(!ut(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>ks(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ks(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),q(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||cl,validation:"UNKNOWN",origin:o.url||""}};try{if(a===it.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}),q(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=te("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),q(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),q(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)}}}),q(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=te("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),q(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,l,u,d,h;return!r||n!==it.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((d=r?.redirect)==null?void 0:d.universal)!==""&&((h=r?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),q(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),q(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=Vb(r,"topic")||"",i=decodeURIComponent(Vb(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:it.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),q(this,"registerLinkModeListeners",async()=>{var r;if(r0()||Li()&&(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)}}}),q(this,"getTVFParams",(r,n,i)=>{var s,o,a;if(!((s=n.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,i);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn("Error getting TVF params",l)}return c}),q(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}),q(this,"extractTxHashesFromResult",(r,n)=>{var i;try{if(!n)return[];const s=r.method,o=NU[s];if(s==="sui_signTransaction")return[kT(n.transactionBytes)];if(s==="near_signTransaction")return[fy(n)];if(s==="near_signTransactions")return n.map(c=>fy(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=n.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[AO({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return Kr(n)?n.map(c=>py(c)):[py(n)];if(s==="cosmos_signDirect")return[DT(n)];if(typeof n=="string")return[n];const a=n[o.key];if(Kr(a))return s==="solana_signAllTransactions"?a.map(c=>OT(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}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}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ct.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(zd)?this.client.auth.authKeys.get(zd):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===it.link_mode?Ji:fr});Z0(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Vr(n)})):Ud(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(Jr.expired,async e=>{const{topic:r,id:n}=qb(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,te("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,te("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(Ws.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Ws.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ut(e,!1)){const{message:r}=te("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}=te("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Mi(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=te("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ut(e,!1)){const{message:r}=te("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}=te("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Mi(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=te("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=te("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(ut(e,!1)){const{message:r}=te("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=te("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!tO(e)){const{message:r}=te("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=te("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Mi(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=te("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class WU extends qs{constructor(e,r){super(e,r,SU,u1),this.core=e,this.logger=r}}class HU extends qs{constructor(e,r){super(e,r,IU,u1),this.core=e,this.logger=r}}class qU extends qs{constructor(e,r){super(e,r,$U,u1,n=>n.id),this.core=e,this.logger=r}}class VU extends qs{constructor(e,r){super(e,r,DU,jd,()=>zd),this.core=e,this.logger=r}}class KU extends qs{constructor(e,r){super(e,r,BU,jd),this.core=e,this.logger=r}}class GU extends qs{constructor(e,r){super(e,r,RU,jd,n=>n.id),this.core=e,this.logger=r}}var ZU=Object.defineProperty,YU=(t,e,r)=>e in t?ZU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p1=(t,e,r)=>YU(t,typeof e!="symbol"?e+"":e,r);class JU{constructor(e,r){this.core=e,this.logger=r,p1(this,"authKeys"),p1(this,"pairingTopics"),p1(this,"requests"),this.authKeys=new VU(this.core,this.logger),this.pairingTopics=new KU(this.core,this.logger),this.requests=new GU(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var XU=Object.defineProperty,QU=(t,e,r)=>e in t?XU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oe=(t,e,r)=>QU(t,typeof e!="symbol"?e+"":e,r);class g1 extends Xk{constructor(e){super(e),Oe(this,"protocol",qv),Oe(this,"version",Vv),Oe(this,"name",d1.name),Oe(this,"metadata"),Oe(this,"core"),Oe(this,"logger"),Oe(this,"events",new Tt.exports.EventEmitter),Oe(this,"engine"),Oe(this,"session"),Oe(this,"proposal"),Oe(this,"pendingRequest"),Oe(this,"auth"),Oe(this,"signConfig"),Oe(this,"on",(n,i)=>this.events.on(n,i)),Oe(this,"once",(n,i)=>this.events.once(n,i)),Oe(this,"off",(n,i)=>this.events.off(n,i)),Oe(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Oe(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Oe(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Oe(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Oe(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||d1.name,this.metadata=_I(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:On(nl({level:e?.logger||d1.logger}));this.core=e?.core||new AU(e),this.logger=tr(r,this.name),this.session=new HU(this.core,this.logger),this.proposal=new WU(this.core,this.logger),this.pendingRequest=new qU(this.core,this.logger),this.engine=new zU(this),this.auth=new JU(this.core,this.logger)}static async init(e){const r=new g1(e);return await r.initialize(),r}get context(){return wr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var w1={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof vt<"u"&&vt,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 vt<"u"&&vt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(w){return w&&DataView.prototype.isPrototypeOf(w)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(w){return w&&u.indexOf(Object.prototype.toString.call(w))>-1};function h(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function f(w){return typeof w!="string"&&(w=String(w)),w}function p(w){var m={next:function(){var A=w.shift();return{done:A===void 0,value:A}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function g(w){this.map={},w instanceof g?w.forEach(function(m,A){this.append(A,m)},this):Array.isArray(w)?w.forEach(function(m){if(m.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+m.length);this.append(m[0],m[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(m){this.append(m,w[m])},this)}g.prototype.append=function(w,m){w=h(w),m=f(m);var A=this.map[w];this.map[w]=A?A+", "+m:m},g.prototype.delete=function(w){delete this.map[h(w)]},g.prototype.get=function(w){return w=h(w),this.has(w)?this.map[w]:null},g.prototype.has=function(w){return this.map.hasOwnProperty(h(w))},g.prototype.set=function(w,m){this.map[h(w)]=f(m)},g.prototype.forEach=function(w,m){for(var A in this.map)this.map.hasOwnProperty(A)&&w.call(m,this.map[A],A,this)},g.prototype.keys=function(){var w=[];return this.forEach(function(m,A){w.push(A)}),p(w)},g.prototype.values=function(){var w=[];return this.forEach(function(m){w.push(m)}),p(w)},g.prototype.entries=function(){var w=[];return this.forEach(function(m,A){w.push([A,m])}),p(w)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function b(w){if(!w._noBody){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}}function C(w){return new Promise(function(m,A){w.onload=function(){m(w.result)},w.onerror=function(){A(w.error)}})}function x(w){var m=new FileReader,A=C(m);return m.readAsArrayBuffer(w),A}function y(w){var m=new FileReader,A=C(m),T=/charset=([A-Za-z0-9_-]+)/.exec(w.type),N=T?T[1]:"utf-8";return m.readAsText(w,N),A}function v(w){for(var m=new Uint8Array(w),A=new Array(m.length),T=0;T<m.length;T++)A[T]=String.fromCharCode(m[T]);return A.join("")}function _(w){if(w.slice)return w.slice(0);var m=new Uint8Array(w.byteLength);return m.set(new Uint8Array(w)),m.buffer}function O(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:c.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:c.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():c.arrayBuffer&&c.blob&&l(w)?(this._bodyArrayBuffer=_(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||d(w))?this._bodyArrayBuffer=_(w):this._bodyText=w=Object.prototype.toString.call(w):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof w=="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(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var w=b(this);if(w)return w;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 w=b(this);return w||(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(x);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var w=b(this);if(w)return w;if(this._bodyBlob)return y(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(v(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($)}),this.json=function(){return this.text().then(JSON.parse)},this}var B=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(w){var m=w.toUpperCase();return B.indexOf(m)>-1?m:w}function E(w,m){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var A=m.body;if(w instanceof E){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,m.headers||(this.headers=new g(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!A&&w._bodyInit!=null&&(A=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new g(m.headers)),this.method=R(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var T=/([?&])_=[^&]*/;if(T.test(this.url))this.url=this.url.replace(T,"$1_="+new Date().getTime());else{var N=/\?/;this.url+=(N.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function $(w){var m=new FormData;return w.trim().split("&").forEach(function(A){if(A){var T=A.split("="),N=T.shift().replace(/\+/g," "),k=T.join("=").replace(/\+/g," ");m.append(decodeURIComponent(N),decodeURIComponent(k))}}),m}function S(w){var m=new g,A=w.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(T){return T.indexOf(`
|
|
46
|
-
`)===0?T.substr(1,T.length):T}).forEach(function(T){var N=T.split(":"),k=N.shift().trim();if(k){var j=N.join(":").trim();try{m.append(k,j)}catch(z){console.warn("Response "+z.message)}}}),m}O.call(E.prototype);function D(w,m){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new g(m.headers),this.url=m.url||"",this._initBody(w)}O.call(D.prototype),D.prototype.clone=function(){return new D(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},D.error=function(){var w=new D(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var U=[301,302,303,307,308];D.redirect=function(w,m){if(U.indexOf(m)===-1)throw new RangeError("Invalid status code");return new D(null,{status:m,headers:{location:w}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,A){this.message=m,this.name=A;var T=Error(m);this.stack=T.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function M(w,m){return new Promise(function(A,T){var N=new E(w,m);if(N.signal&&N.signal.aborted)return T(new o.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function j(){k.abort()}k.onload=function(){var H={statusText:k.statusText,headers:S(k.getAllResponseHeaders()||"")};N.url.indexOf("file://")===0&&(k.status<200||k.status>599)?H.status=200:H.status=k.status,H.url="responseURL"in k?k.responseURL:H.headers.get("X-Request-URL");var J="response"in k?k.response:k.responseText;setTimeout(function(){A(new D(J,H))},0)},k.onerror=function(){setTimeout(function(){T(new TypeError("Network request failed"))},0)},k.ontimeout=function(){setTimeout(function(){T(new TypeError("Network request timed out"))},0)},k.onabort=function(){setTimeout(function(){T(new o.DOMException("Aborted","AbortError"))},0)};function z(H){try{return H===""&&a.location.href?a.location.href:H}catch{return H}}if(k.open(N.method,z(N.url),!0),N.credentials==="include"?k.withCredentials=!0:N.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(c.blob?k.responseType="blob":c.arrayBuffer&&(k.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof g||a.Headers&&m.headers instanceof a.Headers)){var G=[];Object.getOwnPropertyNames(m.headers).forEach(function(H){G.push(h(H)),k.setRequestHeader(H,f(m.headers[H]))}),N.headers.forEach(function(H,J){G.indexOf(J)===-1&&k.setRequestHeader(J,H)})}else N.headers.forEach(function(H,J){k.setRequestHeader(J,H)});N.signal&&(N.signal.addEventListener("abort",j),k.onreadystatechange=function(){k.readyState===4&&N.signal.removeEventListener("abort",j)}),k.send(typeof N._bodyInit>"u"?null:N._bodyInit)})}return M.polyfill=!0,a.fetch||(a.fetch=M,a.Headers=g,a.Request=E,a.Response=D),o.Headers=g,o.Request=E,o.Response=D,o.fetch=M,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})(w1,w1.exports);var Jv=L6(w1.exports),eL=Object.defineProperty,tL=Object.defineProperties,rL=Object.getOwnPropertyDescriptors,Xv=Object.getOwnPropertySymbols,nL=Object.prototype.hasOwnProperty,iL=Object.prototype.propertyIsEnumerable,Qv=(t,e,r)=>e in t?eL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,e5=(t,e)=>{for(var r in e||(e={}))nL.call(e,r)&&Qv(t,r,e[r]);if(Xv)for(var r of Xv(e))iL.call(e,r)&&Qv(t,r,e[r]);return t},t5=(t,e)=>tL(t,rL(e));const sL={Accept:"application/json","Content-Type":"application/json"},oL="POST",r5={headers:sL,method:oL},n5=10;class bn{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Tt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!X3(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=ri(e),n=await(await Jv(this.url,t5(e5({},r5),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!X3(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=ri({id:1,jsonrpc:"2.0",method:"test",params:[]});await Jv(e,t5(e5({},r5),{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"?$s(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=Rd(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return V3(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>n5&&this.events.setMaxListeners(n5)}}var aL=Object.defineProperty,i5=Object.getOwnPropertySymbols,cL=Object.prototype.hasOwnProperty,lL=Object.prototype.propertyIsEnumerable,s5=(t,e,r)=>e in t?aL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,o5=(t,e)=>{for(var r in e||(e={}))cL.call(e,r)&&s5(t,r,e[r]);if(i5)for(var r of i5(e))lL.call(e,r)&&s5(t,r,e[r]);return t};const a5="error",uL="wss://relay.walletconnect.org",dL="wc",hL="universal_provider",Wd=`${dL}@2:${hL}:`,c5="https://rpc.walletconnect.org/v1/",l5="generic",fL=`${c5}bundler`,Qr={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function m1(t){return t==null||typeof t!="object"&&typeof t!="function"}function u5(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function d5(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const pL="[object RegExp]",h5="[object String]",f5="[object Number]",p5="[object Boolean]",g5="[object Arguments]",gL="[object Symbol]",wL="[object Date]",mL="[object Map]",bL="[object Set]",yL="[object Array]",vL="[object ArrayBuffer]",CL="[object Object]",EL="[object DataView]",xL="[object Uint8Array]",_L="[object Uint8ClampedArray]",AL="[object Uint16Array]",SL="[object Uint32Array]",IL="[object Int8Array]",TL="[object Int16Array]",NL="[object Int32Array]",$L="[object Float32Array]",OL="[object Float64Array]";function b1(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function kL(t,e){return ta(t,void 0,t,new Map,e)}function ta(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(m1(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]=ta(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,ta(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(ta(a,void 0,r,n,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(b1(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=ta(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),Vs(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),Vs(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),Vs(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,Vs(o,t,r,n,i),o}if(typeof t=="object"&&PL(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),Vs(o,t,r,n,i),o}return t}function Vs(t,e,r=t,n,i){const s=[...Object.keys(e),...u5(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=ta(e[a],a,r,n,i))}}function PL(t){switch(d5(t)){case g5:case yL:case vL:case EL:case p5:case wL:case $L:case OL:case IL:case TL:case NL:case mL:case f5:case CL:case pL:case bL:case h5:case gL:case xL:case _L:case AL:case SL:return!0;default:return!1}}function DL(t,e){return kL(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 f5:case h5:case p5:{const a=new t.constructor(t?.valueOf());return Vs(a,t),a}case g5:{const a={};return Vs(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function w5(t){return DL(t)}function m5(t){return t!==null&&typeof t=="object"&&d5(t)==="[object Arguments]"}function b5(t){return typeof t=="object"&&t!==null}function BL(){}function RL(t){return b1(t)}function UL(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 LL(t){if(m1(t))return t;if(Array.isArray(t)||b1(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 ML(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=y1(i,o,n,new Map)}return i}function y1(t,e,r,n){var i;if(m1(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return LL(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),...u5(e)];for(let o=0;o<s.length;o++){const a=s[o];let c=e[a],l=t[a];if(m5(c)&&(c=o5({},c)),m5(l)&&(l=o5({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=w5(c)),Array.isArray(c))if(typeof l=="object"&&l!=null){const d=[],h=Reflect.ownKeys(l);for(let f=0;f<h.length;f++){const p=h[f];d[p]=l[p]}l=d}else l=[];const u=r(l,c,a,t,e,n);u!=null?t[a]=u:Array.isArray(c)||b5(l)&&b5(c)?t[a]=y1(l,c,r,n):l==null&&UL(c)?t[a]=y1({},c,r,n):l==null&&RL(c)?t[a]=w5(c):(l===void 0||c!==void 0)&&(t[a]=c)}return t}function FL(t,...e){return ML(t,...e,BL)}var jL=Object.defineProperty,zL=Object.defineProperties,WL=Object.getOwnPropertyDescriptors,y5=Object.getOwnPropertySymbols,HL=Object.prototype.hasOwnProperty,qL=Object.prototype.propertyIsEnumerable,v5=(t,e,r)=>e in t?jL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hd=(t,e)=>{for(var r in e||(e={}))HL.call(e,r)&&v5(t,r,e[r]);if(y5)for(var r of y5(e))qL.call(e,r)&&v5(t,r,e[r]);return t},VL=(t,e)=>zL(t,WL(e));function Pr(t,e,r){var n;const i=ks(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${c5}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Ks(t){return t.includes(":")?t.split(":")[1]:t}function C5(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function KL(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 E5(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var n,i;return((n=r?.chains)==null?void 0:n.length)&&((i=r?.chains)==null?void 0:i.length)>0}))}function qd(t={},e={}){const r=E5(x5(t)),n=E5(x5(e));return FL(r,n)}function x5(t){var e,r,n,i,s;const o={};if(!$n(t))return o;for(const[a,c]of Object.entries(t)){const l=Sd(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},f=Zo(a);o[f]=VL(Hd(Hd({},o[f]),c),{chains:Tn(l,(e=o[f])==null?void 0:e.chains),methods:Tn(u,(r=o[f])==null?void 0:r.methods),events:Tn(d,(n=o[f])==null?void 0:n.events)}),($n(h)||$n(((i=o[f])==null?void 0:i.rpcMap)||{}))&&(o[f].rpcMap=Hd(Hd({},h),(s=o[f])==null?void 0:s.rpcMap))}return o}function _5(t){return t.includes(":")?t.split(":")[2]:t}function A5(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=Sd(r)?[r]:n.chains?n.chains:C5(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function v1(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 S5={},Ue=t=>S5[t],C1=(t,e)=>{S5[t]=e};var GL=Object.defineProperty,I5=Object.getOwnPropertySymbols,ZL=Object.prototype.hasOwnProperty,YL=Object.prototype.propertyIsEnumerable,T5=(t,e,r)=>e in t?GL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,N5=(t,e)=>{for(var r in e||(e={}))ZL.call(e,r)&&T5(t,r,e[r]);if(I5)for(var r of I5(e))YL.call(e,r)&&T5(t,r,e[r]);return t};const $5="eip155",JL=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],XL=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,E1=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,O5=t=>Object.keys(t).filter(e=>JL.includes(e)).reduce((e,r)=>(e[r]=t[r],e),{}),QL=(t,e,r)=>{const{sessionProperties:n={},scopedProperties:i={}}=t,s={};if(!$n(i)&&!$n(n))return;const o=O5(n);for(const a of r){const c=XL(a);if(!c)continue;s[E1(c)]=o;const l=i?.[`${$5}:${c}`];if(l){const u=l?.[`${$5}:${c}:${e}`];s[E1(c)]=N5(N5({},s[E1(c)]),O5(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var eM=Object.defineProperty,tM=(t,e,r)=>e in t?eM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ra=(t,e,r)=>tM(t,typeof e!="symbol"?e+"":e,r);class rM{constructor(e){ra(this,"name","polkadot"),ra(this,"client"),ra(this,"httpProviders"),ra(this,"events"),ra(this,"namespace"),ra(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var nM=Object.defineProperty,iM=Object.defineProperties,sM=Object.getOwnPropertyDescriptors,k5=Object.getOwnPropertySymbols,oM=Object.prototype.hasOwnProperty,aM=Object.prototype.propertyIsEnumerable,x1=(t,e,r)=>e in t?nM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,P5=(t,e)=>{for(var r in e||(e={}))oM.call(e,r)&&x1(t,r,e[r]);if(k5)for(var r of k5(e))aM.call(e,r)&&x1(t,r,e[r]);return t},D5=(t,e)=>iM(t,sM(e)),na=(t,e,r)=>x1(t,typeof e!="symbol"?e+"":e,r);class cM{constructor(e){na(this,"name","eip155"),na(this,"client"),na(this,"chainId"),na(this,"namespace"),na(this,"httpProviders"),na(this,"events"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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||Pr(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("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(Ks(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,s,o;const a=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(i=e.request)==null?void 0:i.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},d=`${a}${c.join(",")}`,h=u?.[d];if(h)return h;let f;try{f=QL(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(f)return f;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:D5(P5({},l.sessionProperties||{}),{capabilities:D5(P5({},u||{}),{[d]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}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(Dn("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`${fL}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var lM=Object.defineProperty,uM=(t,e,r)=>e in t?lM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ia=(t,e,r)=>uM(t,typeof e!="symbol"?e+"":e,r);class dM{constructor(e){ia(this,"name","solana"),ia(this,"client"),ia(this,"httpProviders"),ia(this,"events"),ia(this,"namespace"),ia(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var hM=Object.defineProperty,fM=(t,e,r)=>e in t?hM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sa=(t,e,r)=>fM(t,typeof e!="symbol"?e+"":e,r);class pM{constructor(e){sa(this,"name","cosmos"),sa(this,"client"),sa(this,"httpProviders"),sa(this,"events"),sa(this,"namespace"),sa(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var gM=Object.defineProperty,wM=(t,e,r)=>e in t?gM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oa=(t,e,r)=>wM(t,typeof e!="symbol"?e+"":e,r);class mM{constructor(e){oa(this,"name","algorand"),oa(this,"client"),oa(this,"httpProviders"),oa(this,"events"),oa(this,"namespace"),oa(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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||Pr(`${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(Qr.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||Pr(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new Zr(new bn(n,Ue("disableProviderPing")))}}var bM=Object.defineProperty,yM=(t,e,r)=>e in t?bM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e,r)=>yM(t,typeof e!="symbol"?e+"":e,r);class vM{constructor(e){aa(this,"name","cip34"),aa(this,"client"),aa(this,"httpProviders"),aa(this,"events"),aa(this,"namespace"),aa(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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 Zr(new bn(n,Ue("disableProviderPing")))}}var CM=Object.defineProperty,EM=(t,e,r)=>e in t?CM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ca=(t,e,r)=>EM(t,typeof e!="symbol"?e+"":e,r);class xM{constructor(e){ca(this,"name","elrond"),ca(this,"client"),ca(this,"httpProviders"),ca(this,"events"),ca(this,"namespace"),ca(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var _M=Object.defineProperty,AM=(t,e,r)=>e in t?_M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,la=(t,e,r)=>AM(t,typeof e!="symbol"?e+"":e,r);class SM{constructor(e){la(this,"name","multiversx"),la(this,"client"),la(this,"httpProviders"),la(this,"events"),la(this,"namespace"),la(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var IM=Object.defineProperty,TM=(t,e,r)=>e in t?IM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ua=(t,e,r)=>TM(t,typeof e!="symbol"?e+"":e,r);class NM{constructor(e){ua(this,"name","near"),ua(this,"client"),ua(this,"httpProviders"),ua(this,"events"),ua(this,"namespace"),ua(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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||Pr(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Qr.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||Pr(e,this.namespace);return typeof n>"u"?void 0:new Zr(new bn(n,Ue("disableProviderPing")))}}var $M=Object.defineProperty,OM=(t,e,r)=>e in t?$M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,da=(t,e,r)=>OM(t,typeof e!="symbol"?e+"":e,r);class kM{constructor(e){da(this,"name","tezos"),da(this,"client"),da(this,"httpProviders"),da(this,"events"),da(this,"namespace"),da(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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||Pr(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Qr.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||Pr(e,this.namespace);return typeof n>"u"?void 0:new Zr(new bn(n))}}var PM=Object.defineProperty,DM=(t,e,r)=>e in t?PM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ha=(t,e,r)=>DM(t,typeof e!="symbol"?e+"":e,r);class BM{constructor(e){ha(this,"name",l5),ha(this,"client"),ha(this,"httpProviders"),ha(this,"events"),ha(this,"namespace"),ha(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Qr.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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return ks(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const n={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(i=>{const s=ks(i);n[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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var RM=Object.defineProperty,UM=Object.defineProperties,LM=Object.getOwnPropertyDescriptors,B5=Object.getOwnPropertySymbols,MM=Object.prototype.hasOwnProperty,FM=Object.prototype.propertyIsEnumerable,_1=(t,e,r)=>e in t?RM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vd=(t,e)=>{for(var r in e||(e={}))MM.call(e,r)&&_1(t,r,e[r]);if(B5)for(var r of B5(e))FM.call(e,r)&&_1(t,r,e[r]);return t},A1=(t,e)=>UM(t,LM(e)),en=(t,e,r)=>_1(t,typeof e!="symbol"?e+"":e,r);class Kd{constructor(e){en(this,"client"),en(this,"namespaces"),en(this,"optionalNamespaces"),en(this,"sessionProperties"),en(this,"scopedProperties"),en(this,"events",new Tt.exports),en(this,"rpcProviders",{}),en(this,"session"),en(this,"providerOpts"),en(this,"logger"),en(this,"uri"),en(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:On(nl({level:e?.logger||a5})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new Kd(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:Vd({},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,ol(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:nt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri: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=A5(this.session.namespaces);this.namespaces=qd(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=A5(i.namespaces);return this.namespaces=qd(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);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!Kr(r))return;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}`)}catch(r){this.logger.warn("Failed to cleanup pending pairings",r)}}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 g1.init({core:this.providerOpts.core,logger:this.providerOpts.logger||a5,relayUrl:this.providerOpts.relayUrl||uL,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=>Zo(r)))];C1("client",this.client),C1("events",this.events),C1("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=KL(r,this.session);if(n?.length===0)return;const i=C5(n),s=qd(this.namespaces,this.optionalNamespaces),o=A1(Vd({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new cM({namespace:o});break;case"algorand":this.rpcProviders[r]=new mM({namespace:o});break;case"solana":this.rpcProviders[r]=new dM({namespace:o});break;case"cosmos":this.rpcProviders[r]=new pM({namespace:o});break;case"polkadot":this.rpcProviders[r]=new rM({namespace:o});break;case"cip34":this.rpcProviders[r]=new vM({namespace:o});break;case"elrond":this.rpcProviders[r]=new xM({namespace:o});break;case"multiversx":this.rpcProviders[r]=new SM({namespace:o});break;case"near":this.rpcProviders[r]=new NM({namespace:o});break;case"tezos":this.rpcProviders[r]=new kM({namespace:o});break;default:this.rpcProviders[r]=new BM({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&&Kr(o)&&this.events.emit("accountsChanged",o.map(_5))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Zo(o),l=v1(o)!==v1(a)?`${c}:${v1(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=A1(Vd({},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",A1(Vd({},nt("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Qr.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[l5]}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;this.optionalNamespaces=qd(r,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=>Zo(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=Zo(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(_5);if(!Kr(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,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(`${Wd}/${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(`${Wd}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Wd}/${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(Wd)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}}const jM=Kd,zM="wc",WM="ethereum_provider",HM=`${zM}@2:${WM}:`,qM="https://rpc.walletconnect.org/v1/",Gd=["eth_sendTransaction","personal_sign"],R5=["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"],Zd=["chainChanged","accountsChanged"],U5=["chainChanged","accountsChanged","message","disconnect","connect"],VM=async()=>{const{createAppKit:t}=await Promise.resolve().then(function(){return Wj});return t};var KM=Object.defineProperty,GM=Object.defineProperties,ZM=Object.getOwnPropertyDescriptors,L5=Object.getOwnPropertySymbols,YM=Object.prototype.hasOwnProperty,JM=Object.prototype.propertyIsEnumerable,S1=(t,e,r)=>e in t?KM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gs=(t,e)=>{for(var r in e||(e={}))YM.call(e,r)&&S1(t,r,e[r]);if(L5)for(var r of L5(e))JM.call(e,r)&&S1(t,r,e[r]);return t},wl=(t,e)=>GM(t,ZM(e)),Dr=(t,e,r)=>S1(t,typeof e!="symbol"?e+"":e,r);function Yd(t){return Number(t[0].split(":")[1])}function Jd(t){return`0x${t.toString(16)}`}function XM(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!Kr(e))throw new Error("Invalid chains");const c={chains:e,methods:n||Gd,events:s||Zd,rpcMap:Gs({},e.length?{[Yd(e)]:a[Yd(e)]}:{})},l=s?.filter(f=>!Zd.includes(f)),u=n?.filter(f=>!Gd.includes(f));if(!r&&!o&&!i&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const d=l?.length&&u?.length||!r,h={chains:[...new Set(d?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:R5))],events:[...new Set(c.events.concat(o!=null&&o.length?o:U5))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?h:void 0}}class Xd{constructor(){Dr(this,"events",new Tt.exports.EventEmitter),Dr(this,"namespace","eip155"),Dr(this,"accounts",[]),Dr(this,"signer"),Dr(this,"chainId",1),Dr(this,"modal"),Dr(this,"rpc"),Dr(this,"STORAGE_KEY",HM),Dr(this,"on",(e,r)=>(this.events.on(e,r),this)),Dr(this,"once",(e,r)=>(this.events.once(e,r),this)),Dr(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Dr(this,"off",(e,r)=>(this.events.off(e,r),this)),Dr(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Xd;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:n,optional:i}=XM(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const d=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(wl(Gs({namespaces:Gs({},n&&{[this.namespace]:n})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic,scopedProperties:d})).then(h=>{a(h)}).catch(h=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(h.message))})});if(!s)return;const o=Rb(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Jd(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(wl(Gs({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=i.session;if(s){const o=Rb(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Jd(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(n=this.modal)==null||n.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Jd(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",wl(Gs({},nt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Jd(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||Gd:[],c=i.length?e?.events||Zd:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],d=e?.rpcMap||this.buildRpcMap(o,e.projectId),h=e?.qrModalOptions||void 0;return{chains:i?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:d,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:h,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Yd(this.rpc.chains):Yd(this.rpc.optionalChains),this.signer=await jM.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 n=await VM(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return Qj}),s=i(wl(Gs({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!s.networks.length)throw new Error("No networks found for WalletConnect\xB7");r=n(wl(Gs({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&Kr(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&Kr(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])||`${qM}?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 QM=Xd;var M5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){var r=1e3,n=6e4,i=36e5,s="millisecond",o="second",a="minute",c="hour",l="day",u="week",d="month",h="quarter",f="year",p="date",g="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,C=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,x={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(M){var w=["th","st","nd","rd"],m=M%100;return"["+M+(w[(m-20)%10]||w[m]||w[0])+"]"}},y=function(M,w,m){var A=String(M);return!A||A.length>=w?M:""+Array(w+1-A.length).join(m)+M},v={s:y,z:function(M){var w=-M.utcOffset(),m=Math.abs(w),A=Math.floor(m/60),T=m%60;return(w<=0?"+":"-")+y(A,2,"0")+":"+y(T,2,"0")},m:function M(w,m){if(w.date()<m.date())return-M(m,w);var A=12*(m.year()-w.year())+(m.month()-w.month()),T=w.clone().add(A,d),N=m-T<0,k=w.clone().add(A+(N?-1:1),d);return+(-(A+(m-T)/(N?T-k:k-T))||0)},a:function(M){return M<0?Math.ceil(M)||0:Math.floor(M)},p:function(M){return{M:d,y:f,w:u,d:l,D:p,h:c,m:a,s:o,ms:s,Q:h}[M]||String(M||"").toLowerCase().replace(/s$/,"")},u:function(M){return M===void 0}},_="en",O={};O[_]=x;var B="$isDayjsObject",R=function(M){return M instanceof D||!(!M||!M[B])},E=function M(w,m,A){var T;if(!w)return _;if(typeof w=="string"){var N=w.toLowerCase();O[N]&&(T=N),m&&(O[N]=m,T=N);var k=w.split("-");if(!T&&k.length>1)return M(k[0])}else{var j=w.name;O[j]=w,T=j}return!A&&T&&(_=T),T||!A&&_},$=function(M,w){if(R(M))return M.clone();var m=typeof w=="object"?w:{};return m.date=M,m.args=arguments,new D(m)},S=v;S.l=E,S.i=R,S.w=function(M,w){return $(M,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var D=function(){function M(m){this.$L=E(m.locale,null,!0),this.parse(m),this.$x=this.$x||m.x||{},this[B]=!0}var w=M.prototype;return w.parse=function(m){this.$d=function(A){var T=A.date,N=A.utc;if(T===null)return new Date(NaN);if(S.u(T))return new Date;if(T instanceof Date)return new Date(T);if(typeof T=="string"&&!/Z$/i.test(T)){var k=T.match(b);if(k){var j=k[2]-1||0,z=(k[7]||"0").substring(0,3);return N?new Date(Date.UTC(k[1],j,k[3]||1,k[4]||0,k[5]||0,k[6]||0,z)):new Date(k[1],j,k[3]||1,k[4]||0,k[5]||0,k[6]||0,z)}}return new Date(T)}(m),this.init()},w.init=function(){var m=this.$d;this.$y=m.getFullYear(),this.$M=m.getMonth(),this.$D=m.getDate(),this.$W=m.getDay(),this.$H=m.getHours(),this.$m=m.getMinutes(),this.$s=m.getSeconds(),this.$ms=m.getMilliseconds()},w.$utils=function(){return S},w.isValid=function(){return this.$d.toString()!==g},w.isSame=function(m,A){var T=$(m);return this.startOf(A)<=T&&T<=this.endOf(A)},w.isAfter=function(m,A){return $(m)<this.startOf(A)},w.isBefore=function(m,A){return this.endOf(A)<$(m)},w.$g=function(m,A,T){return S.u(m)?this[A]:this.set(T,m)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(m,A){var T=this,N=!!S.u(A)||A,k=S.p(m),j=function(ge,Ee){var He=S.w(T.$u?Date.UTC(T.$y,Ee,ge):new Date(T.$y,Ee,ge),T);return N?He:He.endOf(l)},z=function(ge,Ee){return S.w(T.toDate()[ge].apply(T.toDate("s"),(N?[0,0,0,0]:[23,59,59,999]).slice(Ee)),T)},G=this.$W,H=this.$M,J=this.$D,fe="set"+(this.$u?"UTC":"");switch(k){case f:return N?j(1,0):j(31,11);case d:return N?j(1,H):j(0,H+1);case u:var ve=this.$locale().weekStart||0,Se=(G<ve?G+7:G)-ve;return j(N?J-Se:J+(6-Se),H);case l:case p:return z(fe+"Hours",0);case c:return z(fe+"Minutes",1);case a:return z(fe+"Seconds",2);case o:return z(fe+"Milliseconds",3);default:return this.clone()}},w.endOf=function(m){return this.startOf(m,!1)},w.$set=function(m,A){var T,N=S.p(m),k="set"+(this.$u?"UTC":""),j=(T={},T[l]=k+"Date",T[p]=k+"Date",T[d]=k+"Month",T[f]=k+"FullYear",T[c]=k+"Hours",T[a]=k+"Minutes",T[o]=k+"Seconds",T[s]=k+"Milliseconds",T)[N],z=N===l?this.$D+(A-this.$W):A;if(N===d||N===f){var G=this.clone().set(p,1);G.$d[j](z),G.init(),this.$d=G.set(p,Math.min(this.$D,G.daysInMonth())).$d}else j&&this.$d[j](z);return this.init(),this},w.set=function(m,A){return this.clone().$set(m,A)},w.get=function(m){return this[S.p(m)]()},w.add=function(m,A){var T,N=this;m=Number(m);var k=S.p(A),j=function(H){var J=$(N);return S.w(J.date(J.date()+Math.round(H*m)),N)};if(k===d)return this.set(d,this.$M+m);if(k===f)return this.set(f,this.$y+m);if(k===l)return j(1);if(k===u)return j(7);var z=(T={},T[a]=n,T[c]=i,T[o]=r,T)[k]||1,G=this.$d.getTime()+m*z;return S.w(G,this)},w.subtract=function(m,A){return this.add(-1*m,A)},w.format=function(m){var A=this,T=this.$locale();if(!this.isValid())return T.invalidDate||g;var N=m||"YYYY-MM-DDTHH:mm:ssZ",k=S.z(this),j=this.$H,z=this.$m,G=this.$M,H=T.weekdays,J=T.months,fe=T.meridiem,ve=function(Ee,He,yt,Ft){return Ee&&(Ee[He]||Ee(A,N))||yt[He].slice(0,Ft)},Se=function(Ee){return S.s(j%12||12,Ee,"0")},ge=fe||function(Ee,He,yt){var Ft=Ee<12?"AM":"PM";return yt?Ft.toLowerCase():Ft};return N.replace(C,function(Ee,He){return He||function(yt){switch(yt){case"YY":return String(A.$y).slice(-2);case"YYYY":return S.s(A.$y,4,"0");case"M":return G+1;case"MM":return S.s(G+1,2,"0");case"MMM":return ve(T.monthsShort,G,J,3);case"MMMM":return ve(J,G);case"D":return A.$D;case"DD":return S.s(A.$D,2,"0");case"d":return String(A.$W);case"dd":return ve(T.weekdaysMin,A.$W,H,2);case"ddd":return ve(T.weekdaysShort,A.$W,H,3);case"dddd":return H[A.$W];case"H":return String(j);case"HH":return S.s(j,2,"0");case"h":return Se(1);case"hh":return Se(2);case"a":return ge(j,z,!0);case"A":return ge(j,z,!1);case"m":return String(z);case"mm":return S.s(z,2,"0");case"s":return String(A.$s);case"ss":return S.s(A.$s,2,"0");case"SSS":return S.s(A.$ms,3,"0");case"Z":return k}return null}(Ee)||k.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(m,A,T){var N,k=this,j=S.p(A),z=$(m),G=(z.utcOffset()-this.utcOffset())*n,H=this-z,J=function(){return S.m(k,z)};switch(j){case f:N=J()/12;break;case d:N=J();break;case h:N=J()/3;break;case u:N=(H-G)/6048e5;break;case l:N=(H-G)/864e5;break;case c:N=H/i;break;case a:N=H/n;break;case o:N=H/r;break;default:N=H}return T?N:S.a(N)},w.daysInMonth=function(){return this.endOf(d).$D},w.$locale=function(){return O[this.$L]},w.locale=function(m,A){if(!m)return this.$L;var T=this.clone(),N=E(m,A,!0);return N&&(T.$L=N),T},w.clone=function(){return S.w(this.$d,this)},w.toDate=function(){return new Date(this.valueOf())},w.toJSON=function(){return this.isValid()?this.toISOString():null},w.toISOString=function(){return this.$d.toISOString()},w.toString=function(){return this.$d.toUTCString()},M}(),U=D.prototype;return $.prototype=U,[["$ms",s],["$s",o],["$m",a],["$H",c],["$W",l],["$M",d],["$y",f],["$D",p]].forEach(function(M){U[M[1]]=function(w){return this.$g(w,M[0],M[1])}}),$.extend=function(M,w){return M.$i||(M(w,D,$),M.$i=!0),$},$.locale=E,$.isDayjs=R,$.unix=function(M){return $(1e3*M)},$.en=O[_],$.Ls=O,$.p={},$})})(M5);var I1=M5.exports,F5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){return{name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(r){var n=["th","st","nd","rd"],i=r%100;return"["+r+(n[(i-20)%10]||n[i]||n[0])+"]"}}})})(F5);var eF=F5.exports,j5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){return function(r,n,i){r=r||{};var s=n.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(l,u,d,h){return s.fromToBase(l,u,d,h)}i.en.relativeTime=o,s.fromToBase=function(l,u,d,h,f){for(var p,g,b,C=d.$locale().relativeTime||o,x=r.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],y=x.length,v=0;v<y;v+=1){var _=x[v];_.d&&(p=h?i(l).diff(d,_.d,!0):d.diff(l,_.d,!0));var O=(r.rounding||Math.round)(Math.abs(p));if(b=p>0,O<=_.r||!_.r){O<=1&&v>0&&(_=x[v-1]);var B=C[_.l];f&&(O=f(""+O)),g=typeof B=="string"?B.replace("%d",O):B(O,u,_.l,b);break}}if(u)return g;var R=b?C.future:C.past;return typeof R=="function"?R(g):R.replace("%s",g)},s.to=function(l,u){return a(l,u,this,!0)},s.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?i.utc():i()};s.toNow=function(l){return this.to(c(this),l)},s.fromNow=function(l){return this.from(c(this),l)}}})})(j5);var tF=j5.exports,z5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){return function(r,n,i){i.updateLocale=function(s,o){var a=i.Ls[s];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(z5);var rF=z5.exports;I1.extend(tF),I1.extend(rF);const nF={...eF,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}};I1.locale("en-web3-modal",nF);const oe={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},W5={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(r=>r.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const r=t.find(i=>i.caipNetworkId===e);if(r)return r.name;const[n]=e.split(":");return oe.CHAIN_NAME_MAP?.[n]||void 0}};var iF=20,sF=1,Zs=1e6,H5=1e6,oF=-7,aF=21,cF=!1,ml="[big.js] ",Ys=ml+"Invalid ",Qd=Ys+"decimal places",lF=Ys+"rounding mode",q5=ml+"Division by zero",Ve={},Fn=void 0,uF=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function V5(){function t(e){var r=this;if(!(r instanceof t))return e===Fn?V5():new t(e);if(e instanceof t)r.s=e.s,r.e=e.e,r.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(Ys+"value");e=e===0&&1/e<0?"-0":String(e)}dF(r,e)}r.constructor=t}return t.prototype=Ve,t.DP=iF,t.RM=sF,t.NE=oF,t.PE=aF,t.strict=cF,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function dF(t,e){var r,n,i;if(!uF.test(e))throw Error(Ys+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),i=e.length,n=0;n<i&&e.charAt(n)=="0";)++n;if(n==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=r-n-1,t.c=[],r=0;n<=i;)t.c[r++]=+e.charAt(n++)}return t}function Js(t,e,r,n){var i=t.c;if(r===Fn&&(r=t.constructor.RM),r!==0&&r!==1&&r!==2&&r!==3)throw Error(lF);if(e<1)n=r===3&&(n||!!i[0])||e===0&&(r===1&&i[0]>=5||r===2&&(i[0]>5||i[0]===5&&(n||i[1]!==Fn))),i.length=1,n?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(n=r===1&&i[e]>=5||r===2&&(i[e]>5||i[e]===5&&(n||i[e+1]!==Fn||i[e-1]&1))||r===3&&(n||!!i[0]),i.length=e,n){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function Xs(t,e,r){var n=t.e,i=t.c.join(""),s=i.length;if(e)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)i="0"+i;i="0."+i}else if(n>0)if(++n>s)for(n-=s;n--;)i+="0";else n<s&&(i=i.slice(0,n)+"."+i.slice(n));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&r?"-"+i:i}Ve.abs=function(){var t=new this.constructor(this);return t.s=1,t},Ve.cmp=function(t){var e,r=this,n=r.c,i=(t=new r.constructor(t)).c,s=r.s,o=t.s,a=r.e,c=t.e;if(!n[0]||!i[0])return n[0]?s:i[0]?-o:0;if(s!=o)return s;if(e=s<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=i.length)?a:c,s=-1;++s<o;)if(n[s]!=i[s])return n[s]>i[s]^e?1:-1;return a==c?0:a>c^e?1:-1},Ve.div=function(t){var e=this,r=e.constructor,n=e.c,i=(t=new r(t)).c,s=e.s==t.s?1:-1,o=r.DP;if(o!==~~o||o<0||o>Zs)throw Error(Qd);if(!i[0])throw Error(q5);if(!n[0])return t.s=s,t.c=[t.e=0],t;var a,c,l,u,d,h=i.slice(),f=a=i.length,p=n.length,g=n.slice(0,a),b=g.length,C=t,x=C.c=[],y=0,v=o+(C.e=e.e-t.e)+1;for(C.s=s,s=v<0?0:v,h.unshift(0);b++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(b=g.length))u=a>b?1:-1;else for(d=-1,u=0;++d<a;)if(i[d]!=g[d]){u=i[d]>g[d]?1:-1;break}if(u<0){for(c=b==a?i:h;b;){if(g[--b]<c[b]){for(d=b;d&&!g[--d];)g[d]=9;--g[d],g[b]+=10}g[b]-=c[b]}for(;!g[0];)g.shift()}else break}x[y++]=u?l:++l,g[0]&&u?g[b]=n[f]||0:g=[n[f]]}while((f++<p||g[0]!==Fn)&&s--);return!x[0]&&y!=1&&(x.shift(),C.e--,v--),y>v&&Js(C,v,r.RM,g[0]!==Fn),C},Ve.eq=function(t){return this.cmp(t)===0},Ve.gt=function(t){return this.cmp(t)>0},Ve.gte=function(t){return this.cmp(t)>-1},Ve.lt=function(t){return this.cmp(t)<0},Ve.lte=function(t){return this.cmp(t)<1},Ve.minus=Ve.sub=function(t){var e,r,n,i,s=this,o=s.constructor,a=s.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,s.plus(t);var l=s.c.slice(),u=s.e,d=t.c,h=t.e;if(!l[0]||!d[0])return d[0]?t.s=-c:l[0]?t=new o(s):t.s=1,t;if(a=u-h){for((i=a<0)?(a=-a,n=l):(h=u,n=d),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(r=((i=l.length<d.length)?l:d).length,a=c=0;c<r;c++)if(l[c]!=d[c]){i=l[c]<d[c];break}if(i&&(n=l,l=d,d=n,t.s=-t.s),(c=(r=d.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;r>a;){if(l[--r]<d[r]){for(e=r;e&&!l[--e];)l[e]=9;--l[e],l[r]+=10}l[r]-=d[r]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t},Ve.mod=function(t){var e,r=this,n=r.constructor,i=r.s,s=(t=new n(t)).s;if(!t.c[0])throw Error(q5);return r.s=t.s=1,e=t.cmp(r)==1,r.s=i,t.s=s,e?new n(r):(i=n.DP,s=n.RM,n.DP=n.RM=0,r=r.div(t),n.DP=i,n.RM=s,this.minus(r.times(t)))},Ve.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t},Ve.plus=Ve.add=function(t){var e,r,n,i=this,s=i.constructor;if(t=new s(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new s(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,r=0;e;a[e]%=10)r=(a[--e]=a[e]+l[e]+r)/10|0;for(r&&(a.unshift(r),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t},Ve.pow=function(t){var e=this,r=new e.constructor("1"),n=r,i=t<0;if(t!==~~t||t<-H5||t>H5)throw Error(Ys+"exponent");for(i&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return i?r.div(n):n},Ve.prec=function(t,e){if(t!==~~t||t<1||t>Zs)throw Error(Ys+"precision");return Js(new this.constructor(this),t,e)},Ve.round=function(t,e){if(t===Fn)t=0;else if(t!==~~t||t<-Zs||t>Zs)throw Error(Qd);return Js(new this.constructor(this),t+this.e+1,e)},Ve.sqrt=function(){var t,e,r,n=this,i=n.constructor,s=n.s,o=n.e,a=new i("0.5");if(!n.c[0])return new i(n);if(s<0)throw Error(ml+"No square root");s=Math.sqrt(+Xs(n,!0,!0)),s===0||s===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),s=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):t=new i(s+""),o=t.e+(i.DP+=4);do r=t,t=a.times(r.plus(n.div(r)));while(r.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return Js(t,(i.DP-=4)+t.e+1,i.RM)},Ve.times=Ve.mul=function(t){var e,r=this,n=r.constructor,i=r.c,s=(t=new n(t)).c,o=i.length,a=s.length,c=r.e,l=t.e;if(t.s=r.s==t.s?1:-1,!i[0]||!s[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=s,s=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+s[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t},Ve.toExponential=function(t,e){var r=this,n=r.c[0];if(t!==Fn){if(t!==~~t||t<0||t>Zs)throw Error(Qd);for(r=Js(new r.constructor(r),++t,e);r.c.length<t;)r.c.push(0)}return Xs(r,!0,!!n)},Ve.toFixed=function(t,e){var r=this,n=r.c[0];if(t!==Fn){if(t!==~~t||t<0||t>Zs)throw Error(Qd);for(r=Js(new r.constructor(r),t+r.e+1,e),t=t+r.e+1;r.c.length<t;)r.c.push(0)}return Xs(r,!1,!!n)},Ve[Symbol.for("nodejs.util.inspect.custom")]=Ve.toJSON=Ve.toString=function(){var t=this,e=t.constructor;return Xs(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])},Ve.toNumber=function(){var t=+Xs(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(ml+"Imprecise conversion");return t},Ve.toPrecision=function(t,e){var r=this,n=r.constructor,i=r.c[0];if(t!==Fn){if(t!==~~t||t<1||t>Zs)throw Error(Ys+"precision");for(r=Js(new n(r),t,e);r.c.length<t;)r.c.push(0)}return Xs(r,t<=r.e||r.e<=n.NE||r.e>=n.PE,!!i)},Ve.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(ml+"valueOf disallowed");return Xs(t,t.e<=e.NE||t.e>=e.PE,!0)};var bl=V5();const tt={bigNumber(t){return t?new bl(t):new bl(0)},multiply(t,e){if(t===void 0||e===void 0)return new bl(0);const r=new bl(t),n=new bl(e);return r.times(n)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},hF=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],fF=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],pF=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],gF={getERC20Abi:t=>oe.USDT_CONTRACT_ADDRESSES.includes(t)?pF:hF,getSwapAbi:()=>fF},es={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[r,n,i]=e;if(!r||!n||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:r,chainId:n,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[r,n]=e;if(!r||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:r,chainId:n}}},_e={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function T1(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Ce={setItem(t,e){yl()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(yl())return localStorage.getItem(t)||void 0},removeItem(t){yl()&&localStorage.removeItem(t)},clear(){yl()&&localStorage.clear()}};function yl(){return typeof window<"u"&&typeof localStorage<"u"}function ts(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const wF=Symbol(),K5=Object.getPrototypeOf,N1=new WeakMap,mF=t=>t&&(N1.has(t)?N1.get(t):K5(t)===Object.prototype||K5(t)===Array.prototype),bF=t=>mF(t)&&t[wF]||null,G5=(t,e=!0)=>{N1.set(t,e)},$1=t=>typeof t=="object"&&t!==null,rs=new WeakMap,vl=new WeakSet,yF=(t=Object.is,e=(l,u)=>new Proxy(l,u),r=l=>$1(l)&&!vl.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,u,d=n)=>{const h=i.get(l);if(h?.[0]===u)return h[1];const f=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return G5(f,!0),i.set(l,[u,f]),Reflect.ownKeys(l).forEach(p=>{if(Object.getOwnPropertyDescriptor(f,p))return;const g=Reflect.get(l,p),{enumerable:b}=Reflect.getOwnPropertyDescriptor(l,p),C={value:g,enumerable:b,configurable:!0};if(vl.has(g))G5(g,!1);else if(g instanceof Promise)delete C.value,C.get=()=>d(g);else if(rs.has(g)){const[x,y]=rs.get(g);C.value=s(x,y(),d)}Object.defineProperty(f,p,C)}),Object.preventExtensions(f)},o=new WeakMap,a=[1,1],c=l=>{if(!$1(l))throw new Error("object required");const u=o.get(l);if(u)return u;let d=a[0];const h=new Set,f=(E,$=++a[0])=>{d!==$&&(d=$,h.forEach(S=>S(E,$)))};let p=a[1];const g=(E=++a[1])=>(p!==E&&!h.size&&(p=E,C.forEach(([$])=>{const S=$[1](E);S>d&&(d=S)})),d),b=E=>($,S)=>{const D=[...$];D[1]=[E,...D[1]],f(D,S)},C=new Map,x=(E,$)=>{if(C.has(E))throw new Error("prop listener already exists");if(h.size){const S=$[3](b(E));C.set(E,[$,S])}else C.set(E,[$])},y=E=>{var $;const S=C.get(E);S&&(C.delete(E),($=S[1])==null||$.call(S))},v=E=>(h.add(E),h.size===1&&C.forEach(([S,D],U)=>{if(D)throw new Error("remove already exists");const M=S[3](b(U));C.set(U,[S,M])}),()=>{h.delete(E),h.size===0&&C.forEach(([S,D],U)=>{D&&(D(),C.set(U,[S]))})}),_=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),B=e(_,{deleteProperty(E,$){const S=Reflect.get(E,$);y($);const D=Reflect.deleteProperty(E,$);return D&&f(["delete",[$],S]),D},set(E,$,S,D){const U=Reflect.has(E,$),M=Reflect.get(E,$,D);if(U&&(t(M,S)||o.has(S)&&t(M,o.get(S))))return!0;y($),$1(S)&&(S=bF(S)||S);let w=S;if(S instanceof Promise)S.then(m=>{S.status="fulfilled",S.value=m,f(["resolve",[$],m])}).catch(m=>{S.status="rejected",S.reason=m,f(["reject",[$],m])});else{!rs.has(S)&&r(S)&&(w=c(S));const m=!vl.has(w)&&rs.get(w);m&&x($,m)}return Reflect.set(E,$,w,D),f(["set",[$],S,M]),!0}});o.set(l,B);const R=[_,g,s,v];return rs.set(B,R),Reflect.ownKeys(l).forEach(E=>{const $=Object.getOwnPropertyDescriptor(l,E);"value"in $&&(B[E]=l[E],delete $.value,delete $.writable),Object.defineProperty(_,E,$)}),B})=>[c,rs,vl,t,e,r,n,i,s,o,a],[vF]=yF();function Ye(t={}){return vF(t)}function At(t,e,r){const n=rs.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 Cl(t,e){const r=rs.get(t);r||console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}function Qs(t){return vl.add(t),t}function St(t,e,r,n){let i=t[e];return At(t,()=>{const s=t[e];Object.is(i,s)||r(i=s)},n)}function CF(t){const e=Ye({data:Array.from(t||[]),has(r){return this.data.some(n=>n[0]===r)},set(r,n){const i=this.data.find(s=>s[0]===r);return i?i[1]=n:this.data.push([r,n]),this},get(r){var n;return(n=this.data.find(i=>i[0]===r))==null?void 0:n[1]},delete(r){const n=this.data.findIndex(i=>i[0]===r);return n===-1?!1:(this.data.splice(n,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(r){this.data.forEach(n=>{r(n[1],n[0],this)})},keys(){return this.data.map(r=>r[0]).values()},values(){return this.data.map(r=>r[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}const O1=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Z5=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],EF="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Me={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:O1,SECURE_SITE_DASHBOARD:`${O1}/dashboard`,SECURE_SITE_FAVICON:`${O1}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}},le={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=le.getActiveNamespace(),e=le.getActiveCaipNetworkId(),r=e?e.split(":")[1]:void 0,n=r?isNaN(Number(r))?r:Number(r):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{Ce.setItem(_e.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Ce.getItem(_e.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Ce.removeItem(_e.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Ce.setItem(_e.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Ce.setItem(_e.ACTIVE_CAIP_NETWORK_ID,t),le.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Ce.getItem(_e.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Ce.removeItem(_e.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=T1(t);Ce.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=le.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Ce.setItem(_e.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Ce.getItem(_e.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const r=T1(t);Ce.setItem(r,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Ce.getItem(_e.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=T1(t);return Ce.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{Ce.setItem(_e.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Ce.getItem(_e.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Ce.removeItem(_e.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Ce.getItem(_e.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Ce.getItem(_e.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Ce.setItem(_e.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Ce.getItem(_e.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Ce.getItem(_e.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Ce.setItem(_e.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=le.getConnectedNamespaces();e.includes(t)||(e.push(t),le.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=le.getConnectedNamespaces(),r=e.indexOf(t);r>-1&&(e.splice(r,1),le.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Ce.getItem(_e.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Ce.setItem(_e.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Ce.removeItem(_e.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Ce.getItem(_e.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=le.getBalanceCache();Ce.setItem(_e.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const r=le.getBalanceCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.portfolio))return r.balance;le.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=le.getBalanceCache();e[t.caipAddress]=t,Ce.setItem(_e.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Ce.getItem(_e.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=le.getBalanceCache();Ce.setItem(_e.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const r=le.getNativeBalanceCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.nativeBalance))return r;console.info("Discarding cache for address",t),le.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=le.getNativeBalanceCache();e[t.caipAddress]=t,Ce.setItem(_e.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Ce.getItem(_e.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const r=le.getEnsCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.ens))return r.ens;le.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=le.getEnsCache();e[t.address]=t,Ce.setItem(_e.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=le.getEnsCache();Ce.setItem(_e.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Ce.getItem(_e.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const r=le.getIdentityCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.identity))return r.identity;le.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=le.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Ce.setItem(_e.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=le.getIdentityCache();Ce.setItem(_e.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Ce.removeItem(_e.PORTFOLIO_CACHE),Ce.removeItem(_e.NATIVE_BALANCE_CACHE),Ce.removeItem(_e.ENS_CACHE),Ce.removeItem(_e.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Ce.setItem(_e.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Ce.getItem(_e.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const r={...le.getConnections(),[e]:t};Ce.setItem(_e.CONNECTIONS,JSON.stringify(r))}catch(r){console.error("Unable to sync connections to storage",r)}},getConnections(){try{const t=Ce.getItem(_e.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},Y={isMobile(){return this.isClient()?!!(typeof window?.matchMedia=="function"&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return Y.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Me.TEN_SEC_MS:!0},isAllowedRetry(t,e=Me.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(Y.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const r=new URL(t),n=new URL(e);return r.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Me.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let r;return(...n)=>{function i(){t(...n)}r&&clearTimeout(r),r=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,r=null){if(Y.isHttpUrl(t))return this.formatUniversalUrl(t,e);let n=t,i=r;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const s=encodeURIComponent(e);return{redirect:`${n}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:n}},formatUniversalUrl(t,e){if(!Y.isHttpUrl(t))return this.formatNativeUrl(t,e);let r=t;r.endsWith("/")||(r=`${r}/`);const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,href:r}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?le.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,r){window?.open(t,this.getOpenTargetForPlatform(e),r||"noreferrer noopener")},returnOpenHref(t,e,r){return window?.open(t,this.getOpenTargetForPlatform(e),r||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window.matchMedia?.("(display-mode: standalone)")?.matches,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((r,n)=>{const i=new Image;i.onload=r,i.onerror=n,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,Y.wait(2e3)])},formatBalance(t,e){let r="0.000";if(typeof t=="string"){const n=Number(t);if(n){const i=Math.floor(n*1e3)/1e3;i&&(r=i.toString())}}return`${r}${e?` ${e}`:""}`},formatBalance2(t,e){let r;if(t==="0")r="0";else if(typeof t=="string"){const n=Number(t);n&&(r=n.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:r??"0",rest:r==="0"?"000":"",symbol:e}},getApiUrl(){return oe.W3M_API_URL},getBlockchainApiUrl(){return oe.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return oe.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const r={};return e&&t&&(t.forEach((n,i)=>{r[n]=i}),e.sort((n,i)=>{const s=r[n.id],o=r[i.id];return s!==void 0&&o!==void 0?s-o:s!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const r of t)e+=r.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[r,n]=e.split(".");return{dollars:r,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const r=new Set;return t.filter(n=>{const i=n[e];return r.has(i)?!1:(r.add(i),!0)})},generateSdkVersion(t,e,r){const i=t.length===0?Me.ADAPTER_TYPES.UNIVERSAL:t.map(s=>s.adapterType).join(",");return`${e}-${i}-${r}`},createAccount(t,e,r,n,i){return{namespace:t,address:e,type:r,publicKey:n,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),r=e[0];return e.filter(Boolean).length===3&&r in oe.CHAIN_NAME_MAP},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,r="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",s=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),r,e);return t.replace(s,encodeURIComponent(o))}return this.injectIntoUrl(t,r,e)},injectIntoUrl(t,e,r){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",n),s=e.length,o=i!==-1?i:t.length,a=t.substring(0,n+s),c=t.substring(n+s,o),l=t.substring(i),u=c+r;return a+u+l}};async function El(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class xl{constructor({baseUrl:e,clientId:r}){this.baseUrl=e,this.clientId=r}async get({headers:e,signal:r,cache:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"GET",headers:e,signal:r,cache:n})).json()}async getBlob({headers:e,signal:r,...n}){const i=this.createUrl(n);return(await El(i,{method:"GET",headers:e,signal:r})).blob()}async post({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"POST",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"PUT",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"DELETE",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:r}){const n=new URL(e,this.baseUrl);return r&&Object.entries(r).forEach(([i,s])=>{s&&n.searchParams.append(i,s)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}}const xF={getFeatureValue(t,e){const r=e?.[t];return r===void 0?Me.DEFAULT_FEATURES[t]:r},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(Y.isTelegram()){if(Y.isIos())return t.filter(e=>e!=="google");if(Y.isMac())return t.filter(e=>e!=="x");if(Y.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},pe=Ye({features:Me.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Me.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),W={state:pe,subscribeKey(t,e){return St(pe,t,e)},setOptions(t){Object.assign(pe,t)},setRemoteFeatures(t){if(!t)return;const e={...pe.remoteFeatures,...t};pe.remoteFeatures=e,pe.remoteFeatures?.socials&&(pe.remoteFeatures.socials=xF.filterSocialsByPlatform(pe.remoteFeatures.socials))},setFeatures(t){if(!t)return;pe.features||(pe.features=Me.DEFAULT_FEATURES);const e={...pe.features,...t};pe.features=e},setProjectId(t){pe.projectId=t},setCustomRpcUrls(t){pe.customRpcUrls=t},setAllWallets(t){pe.allWallets=t},setIncludeWalletIds(t){pe.includeWalletIds=t},setExcludeWalletIds(t){pe.excludeWalletIds=t},setFeaturedWalletIds(t){pe.featuredWalletIds=t},setTokens(t){pe.tokens=t},setTermsConditionsUrl(t){pe.termsConditionsUrl=t},setPrivacyPolicyUrl(t){pe.privacyPolicyUrl=t},setCustomWallets(t){pe.customWallets=t},setIsSiweEnabled(t){pe.isSiweEnabled=t},setIsUniversalProvider(t){pe.isUniversalProvider=t},setSdkVersion(t){pe.sdkVersion=t},setMetadata(t){pe.metadata=t},setDisableAppend(t){pe.disableAppend=t},setEIP6963Enabled(t){pe.enableEIP6963=t},setDebug(t){pe.debug=t},setEnableWalletConnect(t){pe.enableWalletConnect=t},setEnableWalletGuide(t){pe.enableWalletGuide=t},setEnableAuthLogger(t){pe.enableAuthLogger=t},setEnableWallets(t){pe.enableWallets=t},setPreferUniversalLinks(t){pe.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){pe.hasMultipleAddresses=t},setSIWX(t){pe.siwx=t},setConnectMethodsOrder(t){pe.features={...pe.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){pe.features={...pe.features,walletFeaturesOrder:t}},setSocialsOrder(t){pe.remoteFeatures={...pe.remoteFeatures,socials:t}},setCollapseWallets(t){pe.features={...pe.features,collapseWallets:t}},setEnableEmbedded(t){pe.enableEmbedded=t},setAllowUnsupportedChain(t){pe.allowUnsupportedChain=t},setManualWCControl(t){pe.manualWCControl=t},setEnableNetworkSwitch(t){pe.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,r])=>{r&&(pe.defaultAccountTypes[e]=r)})},setUniversalProviderConfigOverride(t){pe.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return pe.universalProviderConfigOverride},getSnapshot(){return Cl(pe)}},_F=Object.freeze({enabled:!0,events:[]}),AF=new xl({baseUrl:Y.getAnalyticsUrl(),clientId:null}),SF=5,IF=60*1e3,ns=Ye({..._F}),TF={state:ns,subscribeKey(t,e){return St(ns,t,e)},async sendError(t,e){if(!ns.enabled)return;const r=Date.now();if(ns.events.filter(s=>{const o=new Date(s.properties.timestamp||"").getTime();return r-o<IF}).length>=SF)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};ns.events.push(i);try{if(typeof window>"u")return;const{projectId:s,sdkType:o,sdkVersion:a}=W.state;await AF.post({path:"/e",params:{projectId:s,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:Y.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){ns.enabled=!0},disable(){ns.enabled=!1},clearEvents(){ns.events=[]}};class fa extends Error{constructor(e,r,n){super(e),this.name="AppKitError",this.category=r,this.originalError=n,Object.setPrototypeOf(this,fa.prototype);let i=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const s=n.stack,o=s.indexOf(`
|
|
45
|
+
***************************************************************************** */var V0=function(t,e){return V0=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])},V0(t,e)};function aP(t,e){V0(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var K0=function(){return K0=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},K0.apply(this,arguments)};function cP(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 lP(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 uP(t,e){return function(r,n){e(r,n,t)}}function dP(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function hP(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(d){o(d)}}function c(u){try{l(n.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function fP(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 pP(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function gP(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function G0(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 G3(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 wP(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(G3(arguments[e]));return t}function mP(){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 sl(t){return this instanceof sl?(this.v=t,this):new sl(t)}function bP(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(f){return new Promise(function(p,g){s.push([h,f,p,g])>1||a(h,f)})})}function a(h,f){try{c(n[h](f))}catch(p){d(s[0][3],p)}}function c(h){h.value instanceof sl?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function yP(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:sl(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function vP(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 G0=="function"?G0(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 CP(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function EP(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 xP(t){return t&&t.__esModule?t:{default:t}}function _P(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function AP(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 SP=Object.freeze({__proto__:null,__extends:aP,get __assign(){return K0},__rest:cP,__decorate:lP,__param:uP,__metadata:dP,__awaiter:hP,__generator:fP,__createBinding:pP,__exportStar:gP,__values:G0,__read:G3,__spread:wP,__spreadArrays:mP,__await:sl,__asyncGenerator:bP,__asyncDelegator:yP,__asyncValues:vP,__makeTemplateObject:CP,__importStar:EP,__importDefault:xP,__classPrivateFieldGet:_P,__classPrivateFieldSet:AP}),IP=Mg(SP),ui={},Z3;function TP(){if(Z3)return ui;Z3=1,Object.defineProperty(ui,"__esModule",{value:!0}),ui.isBrowserCryptoAvailable=ui.getSubtleCrypto=ui.getBrowerCrypto=void 0;function t(){return vt?.crypto||vt?.msCrypto||{}}ui.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}ui.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return ui.isBrowserCryptoAvailable=r,ui}var di={},Y3;function NP(){if(Y3)return di;Y3=1,Object.defineProperty(di,"__esModule",{value:!0}),di.isBrowser=di.isNode=di.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}di.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}di.isNode=e;function r(){return!t()&&!e()}return di.isBrowser=r,di}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=IP;e.__exportStar(TP(),t),e.__exportStar(NP(),t)})(K3);function Pn(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Xi(t=6){return BigInt(Pn(t))}function Dn(t,e,r){return{id:r||Pn(),jsonrpc:"2.0",method:t,params:e}}function ol(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Rd(t,e,r){return{id:t,jsonrpc:"2.0",error:$P(e,r)}}function $P(t,e){return typeof t>"u"?q3(W3):(typeof t=="string"&&(t=Object.assign(Object.assign({},q3(q0)),{message:t})),typeof e<"u"&&(t.data=e),sP(t.code)&&(t=oP(t.code)),t)}class OP{}class kP extends OP{constructor(){super()}}class PP extends kP{constructor(e){super()}}const DP="^https?:",BP="^wss?:";function RP(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function J3(t,e){const r=RP(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function X3(t){return J3(t,DP)}function Q3(t){return J3(t,BP)}function UP(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function ev(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Z0(t){return ev(t)&&"method"in t}function Ud(t){return ev(t)&&(Bn(t)||Gr(t))}function Bn(t){return"result"in t}function Gr(t){return"error"in t}class Zr extends PP{constructor(e){super(e),this.events=new Tt.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(Dn(e.method,e.params||[],e.id||Xi().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=>{Gr(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),Ud(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 LP=()=>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"),MP=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",tv=t=>t.split("?")[0],rv=10,FP=LP();class jP{constructor(e){if(this.url=e,this.events=new Tt.exports.EventEmitter,this.registering=!1,!Q3(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(ri(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Q3(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=K3.isReactNative()?void 0:{rejectUnauthorized:!UP(e)},s=new FP(e,[],i);MP()?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"?$s(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=Rd(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return V3(e,tv(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>rv&&this.events.setMaxListeners(rv)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${tv(this.url)}`));return this.events.emit("register_error",r),r}}var zP=Object.defineProperty,nv=Object.getOwnPropertySymbols,WP=Object.prototype.hasOwnProperty,HP=Object.prototype.propertyIsEnumerable,iv=(t,e,r)=>e in t?zP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e)=>{for(var r in e||(e={}))WP.call(e,r)&&iv(t,r,e[r]);if(nv)for(var r of nv(e))HP.call(e,r)&&iv(t,r,e[r]);return t};const sv="wc",ov=2,Ld="core",Rn=`${sv}@2:${Ld}:`,qP={name:Ld,logger:"error"},VP={database:":memory:"},KP="crypto",av="client_ed25519_seed",GP=ee.ONE_DAY,ZP="keychain",YP="0.3",JP="messages",XP="0.3",QP=ee.SIX_HOURS,eD="publisher",cv="irn",tD="error",lv="wss://relay.walletconnect.org",rD="relayer",ct={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"},nD="_subscription",Yr={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},iD=.1,Y0="2.21.7",it={link_mode:"link_mode",relay:"relay"},Md={inbound:"inbound",outbound:"outbound"},sD="0.3",oD="WALLETCONNECT_CLIENT_ID",uv="WALLETCONNECT_LINK_MODE_APPS",Or={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},aD="subscription",cD="0.3",lD="pairing",uD="0.3",al={wc_pairingDelete:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ee.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ee.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:0},res:{ttl:ee.ONE_DAY,prompt:!1,tag:0}}},Ws={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},mn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},dD="history",hD="0.3",fD="expirer",Jr={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},pD="0.3",gD="verify-api",wD="https://verify.walletconnect.com",dv="https://verify.walletconnect.org",cl=dv,mD=`${cl}/v3`,bD=[wD,dv],yD="echo",vD="https://echo.walletconnect.com",Un={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"},hi={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"},Qi={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"},ll={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"},Hs={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"},ul={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"},CD=.1,ED="event-client",xD=86400,_D="https://pulse.walletconnect.org/batch";function AD(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,b=0,C=0,x=p.length;C!==x&&p[C]===0;)C++,g++;for(var y=(x-C)*u+1>>>0,v=new Uint8Array(y);C!==x;){for(var _=p[C],O=0,B=y-1;(_!==0||O<b)&&B!==-1;B--,O++)_+=256*v[B]>>>0,v[B]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=O,C++}for(var R=y-b;R!==y&&v[R]===0;)R++;for(var E=c.repeat(g);R<y;++R)E+=t.charAt(v[R]);return E}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var b=0,C=0;p[g]===c;)b++,g++;for(var x=(p.length-g)*l+1>>>0,y=new Uint8Array(x);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var _=0,O=x-1;(v!==0||_<C)&&O!==-1;O--,_++)v+=a*y[O]>>>0,y[O]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");C=_,g++}if(p[g]!==" "){for(var B=x-C;B!==x&&y[B]===0;)B++;for(var R=new Uint8Array(b+(x-B)),E=b;B!==x;)R[E++]=y[B++];return R}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var SD=AD,ID=SD;const hv=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")},TD=t=>new TextEncoder().encode(t),ND=t=>new TextDecoder().decode(t);class $D{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 OD{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 fv(this,e)}}class kD{constructor(e){this.decoders=e}or(e){return fv(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 fv=(t,e)=>new kD(rr(rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class PD{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new $D(e,r,n),this.decoder=new OD(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Fd=({name:t,prefix:e,encode:r,decode:n})=>new PD(t,e,r,n),dl=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=ID(r,e);return Fd({prefix:t,name:e,encode:n,decode:s=>hv(i(s))})},DD=(t,e,r,n)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},BD=(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},Dt=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Fd({prefix:e,name:t,encode(i){return BD(i,n,r)},decode(i){return DD(i,n,r,t)}}),RD=Fd({prefix:"\0",name:"identity",encode:t=>ND(t),decode:t=>TD(t)});var UD=Object.freeze({__proto__:null,identity:RD});const LD=Dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var MD=Object.freeze({__proto__:null,base2:LD});const FD=Dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jD=Object.freeze({__proto__:null,base8:FD});const zD=dl({prefix:"9",name:"base10",alphabet:"0123456789"});var WD=Object.freeze({__proto__:null,base10:zD});const HD=Dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qD=Dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var VD=Object.freeze({__proto__:null,base16:HD,base16upper:qD});const KD=Dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),GD=Dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ZD=Dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),YD=Dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),JD=Dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),XD=Dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),QD=Dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),eB=Dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tB=Dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var rB=Object.freeze({__proto__:null,base32:KD,base32upper:GD,base32pad:ZD,base32padupper:YD,base32hex:JD,base32hexupper:XD,base32hexpad:QD,base32hexpadupper:eB,base32z:tB});const nB=dl({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),iB=dl({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sB=Object.freeze({__proto__:null,base36:nB,base36upper:iB});const oB=dl({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),aB=dl({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cB=Object.freeze({__proto__:null,base58btc:oB,base58flickr:aB});const lB=Dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),uB=Dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dB=Dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hB=Dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var fB=Object.freeze({__proto__:null,base64:lB,base64pad:uB,base64url:dB,base64urlpad:hB});const pv=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}"),pB=pv.reduce((t,e,r)=>(t[r]=e,t),[]),gB=pv.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function wB(t){return t.reduce((e,r)=>(e+=pB[r],e),"")}function mB(t){const e=[];for(const r of t){const n=gB[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const bB=Fd({prefix:"\u{1F680}",name:"base256emoji",encode:wB,decode:mB});var yB=Object.freeze({__proto__:null,base256emoji:bB}),vB=wv,gv=128,CB=127,EB=~CB,xB=Math.pow(2,31);function wv(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xB;)e[r++]=t&255|gv,t/=128;for(;t&EB;)e[r++]=t&255|gv,t>>>=7;return e[r]=t|0,wv.bytes=r-n+1,e}var _B=J0,AB=128,mv=127;function J0(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw J0.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&mv)<<i:(o&mv)*Math.pow(2,i),i+=7}while(o>=AB);return J0.bytes=s-n,r}var SB=Math.pow(2,7),IB=Math.pow(2,14),TB=Math.pow(2,21),NB=Math.pow(2,28),$B=Math.pow(2,35),OB=Math.pow(2,42),kB=Math.pow(2,49),PB=Math.pow(2,56),DB=Math.pow(2,63),BB=function(t){return t<SB?1:t<IB?2:t<TB?3:t<NB?4:t<$B?5:t<OB?6:t<kB?7:t<PB?8:t<DB?9:10},RB={encode:vB,decode:_B,encodingLength:BB},bv=RB;const yv=(t,e,r=0)=>(bv.encode(t,e,r),e),vv=t=>bv.encodingLength(t),X0=(t,e)=>{const r=e.byteLength,n=vv(t),i=n+vv(r),s=new Uint8Array(i+r);return yv(t,s,0),yv(r,s,n),s.set(e,i),new UB(t,r,e,s)};class UB{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Cv=({name:t,code:e,encode:r})=>new LB(t,e,r);class LB{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?X0(this.code,r):r.then(n=>X0(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Ev=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),MB=Cv({name:"sha2-256",code:18,encode:Ev("SHA-256")}),FB=Cv({name:"sha2-512",code:19,encode:Ev("SHA-512")});var jB=Object.freeze({__proto__:null,sha256:MB,sha512:FB});const xv=0,zB="identity",_v=hv;var WB=Object.freeze({__proto__:null,identity:{code:xv,name:zB,encode:_v,digest:t=>X0(xv,_v(t))}});new TextEncoder,new TextDecoder;const Av=rr(rr(rr(rr(rr(rr(rr(rr(rr(rr({},UD),MD),jD),WD),VD),rB),sB),cB),fB),yB);rr(rr({},jB),WB);function Sv(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function HB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Sv(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Iv(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Tv=Iv("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Q0=Iv("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=HB(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),qB=rr({utf8:Tv,"utf-8":Tv,hex:Av.base16,latin1:Q0,ascii:Q0,binary:Q0},Av);function VB(t,e="utf8"){const r=qB[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Sv(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var KB=Object.defineProperty,GB=(t,e,r)=>e in t?KB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ln=(t,e,r)=>GB(t,typeof e!="symbol"?e+"":e,r);class ZB{constructor(e,r){this.core=e,this.logger=r,Ln(this,"keychain",new Map),Ln(this,"name",ZP),Ln(this,"version",YP),Ln(this,"initialized",!1),Ln(this,"storagePrefix",Rn),Ln(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Ln(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Ln(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),Ln(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=te("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),Ln(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=tr(r,this.name)}get context(){return wr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,e0(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?t0(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YB=Object.defineProperty,JB=(t,e,r)=>e in t?YB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bt=(t,e,r)=>JB(t,typeof e!="symbol"?e+"":e,r);class XB{constructor(e,r,n){this.core=e,this.logger=r,Bt(this,"name",KP),Bt(this,"keychain"),Bt(this,"randomSessionIdentifier",P0()),Bt(this,"initialized",!1),Bt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Bt(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Bt(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=tb(i);return eb(s.publicKey)}),Bt(this,"generateKeyPair",()=>{this.isInitialized();const i=g$();return this.setPrivateKey(i.publicKey,i.privateKey)}),Bt(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=tb(s),a=this.randomSessionIdentifier;return await TA(a,i,GP,o)}),Bt(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=w$(a,s);return this.setSymKey(c,o)}),Bt(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||xd(i);return await this.keychain.set(o,i),o}),Bt(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Bt(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Bt(this,"encode",async(i,s,o)=>{this.isInitialized();const a=d3(o),c=ri(s);if(f3(a))return y$(c,o?.encoding);if(h3(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return m$({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Bt(this,"decode",async(i,s,o)=>{this.isInitialized();const a=C$(s,o);if(f3(a)){const c=v$(s,o?.encoding);return $s(c)}if(h3(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=b$({symKey:c,encoded:s,encoding:o?.encoding});return $s(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Bt(this,"getPayloadType",(i,s=fr)=>{const o=Jc({encoded:i,encoding:s});return Ms(o.type)}),Bt(this,"getPayloadSenderPublicKey",(i,s=fr)=>{const o=Jc({encoded:i,encoding:s});return o.senderPublicKey?lr(o.senderPublicKey,er):void 0}),this.core=e,this.logger=tr(r,this.name),this.keychain=n||new ZB(this.core,this.logger)}get context(){return wr(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(av)}catch{e=P0(),await this.keychain.set(av,e)}return VB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var QB=Object.defineProperty,eR=Object.defineProperties,tR=Object.getOwnPropertyDescriptors,Nv=Object.getOwnPropertySymbols,rR=Object.prototype.hasOwnProperty,nR=Object.prototype.propertyIsEnumerable,e1=(t,e,r)=>e in t?QB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iR=(t,e)=>{for(var r in e||(e={}))rR.call(e,r)&&e1(t,r,e[r]);if(Nv)for(var r of Nv(e))nR.call(e,r)&&e1(t,r,e[r]);return t},sR=(t,e)=>eR(t,tR(e)),kr=(t,e,r)=>e1(t,typeof e!="symbol"?e+"":e,r);class oR extends jk{constructor(e,r){super(e,r),this.logger=e,this.core=r,kr(this,"messages",new Map),kr(this,"messagesWithoutClientAck",new Map),kr(this,"name",JP),kr(this,"version",XP),kr(this,"initialized",!1),kr(this,"storagePrefix",Rn),kr(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}}}),kr(this,"set",async(n,i,s)=>{this.isInitialized();const o=Vr(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===Md.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,sR(iR({},c),{[o]:i}))}return await this.persist(),o}),kr(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),kr(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}),kr(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Vr(i);return typeof s[o]<"u"}),kr(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Vr(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),kr(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=tr(e,this.name),this.core=r}get context(){return wr(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,e0(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,e0(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?t0(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?t0(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aR=Object.defineProperty,cR=Object.defineProperties,lR=Object.getOwnPropertyDescriptors,$v=Object.getOwnPropertySymbols,uR=Object.prototype.hasOwnProperty,dR=Object.prototype.propertyIsEnumerable,t1=(t,e,r)=>e in t?aR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xo=(t,e)=>{for(var r in e||(e={}))uR.call(e,r)&&t1(t,r,e[r]);if($v)for(var r of $v(e))dR.call(e,r)&&t1(t,r,e[r]);return t},Ov=(t,e)=>cR(t,lR(e)),Xr=(t,e,r)=>t1(t,typeof e!="symbol"?e+"":e,r);class hR extends zk{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Xr(this,"events",new Tt.exports.EventEmitter),Xr(this,"name",eD),Xr(this,"queue",new Map),Xr(this,"publishTimeout",ee.toMiliseconds(ee.ONE_MINUTE)),Xr(this,"initialPublishTimeout",ee.toMiliseconds(ee.ONE_SECOND*15)),Xr(this,"needsTransportRestart",!1),Xr(this,"publish",async(n,i,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const d=s?.ttl||QP,h=s?.prompt||!1,f=s?.tag||0,p=s?.id||Xi().toString(),g=Ko(_d().protocol),b={id:p,method:s?.publishMethod||g.publish,params:Xo({topic:n,message:i,ttl:d,prompt:h,tag:f,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},C=`Failed to publish payload, please try again. id:${p} tag:${f}`;try{gt((o=b.params)==null?void 0:o.prompt)&&((a=b.params)==null||delete a.prompt),gt((c=b.params)==null?void 0:c.tag)&&((l=b.params)==null||delete l.tag);const x=new Promise(async y=>{const v=({id:O})=>{var B;((B=b.id)==null?void 0:B.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(ct.publish,v),y())};this.relayer.events.on(ct.publish,v);const _=In(new Promise((O,B)=>{this.rpcPublish(b,s).then(O).catch(R=>{this.logger.warn(R,R?.message),B(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${f}`);try{await _,this.events.removeListener(ct.publish,v)}catch(O){this.queue.set(p,{request:b,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:n,message:i,opts:s}}),await In(x,this.publishTimeout,C)}catch(x){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(x),(u=s?.internal)!=null&&u.throwOnFailedPublish)throw x}finally{this.queue.delete(p)}}),Xr(this,"publishCustom",async n=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:u={}}=n,{attestation:d,tvf:h,publishMethod:f,prompt:p,tag:g,ttl:b=ee.FIVE_MINUTES}=u,C=u.id||Xi().toString(),x=Ko(_d().protocol),y=f||x.publish,v={id:C,method:y,params:Xo(Ov(Xo({},l),{ttl:b,prompt:p,tag:g,attestation:d}),h)},_=`Failed to publish custom payload, please try again. id:${C} tag:${g}`;try{gt((i=v.params)==null?void 0:i.prompt)&&((s=v.params)==null||delete s.prompt),gt((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const O=new Promise(async B=>{const R=({id:$})=>{var S;((S=v.id)==null?void 0:S.toString())===$.toString()&&(this.removeRequestFromQueue($),this.relayer.events.removeListener(ct.publish,R),B())};this.relayer.events.on(ct.publish,R);const E=In(new Promise(($,S)=>{this.rpcPublish(v,u).then($).catch(D=>{this.logger.warn(D,D?.message),S(D)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${C} tag:${g}`);try{await E,this.events.removeListener(ct.publish,R)}catch($){this.queue.set(C,{request:v,opts:u,attempt:1}),this.logger.warn($,$?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:C,payload:l,opts:u}}),await In(O,this.publishTimeout,_)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(C)}}),Xr(this,"on",(n,i)=>{this.events.on(n,i)}),Xr(this,"once",(n,i)=>{this.events.once(n,i)}),Xr(this,"off",(n,i)=>{this.events.off(n,i)}),Xr(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=tr(r,this.name),this.registerEventListeners()}get context(){return wr(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(ct.publish,Xo(Xo({},e),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var n;const i=e.attempt+1;this.queue.set(r,Ov(Xo({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(js.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ct.connection_stalled);return}this.checkQueue()}),this.relayer.on(ct.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var fR=Object.defineProperty,pR=(t,e,r)=>e in t?fR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qo=(t,e,r)=>pR(t,typeof e!="symbol"?e+"":e,r);class gR{constructor(){Qo(this,"map",new Map),Qo(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Qo(this,"get",e=>this.map.get(e)||[]),Qo(this,"exists",(e,r)=>this.get(e).includes(r)),Qo(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)}),Qo(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var wR=Object.defineProperty,mR=Object.defineProperties,bR=Object.getOwnPropertyDescriptors,kv=Object.getOwnPropertySymbols,yR=Object.prototype.hasOwnProperty,vR=Object.prototype.propertyIsEnumerable,r1=(t,e,r)=>e in t?wR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hl=(t,e)=>{for(var r in e||(e={}))yR.call(e,r)&&r1(t,r,e[r]);if(kv)for(var r of kv(e))vR.call(e,r)&&r1(t,r,e[r]);return t},n1=(t,e)=>mR(t,bR(e)),Xe=(t,e,r)=>r1(t,typeof e!="symbol"?e+"":e,r);class CR extends qk{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Xe(this,"subscriptions",new Map),Xe(this,"topicMap",new gR),Xe(this,"events",new Tt.exports.EventEmitter),Xe(this,"name",aD),Xe(this,"version",cD),Xe(this,"pending",new Map),Xe(this,"cached",[]),Xe(this,"initialized",!1),Xe(this,"storagePrefix",Rn),Xe(this,"subscribeTimeout",ee.toMiliseconds(ee.ONE_MINUTE)),Xe(this,"initialSubscribeTimeout",ee.toMiliseconds(ee.ONE_SECOND*15)),Xe(this,"clientId"),Xe(this,"batchSubscribeTopicsLimit",500),Xe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Xe(this,"subscribe",async(n,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=_d(i),a={topic:n,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Xe(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),Xe(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),Xe(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),Xe(this,"on",(n,i)=>{this.events.on(n,i)}),Xe(this,"once",(n,i)=>{this.events.once(n,i)}),Xe(this,"off",(n,i)=>{this.events.off(n,i)}),Xe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),Xe(this,"start",async()=>{await this.onConnect()}),Xe(this,"stop",async()=>{await this.onDisconnect()}),Xe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Xe(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)}),Xe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(js.pulse,async()=>{await this.checkPending()}),this.events.on(Or.created,async n=>{const i=Or.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(Or.deleted,async n=>{const i=Or.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=tr(r,this.name),this.clientId=""}get context(){return wr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=_d(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=nt("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,s;const o=await this.getSubscriptionId(e);if((i=n?.internal)!=null&&i.skipSubscribe)return o;(!n||n?.transportType===it.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:Ko(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===it.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},ee.toMiliseconds(ee.ONE_SECOND)),o;const l=new Promise(async d=>{const h=f=>{f.topic===e&&(this.events.removeListener(Or.created,h),d(f.id))};this.events.on(Or.created,h);try{const f=await In(new Promise((p,g)=>{this.relayer.request(a).catch(b=>{this.logger.warn(b,b?.message),g(b)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Or.created,h),d(f)}catch{}}),u=await In(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ct.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ko(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 In(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(ct.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Ko(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 In(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(ct.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Ko(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,n1(hl({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,hl({},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,hl({},r)),this.topicMap.set(r.topic,e),this.events.emit(Or.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}=te("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(Or.deleted,n1(hl({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Or.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(Or.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){const{message:r}=te("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=>n1(hl({},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 UI(ee.toMiliseconds(ee.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}=te("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 Vr(e+await this.getClientId())}}var ER=Object.defineProperty,Pv=Object.getOwnPropertySymbols,xR=Object.prototype.hasOwnProperty,_R=Object.prototype.propertyIsEnumerable,i1=(t,e,r)=>e in t?ER(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dv=(t,e)=>{for(var r in e||(e={}))xR.call(e,r)&&i1(t,r,e[r]);if(Pv)for(var r of Pv(e))_R.call(e,r)&&i1(t,r,e[r]);return t},Re=(t,e,r)=>i1(t,typeof e!="symbol"?e+"":e,r);class AR extends Wk{constructor(e){super(e),Re(this,"protocol","wc"),Re(this,"version",2),Re(this,"core"),Re(this,"logger"),Re(this,"events",new Tt.exports.EventEmitter),Re(this,"provider"),Re(this,"messages"),Re(this,"subscriber"),Re(this,"publisher"),Re(this,"name",rD),Re(this,"transportExplicitlyClosed",!1),Re(this,"initialized",!1),Re(this,"connectionAttemptInProgress",!1),Re(this,"relayUrl"),Re(this,"projectId"),Re(this,"packageName"),Re(this,"bundleId"),Re(this,"hasExperiencedNetworkDisruption",!1),Re(this,"pingTimeout"),Re(this,"heartBeatTimeout",ee.toMiliseconds(ee.THIRTY_SECONDS+ee.FIVE_SECONDS)),Re(this,"reconnectTimeout"),Re(this,"connectPromise"),Re(this,"reconnectInProgress",!1),Re(this,"requestsInFlight",[]),Re(this,"connectTimeout",ee.toMiliseconds(ee.ONE_SECOND*15)),Re(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Xi().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}}),Re(this,"resetPingTimeout",()=>{od()&&(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))}),Re(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(ct.connect)}),Re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),Re(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(ct.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Re(this,"registerProviderListeners",()=>{this.provider.on(Yr.payload,this.onPayloadHandler),this.provider.on(Yr.connect,this.onConnectHandler),this.provider.on(Yr.disconnect,this.onDisconnectHandler),this.provider.on(Yr.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?tr(e.logger,this.name):On(nl({level:e.logger||tD})),this.messages=new oR(this.logger,e.core),this.subscriber=new CR(this,this.logger),this.publisher=new hR(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lv,CI()?this.packageName=jb():EI()&&(this.bundleId=jb()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return wr(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:it.relay},Md.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}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(Or.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Or.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,Dv({internal:{throwOnFailedPublish:o}},r)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await In(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,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 S3())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=ft(ee.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(ct.message,e),await this.recordMessageEvent(e,Md.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 connect"))};this.provider.once(Yr.disconnect,s),await In(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(Yr.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Yr.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Yr.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,ee.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(od())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 Zr(new jP(II({sdkVersion:Y0,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}),Z0(e)){if(!e.method.endsWith(nD))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:it.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Dv({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ud(e)&&this.events.emit(ct.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Md.inbound),this.events.emit(ct.message,e))}async acknowledgePayload(e){const r=ol(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Yr.payload,this.onPayloadHandler),this.provider.off(Yr.connect,this.onConnectHandler),this.provider.off(Yr.disconnect,this.onDisconnectHandler),this.provider.off(Yr.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await S3();pO(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))}),this.core.heartbeat.on(js.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&mO())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ct.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},ee.toMiliseconds(iD)))))}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function SR(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Bv(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Rv(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const IR="[object RegExp]",TR="[object String]",NR="[object Number]",$R="[object Boolean]",Uv="[object Arguments]",OR="[object Symbol]",kR="[object Date]",PR="[object Map]",DR="[object Set]",BR="[object Array]",RR="[object Function]",UR="[object ArrayBuffer]",s1="[object Object]",LR="[object Error]",MR="[object DataView]",FR="[object Uint8Array]",jR="[object Uint8ClampedArray]",zR="[object Uint16Array]",WR="[object Uint32Array]",HR="[object BigUint64Array]",qR="[object Int8Array]",VR="[object Int16Array]",KR="[object Int32Array]",GR="[object BigInt64Array]",ZR="[object Float32Array]",YR="[object Float64Array]";function JR(){}function Lv(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 XR(t,e,r){return fl(t,e,void 0,void 0,void 0,void 0,r)}function fl(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 pl(t,e,s,o)}return pl(t,e,s,o)}function pl(t,e,r,n){if(Object.is(t,e))return!0;let i=Rv(t),s=Rv(e);if(i===Uv&&(i=s1),s===Uv&&(s=s1),i!==s)return!1;switch(i){case TR:return t.toString()===e.toString();case NR:{const c=t.valueOf(),l=e.valueOf();return SR(c,l)}case $R:case kR:case OR:return Object.is(t.valueOf(),e.valueOf());case IR:return t.source===e.source&&t.flags===e.flags;case RR: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 PR:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!fl(l,e.get(c),c,t,e,r,n))return!1;return!0}case DR:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(f=>fl(d,f,void 0,t,e,r,n));if(h===-1)return!1;l.splice(h,1)}return!0}case BR:case FR:case jR:case zR:case WR:case HR:case qR:case VR:case KR:case GR:case ZR:case YR:{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(!fl(t[c],e[c],c,t,e,r,n))return!1;return!0}case UR:return t.byteLength!==e.byteLength?!1:pl(new Uint8Array(t),new Uint8Array(e),r,n);case MR:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:pl(new Uint8Array(t),new Uint8Array(e),r,n);case LR:return t.name===e.name&&t.message===e.message;case s1:{if(!(pl(t.constructor,e.constructor,r,n)||Lv(t)&&Lv(e)))return!1;const c=[...Object.keys(t),...Bv(t)],l=[...Object.keys(e),...Bv(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=t[d];if(!Object.hasOwn(e,d))return!1;const f=e[d];if(!fl(h,f,d,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function QR(t,e){return XR(t,e,JR)}var eU=Object.defineProperty,Mv=Object.getOwnPropertySymbols,tU=Object.prototype.hasOwnProperty,rU=Object.prototype.propertyIsEnumerable,o1=(t,e,r)=>e in t?eU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fv=(t,e)=>{for(var r in e||(e={}))tU.call(e,r)&&o1(t,r,e[r]);if(Mv)for(var r of Mv(e))rU.call(e,r)&&o1(t,r,e[r]);return t},mr=(t,e,r)=>o1(t,typeof e!="symbol"?e+"":e,r);class qs extends Hk{constructor(e,r,n,i=Rn,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,mr(this,"map",new Map),mr(this,"version",sD),mr(this,"cached",[]),mr(this,"initialized",!1),mr(this,"getKey"),mr(this,"storagePrefix",Rn),mr(this,"recentlyDeleted",[]),mr(this,"recentlyDeletedLimit",200),mr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!gt(o)?this.map.set(this.getKey(o),o):q$(o)?this.map.set(o.id,o):V$(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),mr(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())}),mr(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),mr(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>QR(a[c],o[c]))):this.values)),mr(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=Fv(Fv({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),mr(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=tr(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return wr(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}=te("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=te("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}=te("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}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nU=Object.defineProperty,iU=(t,e,r)=>e in t?nU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$e=(t,e,r)=>iU(t,typeof e!="symbol"?e+"":e,r);class sU{constructor(e,r){this.core=e,this.logger=r,$e(this,"name",lD),$e(this,"version",uD),$e(this,"events",new Tt.exports),$e(this,"pairings"),$e(this,"initialized",!1),$e(this,"storagePrefix",Rn),$e(this,"ignoredPayloadTypes",[li]),$e(this,"registeredMethods",[]),$e(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),$e(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),$e(this,"create",async n=>{this.isInitialized();const i=P0(),s=await this.core.crypto.setSymKey(i),o=ft(ee.FIVE_MINUTES),a={protocol:cv},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},l=g3({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(Ws.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:l}}),$e(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Un.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=p3(n.uri);i.props.properties.topic=s,i.addTrace(Un.pairing_uri_validation_success),i.addTrace(Un.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(Un.existing_pairing),u.active)throw i.setError(hi.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Un.pairing_not_expired)}const d=c||ft(ee.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(Un.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Ws.create,h),i.addTrace(Un.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Un.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(hi.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(hi.subscribe_pairing_topic_failure),f}return i.addTrace(Un.subscribe_pairing_topic_success),h}),$e(this,"activate",async({topic:n})=>{this.isInitialized();const i=ft(ee.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),$e(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}=Ds();this.events.once(ze("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),$e(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),$e(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),$e(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),$e(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",nt("USER_DISCONNECTED")),await this.deletePairing(i))}),$e(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return g3({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),$e(this,"sendRequest",async(n,i,s)=>{const o=Dn(i,s),a=await this.core.crypto.encode(n,o),c=al[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),$e(this,"sendResult",async(n,i,s)=>{const o=ol(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=al[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),$e(this,"sendError",async(n,i,s)=>{const o=Rd(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,l=al[c]?al[c].res:al.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),$e(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,nt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),$e(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>Mi(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),$e(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)}}),$e(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)}}),$e(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Ws.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),$e(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{Bn(i)?this.events.emit(ze("pairing_ping",s),{}):Gr(i)&&this.events.emit(ze("pairing_ping",s),{error:i.error})},500)}),$e(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Ws.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),$e(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=nt("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)}}),$e(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(nt("WC_METHOD_UNSUPPORTED",n))}),$e(this,"isValidPair",(n,i)=>{var s;if(!pr(n)){const{message:a}=te("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(hi.malformed_pairing_uri),new Error(a)}if(!H$(n.uri)){const{message:a}=te("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(hi.malformed_pairing_uri),new Error(a)}const o=p3(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=te("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(hi.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=te("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(hi.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&ee.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(hi.pairing_expired);const{message:a}=te("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),$e(this,"isValidPing",async n=>{if(!pr(n)){const{message:s}=te("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),$e(this,"isValidDisconnect",async n=>{if(!pr(n)){const{message:s}=te("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),$e(this,"isValidPairingTopic",async n=>{if(!ut(n,!1)){const{message:i}=te("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=te("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Mi(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=te("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=tr(r,this.name),this.pairings=new qs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return wr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ct.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==it.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);Z0(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):Ud(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(Jr.expired,async e=>{const{topic:r}=qb(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ws.expire,{topic:r}))})}}var oU=Object.defineProperty,aU=(t,e,r)=>e in t?oU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rt=(t,e,r)=>aU(t,typeof e!="symbol"?e+"":e,r);class cU extends Fk{constructor(e,r){super(e,r),this.core=e,this.logger=r,Rt(this,"records",new Map),Rt(this,"events",new Tt.exports.EventEmitter),Rt(this,"name",dD),Rt(this,"version",hD),Rt(this,"cached",[]),Rt(this,"initialized",!1),Rt(this,"storagePrefix",Rn),Rt(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)}),Rt(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:ft(ee.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(mn.created,o)}),Rt(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=Gr(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(mn.updated,i))}),Rt(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))),Rt(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(mn.deleted,s)}}),this.persist()}),Rt(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Rt(this,"on",(n,i)=>{this.events.on(n,i)}),Rt(this,"once",(n,i)=>{this.events.once(n,i)}),Rt(this,"off",(n,i)=>{this.events.off(n,i)}),Rt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=tr(r,this.name)}get context(){return wr(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:Dn(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}=te("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(mn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=te("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(mn.created,e=>{const r=mn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(mn.updated,e=>{const r=mn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(mn.deleted,e=>{const r=mn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(js.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{ee.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(mn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var lU=Object.defineProperty,uU=(t,e,r)=>e in t?lU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kt=(t,e,r)=>uU(t,typeof e!="symbol"?e+"":e,r);class dU extends Vk{constructor(e,r){super(e,r),this.core=e,this.logger=r,Kt(this,"expirations",new Map),Kt(this,"events",new Tt.exports.EventEmitter),Kt(this,"name",fD),Kt(this,"version",pD),Kt(this,"cached",[]),Kt(this,"initialized",!1),Kt(this,"storagePrefix",Rn),Kt(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)}),Kt(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Kt(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(Jr.created,{target:s,expiration:o})}),Kt(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),Kt(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(Jr.deleted,{target:i,expiration:s})}}),Kt(this,"on",(n,i)=>{this.events.on(n,i)}),Kt(this,"once",(n,i)=>{this.events.once(n,i)}),Kt(this,"off",(n,i)=>{this.events.off(n,i)}),Kt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=tr(r,this.name)}get context(){return wr(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 TI(e);if(typeof e=="number")return NI(e);const{message:r}=te("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(Jr.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=te("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}=te("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;ee.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Jr.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(js.pulse,()=>this.checkExpirations()),this.events.on(Jr.created,e=>{const r=Jr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Jr.expired,e=>{const r=Jr.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Jr.deleted,e=>{const r=Jr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}}var hU=Object.defineProperty,fU=(t,e,r)=>e in t?hU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dt=(t,e,r)=>fU(t,typeof e!="symbol"?e+"":e,r);class pU extends Kk{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,dt(this,"name",gD),dt(this,"abortController"),dt(this,"isDevEnv"),dt(this,"verifyUrlV3",mD),dt(this,"storagePrefix",Rn),dt(this,"version",ov),dt(this,"publicKey"),dt(this,"fetchPromise"),dt(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&ee.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),dt(this,"register",async i=>{if(!Fo()||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=vs(),u=this.startAbortTimer(ee.ONE_SECOND*5),d=await new Promise((h,f)=>{const p=()=>{window.removeEventListener("message",b),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const b=C=>{if(C.data&&typeof C.data=="string")try{const x=JSON.parse(C.data);if(x.type==="verify_attestation"){if(Vp(x.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",b),h(x.attestation===null?"":x.attestation)}}catch(x){this.logger.warn(x)}};l.body.appendChild(g),window.addEventListener("message",b,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),dt(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(Vp(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)}),dt(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(ee.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}),dt(this,"getVerifyUrl",i=>{let s=i||cl;return bD.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${cl}`),s=cl),s}),dt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(ee.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)}}),dt(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),dt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),dt(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")}}),dt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),dt(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}),dt(this,"validateAttestation",(i,s)=>{const o=x$(i,s.publicKey),a={hasExpired:ee.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=tr(r,this.name),this.abortController=new AbortController,this.isDevEnv=r0(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return wr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ee.toMiliseconds(e))}}var gU=Object.defineProperty,wU=(t,e,r)=>e in t?gU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jv=(t,e,r)=>wU(t,typeof e!="symbol"?e+"":e,r);class mU extends Gk{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,jv(this,"context",yD),jv(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${vD}/${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=tr(r,this.context)}}var bU=Object.defineProperty,zv=Object.getOwnPropertySymbols,yU=Object.prototype.hasOwnProperty,vU=Object.prototype.propertyIsEnumerable,a1=(t,e,r)=>e in t?bU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gl=(t,e)=>{for(var r in e||(e={}))yU.call(e,r)&&a1(t,r,e[r]);if(zv)for(var r of zv(e))vU.call(e,r)&&a1(t,r,e[r]);return t},_t=(t,e,r)=>a1(t,typeof e!="symbol"?e+"":e,r);class CU extends Zk{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,_t(this,"context",ED),_t(this,"storagePrefix",Rn),_t(this,"storageVersion",CD),_t(this,"events",new Map),_t(this,"shouldPersist",!1),_t(this,"init",async()=>{if(!r0())try{const i={eventId:Kb(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Wb(this.core.relayer.protocol,this.core.relayer.version,Y0)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),_t(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=Kb(),u=this.core.projectId||"",d=Date.now(),h=gl({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),_t(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 gl(gl({},a),this.setMethods(a.eventId))}),_t(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),_t(this,"setEventListeners",()=>{this.core.heartbeat.on(js.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{ee.fromMiliseconds(Date.now())-ee.fromMiliseconds(i.timestamp)>xD&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),_t(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),_t(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)}),_t(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)}),_t(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),_t(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,gl(gl({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),_t(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)}}),_t(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${_D}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Y0}${s}`,{method:"POST",body:JSON.stringify(i)})}),_t(this,"getAppDomain",()=>zb().url),this.logger=tr(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 EU=Object.defineProperty,Wv=Object.getOwnPropertySymbols,xU=Object.prototype.hasOwnProperty,_U=Object.prototype.propertyIsEnumerable,c1=(t,e,r)=>e in t?EU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hv=(t,e)=>{for(var r in e||(e={}))xU.call(e,r)&&c1(t,r,e[r]);if(Wv)for(var r of Wv(e))_U.call(e,r)&&c1(t,r,e[r]);return t},et=(t,e,r)=>c1(t,typeof e!="symbol"?e+"":e,r);class l1 extends Rk{constructor(e){var r;super(e),et(this,"protocol",sv),et(this,"version",ov),et(this,"name",Ld),et(this,"relayUrl"),et(this,"projectId"),et(this,"customStoragePrefix"),et(this,"events",new Tt.exports.EventEmitter),et(this,"logger"),et(this,"heartbeat"),et(this,"relayer"),et(this,"crypto"),et(this,"storage"),et(this,"history"),et(this,"expirer"),et(this,"pairing"),et(this,"verify"),et(this,"echoClient"),et(this,"linkModeSupportedApps"),et(this,"eventClient"),et(this,"initialized",!1),et(this,"logChunkController"),et(this,"on",(a,c)=>this.events.on(a,c)),et(this,"once",(a,c)=>this.events.once(a,c)),et(this,"off",(a,c)=>this.events.off(a,c)),et(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),et(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:it.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||lv,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=nl({level:typeof e?.logger=="string"&&e.logger?e.logger:qP.logger,name:Ld}),{logger:s,chunkLoggerController:o}=F3({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=tr(s,this.name),this.heartbeat=new L0,this.crypto=new XB(this,this.logger,e?.keychain),this.history=new cU(this,this.logger),this.expirer=new dU(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ok(Hv(Hv({},VP),e?.storageOptions)),this.relayer=new AR({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new sU(this,this.logger),this.verify=new pU(this,this.logger,this.storage),this.echoClient=new mU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new CU(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new l1(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(oD,n),r}get context(){return wr(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(uv,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(uv)||[],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 AU=l1,qv="wc",Vv=2,Kv="client",u1=`${qv}@${Vv}:${Kv}:`,d1={name:Kv,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Gv="WALLETCONNECT_DEEPLINK_CHOICE",SU="proposal",Zv="Proposal expired",IU="session",ea=ee.SEVEN_DAYS,TU="engine",Ut={wc_sessionPropose:{req:{ttl:ee.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ee.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ee.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ee.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ee.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ee.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ee.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ee.FIVE_MINUTES,prompt:!1,tag:1119}}},h1={min:ee.FIVE_MINUTES,max:ee.SEVEN_DAYS},Mn={idle:"IDLE",active:"ACTIVE"},NU={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},$U="request",OU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],kU="wc",PU="auth",DU="authKeys",BU="pairingTopics",RU="requests",jd=`${kU}@${1.5}:${PU}:`,zd=`${jd}:PUB_KEY`;var UU=Object.defineProperty,LU=Object.defineProperties,MU=Object.getOwnPropertyDescriptors,Yv=Object.getOwnPropertySymbols,FU=Object.prototype.hasOwnProperty,jU=Object.prototype.propertyIsEnumerable,f1=(t,e,r)=>e in t?UU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qe=(t,e)=>{for(var r in e||(e={}))FU.call(e,r)&&f1(t,r,e[r]);if(Yv)for(var r of Yv(e))jU.call(e,r)&&f1(t,r,e[r]);return t},Gt=(t,e)=>LU(t,MU(e)),q=(t,e,r)=>f1(t,typeof e!="symbol"?e+"":e,r);class zU extends Qk{constructor(e){super(e),q(this,"name",TU),q(this,"events",new Tt.exports),q(this,"initialized",!1),q(this,"requestQueue",{state:Mn.idle,queue:[]}),q(this,"sessionRequestQueue",{state:Mn.idle,queue:[]}),q(this,"emittedSessionRequests",new LI({limit:500})),q(this,"requestQueueDelay",ee.ONE_SECOND),q(this,"expectedPairingMethodMap",new Map),q(this,"recentlyDeletedMap",new Map),q(this,"recentlyDeletedLimit",200),q(this,"relayMessageCache",[]),q(this,"pendingSessions",new Map),q(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(Ut)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ee.toMiliseconds(this.requestQueueDelay)))}),q(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Gt(qe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=M$(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let u=i,d,h=!1;try{if(u){const O=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=O.active}}catch(O){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),O}if(!u||!h){const{topic:O,uri:B}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=O,d=B}if(!u){const{message:O}=te("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(O)}const f=await this.client.core.crypto.generateKeyPair(),p=Ut.wc_sessionPropose.req.ttl||ee.FIVE_MINUTES,g=ft(p),b=Gt(qe(qe({requiredNamespaces:s,optionalNamespaces:o,relays:l??[{protocol:cv}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Pn()}),C=ze("session_connect",b.id),{reject:x,resolve:y,done:v}=Ds(p,Zv),_=({id:O})=>{O===b.id&&(this.client.events.off("proposal_expire",_),this.pendingSessions.delete(b.id),this.events.emit(C,{error:{message:Zv,code:0}}))};return this.client.events.on("proposal_expire",_),this.events.once(C,({error:O,session:B})=>{this.client.events.off("proposal_expire",_),O?x(O):B&&y(B)}),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}),await this.setProposal(b.id,b),{uri:d,approval:v}}),q(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}}),q(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:[Qi.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(ll.no_internet_connection),E}try{await this.isValidProposalId(r?.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(ll.proposal_not_found),E}try{await this.isValidApprove(r)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ll.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:b,optionalNamespaces:C}=f;let x=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:p});x||(x=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Qi.session_approve_started,properties:{topic:p,trace:[Qi.session_approve_started,Qi.session_namespaces_validation_success]}}));const y=await this.client.core.crypto.generateKeyPair(),v=g.publicKey,_=await this.client.core.crypto.generateSharedKey(y,v),O=qe(qe(qe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:y,metadata:this.client.metadata},expiry:ft(ea)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),B=it.relay;x.addTrace(Qi.subscribing_session_topic);try{await this.client.core.relayer.subscribe(_,{transportType:B,internal:{skipSubscribe:!0}})}catch(E){throw x.setError(ll.subscribe_session_topic_failure),E}x.addTrace(Qi.subscribe_session_topic_success);const R=Gt(qe({},O),{topic:_,requiredNamespaces:b,optionalNamespaces:C,pairingTopic:p,acknowledged:!1,self:O.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:y,transportType:it.relay});await this.client.session.set(_,R),x.addTrace(Qi.store_session);try{await this.sendApproveSession({sessionTopic:_,proposal:f,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:y},sessionSettleRequest:O,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),x.addTrace(Qi.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(_,nt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(_),E}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(_,ft(ea)),{topic:_,acknowledged:()=>Promise.resolve(this.client.session.get(_))}}),q(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:Ut.wc_sessionPropose.reject}),await this.deleteProposal(n)}),q(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=Ds(),c=Pn(),l=Xi().toString(),u=this.client.session.get(n).namespaces;return this.events.once(ze("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:u}),a(d)}),{acknowledged:s}}),q(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=Pn(),{done:s,resolve:o,reject:a}=Ds();return this.events.once(ze("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,ft(ea)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),q(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:n,request:i,topic:s,expiry:o=Ut.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===it.relay&&await this.confirmOnlineStateOrThrow();const c=Pn(),l=Xi().toString(),{done:u,resolve:d,reject:h}=Ds(o,"Request expired. Please try again.");this.events.once(ze("session_request",c),({error:b,result:C})=>{b?h(b):d(C)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:Gt(qe({},i),{expiryTimestamp:ft(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await u();const g={request:Gt(qe({},i),{expiryTimestamp:ft(o)}),chainId:n};return await Promise.all([new Promise(async b=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(C=>h(C)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var C;if(!((C=a.sessionConfig)!=null&&C.disableDeepLink)){const x=await PI(this.client.core.storage,Gv);await $I({id:c,topic:s,wcDeepLink:x})}b()}),u()]).then(b=>b[2])}),q(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===it.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Bn(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):Gr(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),q(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=Pn(),s=Xi().toString(),{done:o,resolve:a,reject:c}=Ds();this.events.once(ze("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}))}),q(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Xi().toString(),a=Pn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),q(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:nt("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}=te("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),q(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>z$(n,r)))),q(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),q(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?it.link_mode:it.relay;o===it.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:p,methods:g=[],expiry:b}=r,C=[...r.resources||[]],{topic:x,uri:y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:x,uri:y}});const v=await this.client.core.crypto.generateKeyPair(),_=xd(v);if(await Promise.all([this.client.auth.authKeys.set(zd,{responseTopic:_,publicKey:v}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:x})]),await this.client.core.relayer.subscribe(_,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${x}`),g.length>0){const{namespace:N}=ks(a[0]);let k=GT(N,"request",g);dd(C)&&(k=YT(k,C.pop())),C.push(k)}const O=b&&b>Ut.wc_sessionAuthenticate.req.ttl?b:Ut.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:p,resources:C},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:ft(O)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:x,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:ft(Ut.wc_sessionPropose.req.ttl),id:Pn()},{done:$,resolve:S,reject:D}=Ds(O,"Request expired"),U=Pn(),M=ze("session_connect",E.id),w=ze("session_request",U),m=async({error:N,session:k})=>{this.events.off(w,A),N?D(N):k&&S({session:k})},A=async N=>{var k,j,z;if(await this.deletePendingAuthRequest(U,{message:"fulfilled",code:0}),N.error){const ge=nt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return N.error.code===ge.code?void 0:(this.events.off(M,m),D(N.error.message))}await this.deleteProposal(E.id),this.events.off(M,m);const{cacaos:G,responder:H}=N.result,J=[],fe=[];for(const ge of G){await my({cacao:ge,projectId:this.client.core.projectId})||(this.client.logger.error(ge,"Signature verification failed"),D(nt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ee}=ge,He=dd(Ee.resources),yt=[p0(Ee.iss)],Ft=ud(Ee.iss);if(He){const ln=vy(He),Gn=Cy(He);J.push(...ln),yt.push(...Gn)}for(const ln of yt)fe.push(`${ln}:${Ft}`)}const ve=await this.client.core.crypto.generateSharedKey(v,H.publicKey);let Se;J.length>0&&(Se={topic:ve,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:H,controller:H.publicKey,expiry:ft(ea),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:x,namespaces:y3([...new Set(J)],[...new Set(fe)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,Se),x&&await this.client.core.pairing.updateMetadata({topic:x,metadata:H.metadata}),Se=this.client.session.get(ve)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(j=H.metadata.redirect)!=null&&j.linkMode&&(z=H.metadata.redirect)!=null&&z.universal&&n&&(this.client.core.addLinkModeSupportedApp(H.metadata.redirect.universal),this.client.session.update(ve,{transportType:it.link_mode})),S({auths:G,session:Se})};this.events.once(M,m),this.events.once(w,A);let T;try{if(s){const N=Dn("wc_sessionAuthenticate",B,U);this.client.core.history.set(x,N);const k=await this.client.core.crypto.encode("",N,{type:Zc,encoding:Ji});T=Ad(n,x,k)}else await Promise.all([this.sendRequest({topic:x,method:"wc_sessionAuthenticate",params:B,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:U}),this.sendRequest({topic:x,method:"wc_sessionPropose",params:E,expiry:Ut.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(N){throw this.events.off(M,m),this.events.off(w,A),N}return await this.setProposal(E.id,E),await this.setAuthRequest(U,{request:Gt(qe({},B),{verifyContext:{}}),pairingTopic:x,transportType:o}),{uri:T??y,response:$}}),q(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Hs.authenticated_session_approve_started]}});try{this.isInitialized()}catch(b){throw s.setError(ul.no_internet_connection),b}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(ul.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||it.relay;a===it.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=xd(c),d={type:li,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const b of i){if(!await my({cacao:b,projectId:this.client.core.projectId})){s.setError(ul.invalid_cacao);const _=nt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:_,encodeOpts:d}),new Error(_.message)}s.addTrace(Hs.cacaos_verified);const{p:C}=b,x=dd(C.resources),y=[p0(C.iss)],v=ud(C.iss);if(x){const _=vy(x),O=Cy(x);h.push(..._),y.push(...O)}for(const _ of y)f.push(`${_}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Hs.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ft(ea),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:y3([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Hs.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(b){throw s.setError(ul.subscribe_authenticated_session_topic_failure),b}s.addTrace(Hs.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Hs.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Hs.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(b){throw s.setError(ul.authenticated_session_approve_publish_failure),b}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}}),q(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===it.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=xd(o),l={type:li,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:l,rpcOpts:Ut.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),q(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return by(n,i)}),q(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)}),q(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)}}),q(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,nt("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(Gv).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,nt("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Mn.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),q(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(ll.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,nt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),q(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=Mn.idle,this.client.events.emit("session_request_expire",{id:r}))}),q(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)])}),q(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}))}),q(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,ft(Ut.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),q(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=it.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})}),q(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||ft(Ut.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})}),q(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=r,f=Dn(i,s,c);let p;const g=!!u;try{const x=g?Ji:fr;p=await this.client.core.crypto.encode(n,f,{encoding:x})}catch(x){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),x}let b;if(OU.includes(i)){const x=Vr(JSON.stringify(f)),y=Vr(p);b=await this.client.core.verify.register({id:y,decryptedId:x})}const C=qe(qe({},Ut[i].req),h);if(C.attestation=b,o&&(C.ttl=o),a&&(C.id=a),this.client.core.history.set(n,f),g){const x=Ad(u,n,p);await global.Linking.openURL(x,this.client.name)}else C.tvf=Gt(qe({},d),{correlationId:f.id}),l?(C.internal=Gt(qe({},C.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,C)):this.client.core.relayer.publish(n,p,C).catch(x=>this.client.logger.error(x));return f.id}),q(this,"sendProposeSession",async r=>{const{proposal:n,publishOpts:i}=r,s=Dn("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);const o=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:fr}),a=Vr(JSON.stringify(s)),c=Vr(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:Gt(qe({},i),{publishMethod:"wc_proposeSession",attestation:l})})}),q(this,"sendApproveSession",async r=>{const{sessionTopic:n,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=ol(s.id,i),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:fr}),u=Dn("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(n,u,{encoding:fr});this.client.core.history.set(n,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:Gt(qe({},a),{publishMethod:"wc_approveSession"})})}),q(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=ol(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?Ji:fr;u=await this.client.core.crypto.encode(i,l,Gt(qe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,f;try{h=await this.client.core.history.get(i,n);const p=h.request;try{f=this.getTVFParams(n,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),p}if(d){const p=Ad(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Ut[p].res;g.tvf=Gt(qe({},f),{correlationId:n}),o?(g.internal=Gt(qe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(b=>this.client.logger.error(b))}await this.client.core.history.resolve(l)}),q(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Rd(n,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?Ji:fr;u=await this.client.core.crypto.encode(i,l,Gt(qe({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,n)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),f}if(d){const f=Ad(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,p=a||Ut[f].res;this.client.core.relayer.publish(i,u,p)}await this.client.core.history.resolve(l)}),q(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;Mi(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=>{Mi(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),q(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),q(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),q(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Mn.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=Mn.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Mn.idle}),q(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}`)}}),q(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}`)}}),q(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=te("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),q(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)}),q(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(hi.proposal_listener_not_found)),this.isValidConnect(qe({},i.params));const u=a.expiryTimestamp||ft(Ut.wc_sessionPropose.req.ttl),d=qe({id:c,pairingTopic:n,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:Vr(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(Un.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:Ut.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),q(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(Bn(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:r,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:r})}else if(Gr(n)){await this.deleteProposal(s);const o=ze("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})}}),q(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=n.params,f=[...this.pendingSessions.values()].find(b=>b.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const p=this.client.proposal.get(f.proposalId),g=Gt(qe(qe(qe({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:it.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ze("session_connect",f.proposalId),{session:g}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:n.id,topic:r,result:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),q(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;Bn(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ze("session_approve",i),{})):Gr(n)&&(await this.client.session.delete(r,nt("USER_DISCONNECTED")),this.events.emit(ze("session_approve",i),{error:n.error}))}),q(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Xc.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:nt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(qe({topic:r},i));try{Xc.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Xc.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)}}),q(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),q(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=ze("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Bn(n)?this.events.emit(ze("session_update",i),{}):Gr(n)&&this.events.emit(ze("session_update",i),{error:n.error})}),q(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ft(ea)),await this.sendResult({id:i,topic:r,result:!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)}}),q(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=ze("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Bn(n)?this.events.emit(ze("session_extend",i),{}):Gr(n)&&this.events.emit(ze("session_extend",i),{error:n.error})}),q(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)}}),q(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=ze("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Bn(n)?this.events.emit(ze("session_ping",i),{}):Gr(n)&&this.events.emit(ze("session_ping",i),{error:n.error})},500)}),q(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(ct.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:nt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),q(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:d,params:h}=a;try{await this.isValidRequest(qe({topic:o},h));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Vr(JSON.stringify(Dn("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),u===it.link_mode&&(n=f.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),q(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=ze("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Bn(n)?this.events.emit(ze("session_request",i),{result:n.result}):Gr(n)&&this.events.emit(ze("session_request",i),{error:n.error})}),q(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Xc.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(qe({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Xc.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),q(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Bn(n)?this.events.emit(ze("session_request",i),{result:n.result}):Gr(n)&&this.events.emit(ze("session_request",i),{error:n.error})}),q(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:Vr(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===it.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:li,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Ut.wc_sessionAuthenticate.autoReject,appLink:h})}}),q(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),q(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Mn.idle,this.processSessionRequestQueue()},ee.toMiliseconds(this.requestQueueDelay))}),q(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=ze("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ze("session_request",s.request.id),{error:n})})}),q(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Mn.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),q(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Mn.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),q(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:Dn("wc_sessionPropose",Gt(qe({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),q(this,"isValidConnect",async r=>{if(!pr(r)){const{message:l}=te("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(gt(n)||await this.isValidPairingTopic(n),!eO(c,!0)){const{message:l}=te("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!gt(i)&&$n(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(!gt(s)&&$n(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),gt(o)||this.validateSessionProps(o,"sessionProperties"),!gt(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),q(this,"validateNamespaces",(r,n)=>{const i=Q$(r,"connect()",n);if(i)throw new Error(i.message)}),q(this,"isValidApprove",async r=>{if(!pr(r))throw new Error(te("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=B0(i,"approve()");if(l)throw new Error(l.message);const u=_3(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!ut(s,!0)){const{message:d}=te("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(gt(o)||this.validateSessionProps(o,"sessionProperties"),!gt(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),q(this,"isValidReject",async r=>{if(!pr(r)){const{message:s}=te("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!rO(i)){const{message:s}=te("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),q(this,"isValidSessionSettleRequest",r=>{if(!pr(r)){const{message:l}=te("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!E3(n)){const{message:l}=te("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=B0(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Mi(o)){const{message:l}=te("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),q(this,"isValidUpdate",async r=>{if(!pr(r)){const{message:c}=te("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=B0(i,"update()");if(o)throw new Error(o.message);const a=_3(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),q(this,"isValidExtend",async r=>{if(!pr(r)){const{message:i}=te("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),q(this,"isValidRequest",async r=>{if(!pr(r)){const{message:c}=te("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(!x3(a,s)){const{message:c}=te("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!nO(i)){const{message:c}=te("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!oO(a,s,i.method)){const{message:c}=te("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!uO(o,h1)){const{message:c}=te("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${h1.min} and ${h1.max}`);throw new Error(c)}}),q(this,"isValidRespond",async r=>{var n;if(!pr(r)){const{message:o}=te("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(!iO(s)){const{message:o}=te("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),q(this,"isValidPing",async r=>{if(!pr(r)){const{message:i}=te("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),q(this,"isValidEmit",async r=>{if(!pr(r)){const{message:a}=te("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(!x3(o,s)){const{message:a}=te("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!sO(i)){const{message:a}=te("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!aO(o,s,i.name)){const{message:a}=te("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),q(this,"isValidDisconnect",async r=>{if(!pr(r)){const{message:i}=te("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),q(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(!ut(i,!1))throw new Error("uri is required parameter");if(!ut(s,!1))throw new Error("domain is required parameter");if(!ut(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>ks(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ks(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),q(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||cl,validation:"UNKNOWN",origin:o.url||""}};try{if(a===it.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}),q(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=te("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),q(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),q(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)}}}),q(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=te("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),q(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,l,u,d,h;return!r||n!==it.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((d=r?.redirect)==null?void 0:d.universal)!==""&&((h=r?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),q(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),q(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=Vb(r,"topic")||"",i=decodeURIComponent(Vb(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:it.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),q(this,"registerLinkModeListeners",async()=>{var r;if(r0()||Li()&&(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)}}}),q(this,"getTVFParams",(r,n,i)=>{var s,o,a;if(!((s=n.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,i);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn("Error getting TVF params",l)}return c}),q(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}),q(this,"extractTxHashesFromResult",(r,n)=>{var i;try{if(!n)return[];const s=r.method,o=NU[s];if(s==="sui_signTransaction")return[kT(n.transactionBytes)];if(s==="near_signTransaction")return[fy(n)];if(s==="near_signTransactions")return n.map(c=>fy(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=n.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[AO({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return Kr(n)?n.map(c=>py(c)):[py(n)];if(s==="cosmos_signDirect")return[DT(n)];if(typeof n=="string")return[n];const a=n[o.key];if(Kr(a))return s==="solana_signAllTransactions"?a.map(c=>OT(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}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}=te("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ct.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(zd)?this.client.auth.authKeys.get(zd):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===it.link_mode?Ji:fr});Z0(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Vr(n)})):Ud(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(Jr.expired,async e=>{const{topic:r,id:n}=qb(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,te("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,te("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(Ws.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Ws.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ut(e,!1)){const{message:r}=te("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}=te("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Mi(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=te("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ut(e,!1)){const{message:r}=te("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}=te("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Mi(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=te("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=te("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(ut(e,!1)){const{message:r}=te("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=te("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!tO(e)){const{message:r}=te("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=te("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Mi(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=te("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class WU extends qs{constructor(e,r){super(e,r,SU,u1),this.core=e,this.logger=r}}class HU extends qs{constructor(e,r){super(e,r,IU,u1),this.core=e,this.logger=r}}class qU extends qs{constructor(e,r){super(e,r,$U,u1,n=>n.id),this.core=e,this.logger=r}}class VU extends qs{constructor(e,r){super(e,r,DU,jd,()=>zd),this.core=e,this.logger=r}}class KU extends qs{constructor(e,r){super(e,r,BU,jd),this.core=e,this.logger=r}}class GU extends qs{constructor(e,r){super(e,r,RU,jd,n=>n.id),this.core=e,this.logger=r}}var ZU=Object.defineProperty,YU=(t,e,r)=>e in t?ZU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p1=(t,e,r)=>YU(t,typeof e!="symbol"?e+"":e,r);class JU{constructor(e,r){this.core=e,this.logger=r,p1(this,"authKeys"),p1(this,"pairingTopics"),p1(this,"requests"),this.authKeys=new VU(this.core,this.logger),this.pairingTopics=new KU(this.core,this.logger),this.requests=new GU(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var XU=Object.defineProperty,QU=(t,e,r)=>e in t?XU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oe=(t,e,r)=>QU(t,typeof e!="symbol"?e+"":e,r);class g1 extends Xk{constructor(e){super(e),Oe(this,"protocol",qv),Oe(this,"version",Vv),Oe(this,"name",d1.name),Oe(this,"metadata"),Oe(this,"core"),Oe(this,"logger"),Oe(this,"events",new Tt.exports.EventEmitter),Oe(this,"engine"),Oe(this,"session"),Oe(this,"proposal"),Oe(this,"pendingRequest"),Oe(this,"auth"),Oe(this,"signConfig"),Oe(this,"on",(n,i)=>this.events.on(n,i)),Oe(this,"once",(n,i)=>this.events.once(n,i)),Oe(this,"off",(n,i)=>this.events.off(n,i)),Oe(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Oe(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Oe(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Oe(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Oe(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||d1.name,this.metadata=_I(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:On(nl({level:e?.logger||d1.logger}));this.core=e?.core||new AU(e),this.logger=tr(r,this.name),this.session=new HU(this.core,this.logger),this.proposal=new WU(this.core,this.logger),this.pendingRequest=new qU(this.core,this.logger),this.engine=new zU(this),this.auth=new JU(this.core,this.logger)}static async init(e){const r=new g1(e);return await r.initialize(),r}get context(){return wr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var w1={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof vt<"u"&&vt,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 vt<"u"&&vt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(w){return w&&DataView.prototype.isPrototypeOf(w)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(w){return w&&u.indexOf(Object.prototype.toString.call(w))>-1};function h(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function f(w){return typeof w!="string"&&(w=String(w)),w}function p(w){var m={next:function(){var A=w.shift();return{done:A===void 0,value:A}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function g(w){this.map={},w instanceof g?w.forEach(function(m,A){this.append(A,m)},this):Array.isArray(w)?w.forEach(function(m){if(m.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+m.length);this.append(m[0],m[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(m){this.append(m,w[m])},this)}g.prototype.append=function(w,m){w=h(w),m=f(m);var A=this.map[w];this.map[w]=A?A+", "+m:m},g.prototype.delete=function(w){delete this.map[h(w)]},g.prototype.get=function(w){return w=h(w),this.has(w)?this.map[w]:null},g.prototype.has=function(w){return this.map.hasOwnProperty(h(w))},g.prototype.set=function(w,m){this.map[h(w)]=f(m)},g.prototype.forEach=function(w,m){for(var A in this.map)this.map.hasOwnProperty(A)&&w.call(m,this.map[A],A,this)},g.prototype.keys=function(){var w=[];return this.forEach(function(m,A){w.push(A)}),p(w)},g.prototype.values=function(){var w=[];return this.forEach(function(m){w.push(m)}),p(w)},g.prototype.entries=function(){var w=[];return this.forEach(function(m,A){w.push([A,m])}),p(w)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function b(w){if(!w._noBody){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}}function C(w){return new Promise(function(m,A){w.onload=function(){m(w.result)},w.onerror=function(){A(w.error)}})}function x(w){var m=new FileReader,A=C(m);return m.readAsArrayBuffer(w),A}function y(w){var m=new FileReader,A=C(m),T=/charset=([A-Za-z0-9_-]+)/.exec(w.type),N=T?T[1]:"utf-8";return m.readAsText(w,N),A}function v(w){for(var m=new Uint8Array(w),A=new Array(m.length),T=0;T<m.length;T++)A[T]=String.fromCharCode(m[T]);return A.join("")}function _(w){if(w.slice)return w.slice(0);var m=new Uint8Array(w.byteLength);return m.set(new Uint8Array(w)),m.buffer}function O(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:c.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:c.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():c.arrayBuffer&&c.blob&&l(w)?(this._bodyArrayBuffer=_(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||d(w))?this._bodyArrayBuffer=_(w):this._bodyText=w=Object.prototype.toString.call(w):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof w=="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(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var w=b(this);if(w)return w;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 w=b(this);return w||(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(x);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var w=b(this);if(w)return w;if(this._bodyBlob)return y(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(v(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($)}),this.json=function(){return this.text().then(JSON.parse)},this}var B=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(w){var m=w.toUpperCase();return B.indexOf(m)>-1?m:w}function E(w,m){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var A=m.body;if(w instanceof E){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,m.headers||(this.headers=new g(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!A&&w._bodyInit!=null&&(A=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new g(m.headers)),this.method=R(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var T=/([?&])_=[^&]*/;if(T.test(this.url))this.url=this.url.replace(T,"$1_="+new Date().getTime());else{var N=/\?/;this.url+=(N.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function $(w){var m=new FormData;return w.trim().split("&").forEach(function(A){if(A){var T=A.split("="),N=T.shift().replace(/\+/g," "),k=T.join("=").replace(/\+/g," ");m.append(decodeURIComponent(N),decodeURIComponent(k))}}),m}function S(w){var m=new g,A=w.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(T){return T.indexOf(`
|
|
46
|
+
`)===0?T.substr(1,T.length):T}).forEach(function(T){var N=T.split(":"),k=N.shift().trim();if(k){var j=N.join(":").trim();try{m.append(k,j)}catch(z){console.warn("Response "+z.message)}}}),m}O.call(E.prototype);function D(w,m){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new g(m.headers),this.url=m.url||"",this._initBody(w)}O.call(D.prototype),D.prototype.clone=function(){return new D(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},D.error=function(){var w=new D(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var U=[301,302,303,307,308];D.redirect=function(w,m){if(U.indexOf(m)===-1)throw new RangeError("Invalid status code");return new D(null,{status:m,headers:{location:w}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,A){this.message=m,this.name=A;var T=Error(m);this.stack=T.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function M(w,m){return new Promise(function(A,T){var N=new E(w,m);if(N.signal&&N.signal.aborted)return T(new o.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function j(){k.abort()}k.onload=function(){var H={statusText:k.statusText,headers:S(k.getAllResponseHeaders()||"")};N.url.indexOf("file://")===0&&(k.status<200||k.status>599)?H.status=200:H.status=k.status,H.url="responseURL"in k?k.responseURL:H.headers.get("X-Request-URL");var J="response"in k?k.response:k.responseText;setTimeout(function(){A(new D(J,H))},0)},k.onerror=function(){setTimeout(function(){T(new TypeError("Network request failed"))},0)},k.ontimeout=function(){setTimeout(function(){T(new TypeError("Network request timed out"))},0)},k.onabort=function(){setTimeout(function(){T(new o.DOMException("Aborted","AbortError"))},0)};function z(H){try{return H===""&&a.location.href?a.location.href:H}catch{return H}}if(k.open(N.method,z(N.url),!0),N.credentials==="include"?k.withCredentials=!0:N.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(c.blob?k.responseType="blob":c.arrayBuffer&&(k.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof g||a.Headers&&m.headers instanceof a.Headers)){var G=[];Object.getOwnPropertyNames(m.headers).forEach(function(H){G.push(h(H)),k.setRequestHeader(H,f(m.headers[H]))}),N.headers.forEach(function(H,J){G.indexOf(J)===-1&&k.setRequestHeader(J,H)})}else N.headers.forEach(function(H,J){k.setRequestHeader(J,H)});N.signal&&(N.signal.addEventListener("abort",j),k.onreadystatechange=function(){k.readyState===4&&N.signal.removeEventListener("abort",j)}),k.send(typeof N._bodyInit>"u"?null:N._bodyInit)})}return M.polyfill=!0,a.fetch||(a.fetch=M,a.Headers=g,a.Request=E,a.Response=D),o.Headers=g,o.Request=E,o.Response=D,o.fetch=M,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})(w1,w1.exports);var Jv=L6(w1.exports),eL=Object.defineProperty,tL=Object.defineProperties,rL=Object.getOwnPropertyDescriptors,Xv=Object.getOwnPropertySymbols,nL=Object.prototype.hasOwnProperty,iL=Object.prototype.propertyIsEnumerable,Qv=(t,e,r)=>e in t?eL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,e5=(t,e)=>{for(var r in e||(e={}))nL.call(e,r)&&Qv(t,r,e[r]);if(Xv)for(var r of Xv(e))iL.call(e,r)&&Qv(t,r,e[r]);return t},t5=(t,e)=>tL(t,rL(e));const sL={Accept:"application/json","Content-Type":"application/json"},oL="POST",r5={headers:sL,method:oL},n5=10;class bn{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Tt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!X3(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=ri(e),n=await(await Jv(this.url,t5(e5({},r5),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!X3(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=ri({id:1,jsonrpc:"2.0",method:"test",params:[]});await Jv(e,t5(e5({},r5),{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"?$s(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=Rd(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return V3(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>n5&&this.events.setMaxListeners(n5)}}var aL=Object.defineProperty,i5=Object.getOwnPropertySymbols,cL=Object.prototype.hasOwnProperty,lL=Object.prototype.propertyIsEnumerable,s5=(t,e,r)=>e in t?aL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,o5=(t,e)=>{for(var r in e||(e={}))cL.call(e,r)&&s5(t,r,e[r]);if(i5)for(var r of i5(e))lL.call(e,r)&&s5(t,r,e[r]);return t};const a5="error",uL="wss://relay.walletconnect.org",dL="wc",hL="universal_provider",Wd=`${dL}@2:${hL}:`,c5="https://rpc.walletconnect.org/v1/",l5="generic",fL=`${c5}bundler`,Qr={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function m1(t){return t==null||typeof t!="object"&&typeof t!="function"}function u5(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function d5(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const pL="[object RegExp]",h5="[object String]",f5="[object Number]",p5="[object Boolean]",g5="[object Arguments]",gL="[object Symbol]",wL="[object Date]",mL="[object Map]",bL="[object Set]",yL="[object Array]",vL="[object ArrayBuffer]",CL="[object Object]",EL="[object DataView]",xL="[object Uint8Array]",_L="[object Uint8ClampedArray]",AL="[object Uint16Array]",SL="[object Uint32Array]",IL="[object Int8Array]",TL="[object Int16Array]",NL="[object Int32Array]",$L="[object Float32Array]",OL="[object Float64Array]";function b1(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function kL(t,e){return ta(t,void 0,t,new Map,e)}function ta(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(m1(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]=ta(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,ta(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(ta(a,void 0,r,n,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(b1(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=ta(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),Vs(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),Vs(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),Vs(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,Vs(o,t,r,n,i),o}if(typeof t=="object"&&PL(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),Vs(o,t,r,n,i),o}return t}function Vs(t,e,r=t,n,i){const s=[...Object.keys(e),...u5(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=ta(e[a],a,r,n,i))}}function PL(t){switch(d5(t)){case g5:case yL:case vL:case EL:case p5:case wL:case $L:case OL:case IL:case TL:case NL:case mL:case f5:case CL:case pL:case bL:case h5:case gL:case xL:case _L:case AL:case SL:return!0;default:return!1}}function DL(t,e){return kL(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 f5:case h5:case p5:{const a=new t.constructor(t?.valueOf());return Vs(a,t),a}case g5:{const a={};return Vs(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function w5(t){return DL(t)}function m5(t){return t!==null&&typeof t=="object"&&d5(t)==="[object Arguments]"}function b5(t){return typeof t=="object"&&t!==null}function BL(){}function RL(t){return b1(t)}function UL(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 LL(t){if(m1(t))return t;if(Array.isArray(t)||b1(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 ML(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=y1(i,o,n,new Map)}return i}function y1(t,e,r,n){var i;if(m1(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return LL(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),...u5(e)];for(let o=0;o<s.length;o++){const a=s[o];let c=e[a],l=t[a];if(m5(c)&&(c=o5({},c)),m5(l)&&(l=o5({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=w5(c)),Array.isArray(c))if(typeof l=="object"&&l!=null){const d=[],h=Reflect.ownKeys(l);for(let f=0;f<h.length;f++){const p=h[f];d[p]=l[p]}l=d}else l=[];const u=r(l,c,a,t,e,n);u!=null?t[a]=u:Array.isArray(c)||b5(l)&&b5(c)?t[a]=y1(l,c,r,n):l==null&&UL(c)?t[a]=y1({},c,r,n):l==null&&RL(c)?t[a]=w5(c):(l===void 0||c!==void 0)&&(t[a]=c)}return t}function FL(t,...e){return ML(t,...e,BL)}var jL=Object.defineProperty,zL=Object.defineProperties,WL=Object.getOwnPropertyDescriptors,y5=Object.getOwnPropertySymbols,HL=Object.prototype.hasOwnProperty,qL=Object.prototype.propertyIsEnumerable,v5=(t,e,r)=>e in t?jL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hd=(t,e)=>{for(var r in e||(e={}))HL.call(e,r)&&v5(t,r,e[r]);if(y5)for(var r of y5(e))qL.call(e,r)&&v5(t,r,e[r]);return t},VL=(t,e)=>zL(t,WL(e));function Pr(t,e,r){var n;const i=ks(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${c5}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Ks(t){return t.includes(":")?t.split(":")[1]:t}function C5(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function KL(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 E5(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var n,i;return((n=r?.chains)==null?void 0:n.length)&&((i=r?.chains)==null?void 0:i.length)>0}))}function qd(t={},e={}){const r=E5(x5(t)),n=E5(x5(e));return FL(r,n)}function x5(t){var e,r,n,i,s;const o={};if(!$n(t))return o;for(const[a,c]of Object.entries(t)){const l=Sd(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},f=Zo(a);o[f]=VL(Hd(Hd({},o[f]),c),{chains:Tn(l,(e=o[f])==null?void 0:e.chains),methods:Tn(u,(r=o[f])==null?void 0:r.methods),events:Tn(d,(n=o[f])==null?void 0:n.events)}),($n(h)||$n(((i=o[f])==null?void 0:i.rpcMap)||{}))&&(o[f].rpcMap=Hd(Hd({},h),(s=o[f])==null?void 0:s.rpcMap))}return o}function _5(t){return t.includes(":")?t.split(":")[2]:t}function A5(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=Sd(r)?[r]:n.chains?n.chains:C5(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function v1(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 S5={},Ue=t=>S5[t],C1=(t,e)=>{S5[t]=e};var GL=Object.defineProperty,I5=Object.getOwnPropertySymbols,ZL=Object.prototype.hasOwnProperty,YL=Object.prototype.propertyIsEnumerable,T5=(t,e,r)=>e in t?GL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,N5=(t,e)=>{for(var r in e||(e={}))ZL.call(e,r)&&T5(t,r,e[r]);if(I5)for(var r of I5(e))YL.call(e,r)&&T5(t,r,e[r]);return t};const $5="eip155",JL=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],XL=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,E1=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,O5=t=>Object.keys(t).filter(e=>JL.includes(e)).reduce((e,r)=>(e[r]=t[r],e),{}),QL=(t,e,r)=>{const{sessionProperties:n={},scopedProperties:i={}}=t,s={};if(!$n(i)&&!$n(n))return;const o=O5(n);for(const a of r){const c=XL(a);if(!c)continue;s[E1(c)]=o;const l=i?.[`${$5}:${c}`];if(l){const u=l?.[`${$5}:${c}:${e}`];s[E1(c)]=N5(N5({},s[E1(c)]),O5(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var eM=Object.defineProperty,tM=(t,e,r)=>e in t?eM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ra=(t,e,r)=>tM(t,typeof e!="symbol"?e+"":e,r);class rM{constructor(e){ra(this,"name","polkadot"),ra(this,"client"),ra(this,"httpProviders"),ra(this,"events"),ra(this,"namespace"),ra(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var nM=Object.defineProperty,iM=Object.defineProperties,sM=Object.getOwnPropertyDescriptors,k5=Object.getOwnPropertySymbols,oM=Object.prototype.hasOwnProperty,aM=Object.prototype.propertyIsEnumerable,x1=(t,e,r)=>e in t?nM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,P5=(t,e)=>{for(var r in e||(e={}))oM.call(e,r)&&x1(t,r,e[r]);if(k5)for(var r of k5(e))aM.call(e,r)&&x1(t,r,e[r]);return t},D5=(t,e)=>iM(t,sM(e)),na=(t,e,r)=>x1(t,typeof e!="symbol"?e+"":e,r);class cM{constructor(e){na(this,"name","eip155"),na(this,"client"),na(this,"chainId"),na(this,"namespace"),na(this,"httpProviders"),na(this,"events"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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||Pr(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("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(Ks(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,s,o;const a=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(i=e.request)==null?void 0:i.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},d=`${a}${c.join(",")}`,h=u?.[d];if(h)return h;let f;try{f=QL(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(f)return f;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:D5(P5({},l.sessionProperties||{}),{capabilities:D5(P5({},u||{}),{[d]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}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(Dn("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`${fL}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var lM=Object.defineProperty,uM=(t,e,r)=>e in t?lM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ia=(t,e,r)=>uM(t,typeof e!="symbol"?e+"":e,r);class dM{constructor(e){ia(this,"name","solana"),ia(this,"client"),ia(this,"httpProviders"),ia(this,"events"),ia(this,"namespace"),ia(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var hM=Object.defineProperty,fM=(t,e,r)=>e in t?hM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sa=(t,e,r)=>fM(t,typeof e!="symbol"?e+"":e,r);class pM{constructor(e){sa(this,"name","cosmos"),sa(this,"client"),sa(this,"httpProviders"),sa(this,"events"),sa(this,"namespace"),sa(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var gM=Object.defineProperty,wM=(t,e,r)=>e in t?gM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oa=(t,e,r)=>wM(t,typeof e!="symbol"?e+"":e,r);class mM{constructor(e){oa(this,"name","algorand"),oa(this,"client"),oa(this,"httpProviders"),oa(this,"events"),oa(this,"namespace"),oa(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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||Pr(`${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(Qr.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||Pr(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new Zr(new bn(n,Ue("disableProviderPing")))}}var bM=Object.defineProperty,yM=(t,e,r)=>e in t?bM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e,r)=>yM(t,typeof e!="symbol"?e+"":e,r);class vM{constructor(e){aa(this,"name","cip34"),aa(this,"client"),aa(this,"httpProviders"),aa(this,"events"),aa(this,"namespace"),aa(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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 Zr(new bn(n,Ue("disableProviderPing")))}}var CM=Object.defineProperty,EM=(t,e,r)=>e in t?CM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ca=(t,e,r)=>EM(t,typeof e!="symbol"?e+"":e,r);class xM{constructor(e){ca(this,"name","elrond"),ca(this,"client"),ca(this,"httpProviders"),ca(this,"events"),ca(this,"namespace"),ca(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var _M=Object.defineProperty,AM=(t,e,r)=>e in t?_M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,la=(t,e,r)=>AM(t,typeof e!="symbol"?e+"":e,r);class SM{constructor(e){la(this,"name","multiversx"),la(this,"client"),la(this,"httpProviders"),la(this,"events"),la(this,"namespace"),la(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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(Qr.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=Ks(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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var IM=Object.defineProperty,TM=(t,e,r)=>e in t?IM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ua=(t,e,r)=>TM(t,typeof e!="symbol"?e+"":e,r);class NM{constructor(e){ua(this,"name","near"),ua(this,"client"),ua(this,"httpProviders"),ua(this,"events"),ua(this,"namespace"),ua(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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||Pr(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Qr.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||Pr(e,this.namespace);return typeof n>"u"?void 0:new Zr(new bn(n,Ue("disableProviderPing")))}}var $M=Object.defineProperty,OM=(t,e,r)=>e in t?$M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,da=(t,e,r)=>OM(t,typeof e!="symbol"?e+"":e,r);class kM{constructor(e){da(this,"name","tezos"),da(this,"client"),da(this,"httpProviders"),da(this,"events"),da(this,"namespace"),da(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("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||Pr(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Qr.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||Pr(e,this.namespace);return typeof n>"u"?void 0:new Zr(new bn(n))}}var PM=Object.defineProperty,DM=(t,e,r)=>e in t?PM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ha=(t,e,r)=>DM(t,typeof e!="symbol"?e+"":e,r);class BM{constructor(e){ha(this,"name",l5),ha(this,"client"),ha(this,"httpProviders"),ha(this,"events"),ha(this,"namespace"),ha(this,"chainId"),this.namespace=e.namespace,this.events=Ue("events"),this.client=Ue("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Qr.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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return ks(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const n={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(i=>{const s=ks(i);n[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||Pr(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zr(new bn(n,Ue("disableProviderPing")))}}var RM=Object.defineProperty,UM=Object.defineProperties,LM=Object.getOwnPropertyDescriptors,B5=Object.getOwnPropertySymbols,MM=Object.prototype.hasOwnProperty,FM=Object.prototype.propertyIsEnumerable,_1=(t,e,r)=>e in t?RM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vd=(t,e)=>{for(var r in e||(e={}))MM.call(e,r)&&_1(t,r,e[r]);if(B5)for(var r of B5(e))FM.call(e,r)&&_1(t,r,e[r]);return t},A1=(t,e)=>UM(t,LM(e)),en=(t,e,r)=>_1(t,typeof e!="symbol"?e+"":e,r);class Kd{constructor(e){en(this,"client"),en(this,"namespaces"),en(this,"optionalNamespaces"),en(this,"sessionProperties"),en(this,"scopedProperties"),en(this,"events",new Tt.exports),en(this,"rpcProviders",{}),en(this,"session"),en(this,"providerOpts"),en(this,"logger"),en(this,"uri"),en(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:On(nl({level:e?.logger||a5})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new Kd(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:Vd({},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,ol(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:nt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri: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=A5(this.session.namespaces);this.namespaces=qd(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=A5(i.namespaces);return this.namespaces=qd(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);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!Kr(r))return;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}`)}catch(r){this.logger.warn("Failed to cleanup pending pairings",r)}}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 g1.init({core:this.providerOpts.core,logger:this.providerOpts.logger||a5,relayUrl:this.providerOpts.relayUrl||uL,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=>Zo(r)))];C1("client",this.client),C1("events",this.events),C1("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=KL(r,this.session);if(n?.length===0)return;const i=C5(n),s=qd(this.namespaces,this.optionalNamespaces),o=A1(Vd({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new cM({namespace:o});break;case"algorand":this.rpcProviders[r]=new mM({namespace:o});break;case"solana":this.rpcProviders[r]=new dM({namespace:o});break;case"cosmos":this.rpcProviders[r]=new pM({namespace:o});break;case"polkadot":this.rpcProviders[r]=new rM({namespace:o});break;case"cip34":this.rpcProviders[r]=new vM({namespace:o});break;case"elrond":this.rpcProviders[r]=new xM({namespace:o});break;case"multiversx":this.rpcProviders[r]=new SM({namespace:o});break;case"near":this.rpcProviders[r]=new NM({namespace:o});break;case"tezos":this.rpcProviders[r]=new kM({namespace:o});break;default:this.rpcProviders[r]=new BM({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&&Kr(o)&&this.events.emit("accountsChanged",o.map(_5))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Zo(o),l=v1(o)!==v1(a)?`${c}:${v1(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=A1(Vd({},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",A1(Vd({},nt("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Qr.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[l5]}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;this.optionalNamespaces=qd(r,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=>Zo(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=Zo(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);const s=this.getProvider(n).getDefaultChain();r?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:n,previousChainId:s,newChainId:e})):this.getProvider(n).setDefaultChain(i),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(_5);if(!Kr(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,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(`${Wd}/${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(`${Wd}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Wd}/${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(Wd)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}}const jM=Kd,zM="wc",WM="ethereum_provider",HM=`${zM}@2:${WM}:`,qM="https://rpc.walletconnect.org/v1/",Gd=["eth_sendTransaction","personal_sign"],R5=["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"],Zd=["chainChanged","accountsChanged"],U5=["chainChanged","accountsChanged","message","disconnect","connect"],VM=async()=>{const{createAppKit:t}=await Promise.resolve().then(function(){return Wj});return t};var KM=Object.defineProperty,GM=Object.defineProperties,ZM=Object.getOwnPropertyDescriptors,L5=Object.getOwnPropertySymbols,YM=Object.prototype.hasOwnProperty,JM=Object.prototype.propertyIsEnumerable,S1=(t,e,r)=>e in t?KM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gs=(t,e)=>{for(var r in e||(e={}))YM.call(e,r)&&S1(t,r,e[r]);if(L5)for(var r of L5(e))JM.call(e,r)&&S1(t,r,e[r]);return t},wl=(t,e)=>GM(t,ZM(e)),Dr=(t,e,r)=>S1(t,typeof e!="symbol"?e+"":e,r);function Yd(t){return Number(t[0].split(":")[1])}function Jd(t){return`0x${t.toString(16)}`}function XM(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!Kr(e))throw new Error("Invalid chains");const c={chains:e,methods:n||Gd,events:s||Zd,rpcMap:Gs({},e.length?{[Yd(e)]:a[Yd(e)]}:{})},l=s?.filter(f=>!Zd.includes(f)),u=n?.filter(f=>!Gd.includes(f));if(!r&&!o&&!i&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const d=l?.length&&u?.length||!r,h={chains:[...new Set(d?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:R5))],events:[...new Set(c.events.concat(o!=null&&o.length?o:U5))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?h:void 0}}class Xd{constructor(){Dr(this,"events",new Tt.exports.EventEmitter),Dr(this,"namespace","eip155"),Dr(this,"accounts",[]),Dr(this,"signer"),Dr(this,"chainId",1),Dr(this,"modal"),Dr(this,"rpc"),Dr(this,"STORAGE_KEY",HM),Dr(this,"on",(e,r)=>(this.events.on(e,r),this)),Dr(this,"once",(e,r)=>(this.events.once(e,r),this)),Dr(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Dr(this,"off",(e,r)=>(this.events.off(e,r),this)),Dr(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Xd;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:n,optional:i}=XM(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const d=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(wl(Gs({namespaces:Gs({},n&&{[this.namespace]:n})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic,scopedProperties:d})).then(h=>{a(h)}).catch(h=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(h.message))})});if(!s)return;const o=Rb(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Jd(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(wl(Gs({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=i.session;if(s){const o=Rb(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Jd(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(n=this.modal)==null||n.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Jd(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",wl(Gs({},nt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Jd(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||Gd:[],c=i.length?e?.events||Zd:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],d=e?.rpcMap||this.buildRpcMap(o,e.projectId),h=e?.qrModalOptions||void 0;return{chains:i?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:d,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:h,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Yd(this.rpc.chains):Yd(this.rpc.optionalChains),this.signer=await jM.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 n=await VM(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return Qj}),s=i(wl(Gs({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!s.networks.length)throw new Error("No networks found for WalletConnect\xB7");r=n(wl(Gs({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&Kr(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&Kr(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])||`${qM}?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 QM=Xd;var M5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){var r=1e3,n=6e4,i=36e5,s="millisecond",o="second",a="minute",c="hour",l="day",u="week",d="month",h="quarter",f="year",p="date",g="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,C=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,x={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(M){var w=["th","st","nd","rd"],m=M%100;return"["+M+(w[(m-20)%10]||w[m]||w[0])+"]"}},y=function(M,w,m){var A=String(M);return!A||A.length>=w?M:""+Array(w+1-A.length).join(m)+M},v={s:y,z:function(M){var w=-M.utcOffset(),m=Math.abs(w),A=Math.floor(m/60),T=m%60;return(w<=0?"+":"-")+y(A,2,"0")+":"+y(T,2,"0")},m:function M(w,m){if(w.date()<m.date())return-M(m,w);var A=12*(m.year()-w.year())+(m.month()-w.month()),T=w.clone().add(A,d),N=m-T<0,k=w.clone().add(A+(N?-1:1),d);return+(-(A+(m-T)/(N?T-k:k-T))||0)},a:function(M){return M<0?Math.ceil(M)||0:Math.floor(M)},p:function(M){return{M:d,y:f,w:u,d:l,D:p,h:c,m:a,s:o,ms:s,Q:h}[M]||String(M||"").toLowerCase().replace(/s$/,"")},u:function(M){return M===void 0}},_="en",O={};O[_]=x;var B="$isDayjsObject",R=function(M){return M instanceof D||!(!M||!M[B])},E=function M(w,m,A){var T;if(!w)return _;if(typeof w=="string"){var N=w.toLowerCase();O[N]&&(T=N),m&&(O[N]=m,T=N);var k=w.split("-");if(!T&&k.length>1)return M(k[0])}else{var j=w.name;O[j]=w,T=j}return!A&&T&&(_=T),T||!A&&_},$=function(M,w){if(R(M))return M.clone();var m=typeof w=="object"?w:{};return m.date=M,m.args=arguments,new D(m)},S=v;S.l=E,S.i=R,S.w=function(M,w){return $(M,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var D=function(){function M(m){this.$L=E(m.locale,null,!0),this.parse(m),this.$x=this.$x||m.x||{},this[B]=!0}var w=M.prototype;return w.parse=function(m){this.$d=function(A){var T=A.date,N=A.utc;if(T===null)return new Date(NaN);if(S.u(T))return new Date;if(T instanceof Date)return new Date(T);if(typeof T=="string"&&!/Z$/i.test(T)){var k=T.match(b);if(k){var j=k[2]-1||0,z=(k[7]||"0").substring(0,3);return N?new Date(Date.UTC(k[1],j,k[3]||1,k[4]||0,k[5]||0,k[6]||0,z)):new Date(k[1],j,k[3]||1,k[4]||0,k[5]||0,k[6]||0,z)}}return new Date(T)}(m),this.init()},w.init=function(){var m=this.$d;this.$y=m.getFullYear(),this.$M=m.getMonth(),this.$D=m.getDate(),this.$W=m.getDay(),this.$H=m.getHours(),this.$m=m.getMinutes(),this.$s=m.getSeconds(),this.$ms=m.getMilliseconds()},w.$utils=function(){return S},w.isValid=function(){return this.$d.toString()!==g},w.isSame=function(m,A){var T=$(m);return this.startOf(A)<=T&&T<=this.endOf(A)},w.isAfter=function(m,A){return $(m)<this.startOf(A)},w.isBefore=function(m,A){return this.endOf(A)<$(m)},w.$g=function(m,A,T){return S.u(m)?this[A]:this.set(T,m)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(m,A){var T=this,N=!!S.u(A)||A,k=S.p(m),j=function(ge,Ee){var He=S.w(T.$u?Date.UTC(T.$y,Ee,ge):new Date(T.$y,Ee,ge),T);return N?He:He.endOf(l)},z=function(ge,Ee){return S.w(T.toDate()[ge].apply(T.toDate("s"),(N?[0,0,0,0]:[23,59,59,999]).slice(Ee)),T)},G=this.$W,H=this.$M,J=this.$D,fe="set"+(this.$u?"UTC":"");switch(k){case f:return N?j(1,0):j(31,11);case d:return N?j(1,H):j(0,H+1);case u:var ve=this.$locale().weekStart||0,Se=(G<ve?G+7:G)-ve;return j(N?J-Se:J+(6-Se),H);case l:case p:return z(fe+"Hours",0);case c:return z(fe+"Minutes",1);case a:return z(fe+"Seconds",2);case o:return z(fe+"Milliseconds",3);default:return this.clone()}},w.endOf=function(m){return this.startOf(m,!1)},w.$set=function(m,A){var T,N=S.p(m),k="set"+(this.$u?"UTC":""),j=(T={},T[l]=k+"Date",T[p]=k+"Date",T[d]=k+"Month",T[f]=k+"FullYear",T[c]=k+"Hours",T[a]=k+"Minutes",T[o]=k+"Seconds",T[s]=k+"Milliseconds",T)[N],z=N===l?this.$D+(A-this.$W):A;if(N===d||N===f){var G=this.clone().set(p,1);G.$d[j](z),G.init(),this.$d=G.set(p,Math.min(this.$D,G.daysInMonth())).$d}else j&&this.$d[j](z);return this.init(),this},w.set=function(m,A){return this.clone().$set(m,A)},w.get=function(m){return this[S.p(m)]()},w.add=function(m,A){var T,N=this;m=Number(m);var k=S.p(A),j=function(H){var J=$(N);return S.w(J.date(J.date()+Math.round(H*m)),N)};if(k===d)return this.set(d,this.$M+m);if(k===f)return this.set(f,this.$y+m);if(k===l)return j(1);if(k===u)return j(7);var z=(T={},T[a]=n,T[c]=i,T[o]=r,T)[k]||1,G=this.$d.getTime()+m*z;return S.w(G,this)},w.subtract=function(m,A){return this.add(-1*m,A)},w.format=function(m){var A=this,T=this.$locale();if(!this.isValid())return T.invalidDate||g;var N=m||"YYYY-MM-DDTHH:mm:ssZ",k=S.z(this),j=this.$H,z=this.$m,G=this.$M,H=T.weekdays,J=T.months,fe=T.meridiem,ve=function(Ee,He,yt,Ft){return Ee&&(Ee[He]||Ee(A,N))||yt[He].slice(0,Ft)},Se=function(Ee){return S.s(j%12||12,Ee,"0")},ge=fe||function(Ee,He,yt){var Ft=Ee<12?"AM":"PM";return yt?Ft.toLowerCase():Ft};return N.replace(C,function(Ee,He){return He||function(yt){switch(yt){case"YY":return String(A.$y).slice(-2);case"YYYY":return S.s(A.$y,4,"0");case"M":return G+1;case"MM":return S.s(G+1,2,"0");case"MMM":return ve(T.monthsShort,G,J,3);case"MMMM":return ve(J,G);case"D":return A.$D;case"DD":return S.s(A.$D,2,"0");case"d":return String(A.$W);case"dd":return ve(T.weekdaysMin,A.$W,H,2);case"ddd":return ve(T.weekdaysShort,A.$W,H,3);case"dddd":return H[A.$W];case"H":return String(j);case"HH":return S.s(j,2,"0");case"h":return Se(1);case"hh":return Se(2);case"a":return ge(j,z,!0);case"A":return ge(j,z,!1);case"m":return String(z);case"mm":return S.s(z,2,"0");case"s":return String(A.$s);case"ss":return S.s(A.$s,2,"0");case"SSS":return S.s(A.$ms,3,"0");case"Z":return k}return null}(Ee)||k.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(m,A,T){var N,k=this,j=S.p(A),z=$(m),G=(z.utcOffset()-this.utcOffset())*n,H=this-z,J=function(){return S.m(k,z)};switch(j){case f:N=J()/12;break;case d:N=J();break;case h:N=J()/3;break;case u:N=(H-G)/6048e5;break;case l:N=(H-G)/864e5;break;case c:N=H/i;break;case a:N=H/n;break;case o:N=H/r;break;default:N=H}return T?N:S.a(N)},w.daysInMonth=function(){return this.endOf(d).$D},w.$locale=function(){return O[this.$L]},w.locale=function(m,A){if(!m)return this.$L;var T=this.clone(),N=E(m,A,!0);return N&&(T.$L=N),T},w.clone=function(){return S.w(this.$d,this)},w.toDate=function(){return new Date(this.valueOf())},w.toJSON=function(){return this.isValid()?this.toISOString():null},w.toISOString=function(){return this.$d.toISOString()},w.toString=function(){return this.$d.toUTCString()},M}(),U=D.prototype;return $.prototype=U,[["$ms",s],["$s",o],["$m",a],["$H",c],["$W",l],["$M",d],["$y",f],["$D",p]].forEach(function(M){U[M[1]]=function(w){return this.$g(w,M[0],M[1])}}),$.extend=function(M,w){return M.$i||(M(w,D,$),M.$i=!0),$},$.locale=E,$.isDayjs=R,$.unix=function(M){return $(1e3*M)},$.en=O[_],$.Ls=O,$.p={},$})})(M5);var I1=M5.exports,F5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){return{name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(r){var n=["th","st","nd","rd"],i=r%100;return"["+r+(n[(i-20)%10]||n[i]||n[0])+"]"}}})})(F5);var eF=F5.exports,j5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){return function(r,n,i){r=r||{};var s=n.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(l,u,d,h){return s.fromToBase(l,u,d,h)}i.en.relativeTime=o,s.fromToBase=function(l,u,d,h,f){for(var p,g,b,C=d.$locale().relativeTime||o,x=r.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],y=x.length,v=0;v<y;v+=1){var _=x[v];_.d&&(p=h?i(l).diff(d,_.d,!0):d.diff(l,_.d,!0));var O=(r.rounding||Math.round)(Math.abs(p));if(b=p>0,O<=_.r||!_.r){O<=1&&v>0&&(_=x[v-1]);var B=C[_.l];f&&(O=f(""+O)),g=typeof B=="string"?B.replace("%d",O):B(O,u,_.l,b);break}}if(u)return g;var R=b?C.future:C.past;return typeof R=="function"?R(g):R.replace("%s",g)},s.to=function(l,u){return a(l,u,this,!0)},s.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?i.utc():i()};s.toNow=function(l){return this.to(c(this),l)},s.fromNow=function(l){return this.from(c(this),l)}}})})(j5);var tF=j5.exports,z5={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(vt,function(){return function(r,n,i){i.updateLocale=function(s,o){var a=i.Ls[s];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(z5);var rF=z5.exports;I1.extend(tF),I1.extend(rF);const nF={...eF,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}};I1.locale("en-web3-modal",nF);const oe={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},W5={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(r=>r.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const r=t.find(i=>i.caipNetworkId===e);if(r)return r.name;const[n]=e.split(":");return oe.CHAIN_NAME_MAP?.[n]||void 0}};var iF=20,sF=1,Zs=1e6,H5=1e6,oF=-7,aF=21,cF=!1,ml="[big.js] ",Ys=ml+"Invalid ",Qd=Ys+"decimal places",lF=Ys+"rounding mode",q5=ml+"Division by zero",Ve={},Fn=void 0,uF=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function V5(){function t(e){var r=this;if(!(r instanceof t))return e===Fn?V5():new t(e);if(e instanceof t)r.s=e.s,r.e=e.e,r.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(Ys+"value");e=e===0&&1/e<0?"-0":String(e)}dF(r,e)}r.constructor=t}return t.prototype=Ve,t.DP=iF,t.RM=sF,t.NE=oF,t.PE=aF,t.strict=cF,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function dF(t,e){var r,n,i;if(!uF.test(e))throw Error(Ys+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),i=e.length,n=0;n<i&&e.charAt(n)=="0";)++n;if(n==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=r-n-1,t.c=[],r=0;n<=i;)t.c[r++]=+e.charAt(n++)}return t}function Js(t,e,r,n){var i=t.c;if(r===Fn&&(r=t.constructor.RM),r!==0&&r!==1&&r!==2&&r!==3)throw Error(lF);if(e<1)n=r===3&&(n||!!i[0])||e===0&&(r===1&&i[0]>=5||r===2&&(i[0]>5||i[0]===5&&(n||i[1]!==Fn))),i.length=1,n?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(n=r===1&&i[e]>=5||r===2&&(i[e]>5||i[e]===5&&(n||i[e+1]!==Fn||i[e-1]&1))||r===3&&(n||!!i[0]),i.length=e,n){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function Xs(t,e,r){var n=t.e,i=t.c.join(""),s=i.length;if(e)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)i="0"+i;i="0."+i}else if(n>0)if(++n>s)for(n-=s;n--;)i+="0";else n<s&&(i=i.slice(0,n)+"."+i.slice(n));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&r?"-"+i:i}Ve.abs=function(){var t=new this.constructor(this);return t.s=1,t},Ve.cmp=function(t){var e,r=this,n=r.c,i=(t=new r.constructor(t)).c,s=r.s,o=t.s,a=r.e,c=t.e;if(!n[0]||!i[0])return n[0]?s:i[0]?-o:0;if(s!=o)return s;if(e=s<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=i.length)?a:c,s=-1;++s<o;)if(n[s]!=i[s])return n[s]>i[s]^e?1:-1;return a==c?0:a>c^e?1:-1},Ve.div=function(t){var e=this,r=e.constructor,n=e.c,i=(t=new r(t)).c,s=e.s==t.s?1:-1,o=r.DP;if(o!==~~o||o<0||o>Zs)throw Error(Qd);if(!i[0])throw Error(q5);if(!n[0])return t.s=s,t.c=[t.e=0],t;var a,c,l,u,d,h=i.slice(),f=a=i.length,p=n.length,g=n.slice(0,a),b=g.length,C=t,x=C.c=[],y=0,v=o+(C.e=e.e-t.e)+1;for(C.s=s,s=v<0?0:v,h.unshift(0);b++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(b=g.length))u=a>b?1:-1;else for(d=-1,u=0;++d<a;)if(i[d]!=g[d]){u=i[d]>g[d]?1:-1;break}if(u<0){for(c=b==a?i:h;b;){if(g[--b]<c[b]){for(d=b;d&&!g[--d];)g[d]=9;--g[d],g[b]+=10}g[b]-=c[b]}for(;!g[0];)g.shift()}else break}x[y++]=u?l:++l,g[0]&&u?g[b]=n[f]||0:g=[n[f]]}while((f++<p||g[0]!==Fn)&&s--);return!x[0]&&y!=1&&(x.shift(),C.e--,v--),y>v&&Js(C,v,r.RM,g[0]!==Fn),C},Ve.eq=function(t){return this.cmp(t)===0},Ve.gt=function(t){return this.cmp(t)>0},Ve.gte=function(t){return this.cmp(t)>-1},Ve.lt=function(t){return this.cmp(t)<0},Ve.lte=function(t){return this.cmp(t)<1},Ve.minus=Ve.sub=function(t){var e,r,n,i,s=this,o=s.constructor,a=s.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,s.plus(t);var l=s.c.slice(),u=s.e,d=t.c,h=t.e;if(!l[0]||!d[0])return d[0]?t.s=-c:l[0]?t=new o(s):t.s=1,t;if(a=u-h){for((i=a<0)?(a=-a,n=l):(h=u,n=d),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(r=((i=l.length<d.length)?l:d).length,a=c=0;c<r;c++)if(l[c]!=d[c]){i=l[c]<d[c];break}if(i&&(n=l,l=d,d=n,t.s=-t.s),(c=(r=d.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;r>a;){if(l[--r]<d[r]){for(e=r;e&&!l[--e];)l[e]=9;--l[e],l[r]+=10}l[r]-=d[r]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t},Ve.mod=function(t){var e,r=this,n=r.constructor,i=r.s,s=(t=new n(t)).s;if(!t.c[0])throw Error(q5);return r.s=t.s=1,e=t.cmp(r)==1,r.s=i,t.s=s,e?new n(r):(i=n.DP,s=n.RM,n.DP=n.RM=0,r=r.div(t),n.DP=i,n.RM=s,this.minus(r.times(t)))},Ve.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t},Ve.plus=Ve.add=function(t){var e,r,n,i=this,s=i.constructor;if(t=new s(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new s(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,r=0;e;a[e]%=10)r=(a[--e]=a[e]+l[e]+r)/10|0;for(r&&(a.unshift(r),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t},Ve.pow=function(t){var e=this,r=new e.constructor("1"),n=r,i=t<0;if(t!==~~t||t<-H5||t>H5)throw Error(Ys+"exponent");for(i&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return i?r.div(n):n},Ve.prec=function(t,e){if(t!==~~t||t<1||t>Zs)throw Error(Ys+"precision");return Js(new this.constructor(this),t,e)},Ve.round=function(t,e){if(t===Fn)t=0;else if(t!==~~t||t<-Zs||t>Zs)throw Error(Qd);return Js(new this.constructor(this),t+this.e+1,e)},Ve.sqrt=function(){var t,e,r,n=this,i=n.constructor,s=n.s,o=n.e,a=new i("0.5");if(!n.c[0])return new i(n);if(s<0)throw Error(ml+"No square root");s=Math.sqrt(+Xs(n,!0,!0)),s===0||s===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),s=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):t=new i(s+""),o=t.e+(i.DP+=4);do r=t,t=a.times(r.plus(n.div(r)));while(r.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return Js(t,(i.DP-=4)+t.e+1,i.RM)},Ve.times=Ve.mul=function(t){var e,r=this,n=r.constructor,i=r.c,s=(t=new n(t)).c,o=i.length,a=s.length,c=r.e,l=t.e;if(t.s=r.s==t.s?1:-1,!i[0]||!s[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=s,s=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+s[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t},Ve.toExponential=function(t,e){var r=this,n=r.c[0];if(t!==Fn){if(t!==~~t||t<0||t>Zs)throw Error(Qd);for(r=Js(new r.constructor(r),++t,e);r.c.length<t;)r.c.push(0)}return Xs(r,!0,!!n)},Ve.toFixed=function(t,e){var r=this,n=r.c[0];if(t!==Fn){if(t!==~~t||t<0||t>Zs)throw Error(Qd);for(r=Js(new r.constructor(r),t+r.e+1,e),t=t+r.e+1;r.c.length<t;)r.c.push(0)}return Xs(r,!1,!!n)},Ve[Symbol.for("nodejs.util.inspect.custom")]=Ve.toJSON=Ve.toString=function(){var t=this,e=t.constructor;return Xs(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])},Ve.toNumber=function(){var t=+Xs(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(ml+"Imprecise conversion");return t},Ve.toPrecision=function(t,e){var r=this,n=r.constructor,i=r.c[0];if(t!==Fn){if(t!==~~t||t<1||t>Zs)throw Error(Ys+"precision");for(r=Js(new n(r),t,e);r.c.length<t;)r.c.push(0)}return Xs(r,t<=r.e||r.e<=n.NE||r.e>=n.PE,!!i)},Ve.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(ml+"valueOf disallowed");return Xs(t,t.e<=e.NE||t.e>=e.PE,!0)};var bl=V5();const tt={bigNumber(t){return t?new bl(t):new bl(0)},multiply(t,e){if(t===void 0||e===void 0)return new bl(0);const r=new bl(t),n=new bl(e);return r.times(n)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},hF=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],fF=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],pF=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],gF={getERC20Abi:t=>oe.USDT_CONTRACT_ADDRESSES.includes(t)?pF:hF,getSwapAbi:()=>fF},es={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[r,n,i]=e;if(!r||!n||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:r,chainId:n,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[r,n]=e;if(!r||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:r,chainId:n}}},_e={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function T1(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Ce={setItem(t,e){yl()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(yl())return localStorage.getItem(t)||void 0},removeItem(t){yl()&&localStorage.removeItem(t)},clear(){yl()&&localStorage.clear()}};function yl(){return typeof window<"u"&&typeof localStorage<"u"}function ts(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const wF=Symbol(),K5=Object.getPrototypeOf,N1=new WeakMap,mF=t=>t&&(N1.has(t)?N1.get(t):K5(t)===Object.prototype||K5(t)===Array.prototype),bF=t=>mF(t)&&t[wF]||null,G5=(t,e=!0)=>{N1.set(t,e)},$1=t=>typeof t=="object"&&t!==null,rs=new WeakMap,vl=new WeakSet,yF=(t=Object.is,e=(l,u)=>new Proxy(l,u),r=l=>$1(l)&&!vl.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,u,d=n)=>{const h=i.get(l);if(h?.[0]===u)return h[1];const f=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return G5(f,!0),i.set(l,[u,f]),Reflect.ownKeys(l).forEach(p=>{if(Object.getOwnPropertyDescriptor(f,p))return;const g=Reflect.get(l,p),{enumerable:b}=Reflect.getOwnPropertyDescriptor(l,p),C={value:g,enumerable:b,configurable:!0};if(vl.has(g))G5(g,!1);else if(g instanceof Promise)delete C.value,C.get=()=>d(g);else if(rs.has(g)){const[x,y]=rs.get(g);C.value=s(x,y(),d)}Object.defineProperty(f,p,C)}),Object.preventExtensions(f)},o=new WeakMap,a=[1,1],c=l=>{if(!$1(l))throw new Error("object required");const u=o.get(l);if(u)return u;let d=a[0];const h=new Set,f=(E,$=++a[0])=>{d!==$&&(d=$,h.forEach(S=>S(E,$)))};let p=a[1];const g=(E=++a[1])=>(p!==E&&!h.size&&(p=E,C.forEach(([$])=>{const S=$[1](E);S>d&&(d=S)})),d),b=E=>($,S)=>{const D=[...$];D[1]=[E,...D[1]],f(D,S)},C=new Map,x=(E,$)=>{if(C.has(E))throw new Error("prop listener already exists");if(h.size){const S=$[3](b(E));C.set(E,[$,S])}else C.set(E,[$])},y=E=>{var $;const S=C.get(E);S&&(C.delete(E),($=S[1])==null||$.call(S))},v=E=>(h.add(E),h.size===1&&C.forEach(([S,D],U)=>{if(D)throw new Error("remove already exists");const M=S[3](b(U));C.set(U,[S,M])}),()=>{h.delete(E),h.size===0&&C.forEach(([S,D],U)=>{D&&(D(),C.set(U,[S]))})}),_=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),B=e(_,{deleteProperty(E,$){const S=Reflect.get(E,$);y($);const D=Reflect.deleteProperty(E,$);return D&&f(["delete",[$],S]),D},set(E,$,S,D){const U=Reflect.has(E,$),M=Reflect.get(E,$,D);if(U&&(t(M,S)||o.has(S)&&t(M,o.get(S))))return!0;y($),$1(S)&&(S=bF(S)||S);let w=S;if(S instanceof Promise)S.then(m=>{S.status="fulfilled",S.value=m,f(["resolve",[$],m])}).catch(m=>{S.status="rejected",S.reason=m,f(["reject",[$],m])});else{!rs.has(S)&&r(S)&&(w=c(S));const m=!vl.has(w)&&rs.get(w);m&&x($,m)}return Reflect.set(E,$,w,D),f(["set",[$],S,M]),!0}});o.set(l,B);const R=[_,g,s,v];return rs.set(B,R),Reflect.ownKeys(l).forEach(E=>{const $=Object.getOwnPropertyDescriptor(l,E);"value"in $&&(B[E]=l[E],delete $.value,delete $.writable),Object.defineProperty(_,E,$)}),B})=>[c,rs,vl,t,e,r,n,i,s,o,a],[vF]=yF();function Ye(t={}){return vF(t)}function At(t,e,r){const n=rs.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 Cl(t,e){const r=rs.get(t);r||console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}function Qs(t){return vl.add(t),t}function St(t,e,r,n){let i=t[e];return At(t,()=>{const s=t[e];Object.is(i,s)||r(i=s)},n)}function CF(t){const e=Ye({data:Array.from(t||[]),has(r){return this.data.some(n=>n[0]===r)},set(r,n){const i=this.data.find(s=>s[0]===r);return i?i[1]=n:this.data.push([r,n]),this},get(r){var n;return(n=this.data.find(i=>i[0]===r))==null?void 0:n[1]},delete(r){const n=this.data.findIndex(i=>i[0]===r);return n===-1?!1:(this.data.splice(n,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(r){this.data.forEach(n=>{r(n[1],n[0],this)})},keys(){return this.data.map(r=>r[0]).values()},values(){return this.data.map(r=>r[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}const O1=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Z5=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],EF="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Me={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:O1,SECURE_SITE_DASHBOARD:`${O1}/dashboard`,SECURE_SITE_FAVICON:`${O1}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}},le={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=le.getActiveNamespace(),e=le.getActiveCaipNetworkId(),r=e?e.split(":")[1]:void 0,n=r?isNaN(Number(r))?r:Number(r):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{Ce.setItem(_e.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Ce.getItem(_e.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Ce.removeItem(_e.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Ce.setItem(_e.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Ce.setItem(_e.ACTIVE_CAIP_NETWORK_ID,t),le.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Ce.getItem(_e.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Ce.removeItem(_e.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=T1(t);Ce.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=le.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Ce.setItem(_e.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Ce.getItem(_e.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const r=T1(t);Ce.setItem(r,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Ce.getItem(_e.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=T1(t);return Ce.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{Ce.setItem(_e.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Ce.getItem(_e.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Ce.removeItem(_e.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Ce.getItem(_e.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Ce.getItem(_e.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Ce.setItem(_e.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Ce.getItem(_e.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Ce.getItem(_e.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Ce.setItem(_e.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=le.getConnectedNamespaces();e.includes(t)||(e.push(t),le.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=le.getConnectedNamespaces(),r=e.indexOf(t);r>-1&&(e.splice(r,1),le.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Ce.getItem(_e.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Ce.setItem(_e.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Ce.removeItem(_e.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Ce.getItem(_e.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=le.getBalanceCache();Ce.setItem(_e.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const r=le.getBalanceCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.portfolio))return r.balance;le.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=le.getBalanceCache();e[t.caipAddress]=t,Ce.setItem(_e.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Ce.getItem(_e.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=le.getBalanceCache();Ce.setItem(_e.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const r=le.getNativeBalanceCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.nativeBalance))return r;console.info("Discarding cache for address",t),le.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=le.getNativeBalanceCache();e[t.caipAddress]=t,Ce.setItem(_e.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Ce.getItem(_e.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const r=le.getEnsCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.ens))return r.ens;le.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=le.getEnsCache();e[t.address]=t,Ce.setItem(_e.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=le.getEnsCache();Ce.setItem(_e.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Ce.getItem(_e.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const r=le.getIdentityCache()[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.identity))return r.identity;le.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=le.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Ce.setItem(_e.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=le.getIdentityCache();Ce.setItem(_e.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Ce.removeItem(_e.PORTFOLIO_CACHE),Ce.removeItem(_e.NATIVE_BALANCE_CACHE),Ce.removeItem(_e.ENS_CACHE),Ce.removeItem(_e.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Ce.setItem(_e.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Ce.getItem(_e.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const r={...le.getConnections(),[e]:t};Ce.setItem(_e.CONNECTIONS,JSON.stringify(r))}catch(r){console.error("Unable to sync connections to storage",r)}},getConnections(){try{const t=Ce.getItem(_e.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},Y={isMobile(){return this.isClient()?!!(typeof window?.matchMedia=="function"&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return Y.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Me.TEN_SEC_MS:!0},isAllowedRetry(t,e=Me.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(Y.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const r=new URL(t),n=new URL(e);return r.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Me.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let r;return(...n)=>{function i(){t(...n)}r&&clearTimeout(r),r=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,r=null){if(Y.isHttpUrl(t))return this.formatUniversalUrl(t,e);let n=t,i=r;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const s=encodeURIComponent(e);return{redirect:`${n}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:n}},formatUniversalUrl(t,e){if(!Y.isHttpUrl(t))return this.formatNativeUrl(t,e);let r=t;r.endsWith("/")||(r=`${r}/`);const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,href:r}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?le.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,r){window?.open(t,this.getOpenTargetForPlatform(e),r||"noreferrer noopener")},returnOpenHref(t,e,r){return window?.open(t,this.getOpenTargetForPlatform(e),r||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window.matchMedia?.("(display-mode: standalone)")?.matches,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((r,n)=>{const i=new Image;i.onload=r,i.onerror=n,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,Y.wait(2e3)])},formatBalance(t,e){let r="0.000";if(typeof t=="string"){const n=Number(t);if(n){const i=Math.floor(n*1e3)/1e3;i&&(r=i.toString())}}return`${r}${e?` ${e}`:""}`},formatBalance2(t,e){let r;if(t==="0")r="0";else if(typeof t=="string"){const n=Number(t);n&&(r=n.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:r??"0",rest:r==="0"?"000":"",symbol:e}},getApiUrl(){return oe.W3M_API_URL},getBlockchainApiUrl(){return oe.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return oe.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const r={};return e&&t&&(t.forEach((n,i)=>{r[n]=i}),e.sort((n,i)=>{const s=r[n.id],o=r[i.id];return s!==void 0&&o!==void 0?s-o:s!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const r of t)e+=r.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[r,n]=e.split(".");return{dollars:r,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const r=new Set;return t.filter(n=>{const i=n[e];return r.has(i)?!1:(r.add(i),!0)})},generateSdkVersion(t,e,r){const i=t.length===0?Me.ADAPTER_TYPES.UNIVERSAL:t.map(s=>s.adapterType).join(",");return`${e}-${i}-${r}`},createAccount(t,e,r,n,i){return{namespace:t,address:e,type:r,publicKey:n,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),r=e[0];return e.filter(Boolean).length===3&&r in oe.CHAIN_NAME_MAP},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,r="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",s=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),r,e);return t.replace(s,encodeURIComponent(o))}return this.injectIntoUrl(t,r,e)},injectIntoUrl(t,e,r){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",n),s=e.length,o=i!==-1?i:t.length,a=t.substring(0,n+s),c=t.substring(n+s,o),l=t.substring(i),u=c+r;return a+u+l}};async function El(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class xl{constructor({baseUrl:e,clientId:r}){this.baseUrl=e,this.clientId=r}async get({headers:e,signal:r,cache:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"GET",headers:e,signal:r,cache:n})).json()}async getBlob({headers:e,signal:r,...n}){const i=this.createUrl(n);return(await El(i,{method:"GET",headers:e,signal:r})).blob()}async post({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"POST",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"PUT",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:r,signal:n,...i}){const s=this.createUrl(i);return(await El(s,{method:"DELETE",headers:r,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:r}){const n=new URL(e,this.baseUrl);return r&&Object.entries(r).forEach(([i,s])=>{s&&n.searchParams.append(i,s)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}}const xF={getFeatureValue(t,e){const r=e?.[t];return r===void 0?Me.DEFAULT_FEATURES[t]:r},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(Y.isTelegram()){if(Y.isIos())return t.filter(e=>e!=="google");if(Y.isMac())return t.filter(e=>e!=="x");if(Y.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},pe=Ye({features:Me.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Me.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),W={state:pe,subscribeKey(t,e){return St(pe,t,e)},setOptions(t){Object.assign(pe,t)},setRemoteFeatures(t){if(!t)return;const e={...pe.remoteFeatures,...t};pe.remoteFeatures=e,pe.remoteFeatures?.socials&&(pe.remoteFeatures.socials=xF.filterSocialsByPlatform(pe.remoteFeatures.socials))},setFeatures(t){if(!t)return;pe.features||(pe.features=Me.DEFAULT_FEATURES);const e={...pe.features,...t};pe.features=e},setProjectId(t){pe.projectId=t},setCustomRpcUrls(t){pe.customRpcUrls=t},setAllWallets(t){pe.allWallets=t},setIncludeWalletIds(t){pe.includeWalletIds=t},setExcludeWalletIds(t){pe.excludeWalletIds=t},setFeaturedWalletIds(t){pe.featuredWalletIds=t},setTokens(t){pe.tokens=t},setTermsConditionsUrl(t){pe.termsConditionsUrl=t},setPrivacyPolicyUrl(t){pe.privacyPolicyUrl=t},setCustomWallets(t){pe.customWallets=t},setIsSiweEnabled(t){pe.isSiweEnabled=t},setIsUniversalProvider(t){pe.isUniversalProvider=t},setSdkVersion(t){pe.sdkVersion=t},setMetadata(t){pe.metadata=t},setDisableAppend(t){pe.disableAppend=t},setEIP6963Enabled(t){pe.enableEIP6963=t},setDebug(t){pe.debug=t},setEnableWalletConnect(t){pe.enableWalletConnect=t},setEnableWalletGuide(t){pe.enableWalletGuide=t},setEnableAuthLogger(t){pe.enableAuthLogger=t},setEnableWallets(t){pe.enableWallets=t},setPreferUniversalLinks(t){pe.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){pe.hasMultipleAddresses=t},setSIWX(t){pe.siwx=t},setConnectMethodsOrder(t){pe.features={...pe.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){pe.features={...pe.features,walletFeaturesOrder:t}},setSocialsOrder(t){pe.remoteFeatures={...pe.remoteFeatures,socials:t}},setCollapseWallets(t){pe.features={...pe.features,collapseWallets:t}},setEnableEmbedded(t){pe.enableEmbedded=t},setAllowUnsupportedChain(t){pe.allowUnsupportedChain=t},setManualWCControl(t){pe.manualWCControl=t},setEnableNetworkSwitch(t){pe.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,r])=>{r&&(pe.defaultAccountTypes[e]=r)})},setUniversalProviderConfigOverride(t){pe.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return pe.universalProviderConfigOverride},getSnapshot(){return Cl(pe)}},_F=Object.freeze({enabled:!0,events:[]}),AF=new xl({baseUrl:Y.getAnalyticsUrl(),clientId:null}),SF=5,IF=60*1e3,ns=Ye({..._F}),TF={state:ns,subscribeKey(t,e){return St(ns,t,e)},async sendError(t,e){if(!ns.enabled)return;const r=Date.now();if(ns.events.filter(s=>{const o=new Date(s.properties.timestamp||"").getTime();return r-o<IF}).length>=SF)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};ns.events.push(i);try{if(typeof window>"u")return;const{projectId:s,sdkType:o,sdkVersion:a}=W.state;await AF.post({path:"/e",params:{projectId:s,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:Y.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){ns.enabled=!0},disable(){ns.enabled=!1},clearEvents(){ns.events=[]}};class fa extends Error{constructor(e,r,n){super(e),this.name="AppKitError",this.category=r,this.originalError=n,Object.setPrototypeOf(this,fa.prototype);let i=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const s=n.stack,o=s.indexOf(`
|
|
47
47
|
`);if(o>-1){const a=s.substring(o+1);this.stack=`${this.name}: ${this.message}
|
|
48
48
|
${a}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,fa):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Y5(t,e){const r=t instanceof fa?t:new fa(t instanceof Error?t.message:String(t),e,t);throw TF.sendError(r,r.category),r}function nr(t,e="INTERNAL_SDK_ERROR"){const r={};return Object.keys(t).forEach(n=>{const i=t[n];if(typeof i=="function"){let s=i;i.constructor.name==="AsyncFunction"?s=async(...o)=>{try{return await i(...o)}catch(a){return Y5(a,e)}}:s=(...o)=>{try{return i(...o)}catch(a){return Y5(a,e)}},r[n]=s}else r[n]=i}),r}const jn={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},NF={handleMobileDeeplinkRedirect(t,e){const r=window.location.href,n=encodeURIComponent(r);if(t===jn.PHANTOM.id&&!("phantom"in window)){const i=r.startsWith("https")?"https":"http",s=r.split("/")[2],o=encodeURIComponent(`${i}://${s}`);window.location.href=`${jn.PHANTOM.url}/ul/browse/${n}?ref=${o}`}t===jn.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${jn.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===oe.CHAIN.SOLANA&&t===jn.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${jn.COINBASE.url}/dapp?cb_url=${n}`)}},Br=Ye({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),br=nr({state:Br,subscribeNetworkImages(t){return At(Br.networkImages,()=>t(Br.networkImages))},subscribeKey(t,e){return St(Br,t,e)},subscribe(t){return At(Br,()=>t(Br))},setWalletImage(t,e){Br.walletImages[t]=e},setNetworkImage(t,e){Br.networkImages[t]=e},setChainImage(t,e){Br.chainImages[t]=e},setConnectorImage(t,e){Br.connectorImages={...Br.connectorImages,[t]:e}},setTokenImage(t,e){Br.tokenImages[t]=e},setCurrencyImage(t,e){Br.currencyImages[t]=e}}),$F={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},k1=Ye({networkImagePromises:{}}),wt={async fetchWalletImage(t){if(t)return await Q._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(k1.networkImagePromises[t]||(k1.networkImagePromises[t]=Q._fetchNetworkImage(t)),await k1.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return br.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return br.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return br.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return br.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.imageId)return br.state.connectorImages[t.imageId]},getChainImage(t){return br.state.networkImages[$F[t]]}},is=Ye({message:"",variant:"info",open:!1}),tn=nr({state:is,subscribeKey(t,e){return St(is,t,e)},open(t,e){const{debug:r}=W.state,{shortMessage:n,longMessage:i}=t;r&&(is.message=n,is.variant=e,is.open=!0),i&&console.error(typeof i=="function"?i():i)},close(){is.open=!1,is.message="",is.variant="info"}}),OF=Y.getAnalyticsUrl(),kF=new xl({baseUrl:OF,clientId:null}),PF=["MODAL_CREATED"],fi=Ye({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Te={state:fi,subscribe(t){return At(fi,()=>t(fi))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:r}=W.state;return{projectId:t,st:e,sv:r||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=ae.state.address;if(PF.includes(t.data.event)||typeof window>"u")return;await kF.post({path:"/e",params:Te.getSdkProperties(),body:{eventId:Y.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),fi.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===oe.HTTP_STATUS_CODES.FORBIDDEN&&!fi.reportedErrors.FORBIDDEN&&(tn.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${yl()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),fi.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){fi.timestamp=Date.now(),fi.data=t,W.state.features?.analytics&&Te._sendAnalyticsEvent(fi)}},DF=Y.getApiUrl(),yr=new xl({baseUrl:DF,clientId:null}),BF=40,J5=4,RF=20,Ae=Ye({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),Q={state:Ae,subscribeKey(t,e){return St(Ae,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:r}=W.state;return{projectId:t,st:e||"appkit",sv:r||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return W.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${yr.baseUrl}/getWalletImage/${t}`,r=await yr.getBlob({path:e,params:Q._getSdkProperties()});br.setWalletImage(t,URL.createObjectURL(r))},async _fetchNetworkImage(t){const e=`${yr.baseUrl}/public/getAssetImage/${t}`,r=await yr.getBlob({path:e,params:Q._getSdkProperties()});br.setNetworkImage(t,URL.createObjectURL(r))},async _fetchConnectorImage(t){const e=`${yr.baseUrl}/public/getAssetImage/${t}`,r=await yr.getBlob({path:e,params:Q._getSdkProperties()});br.setConnectorImage(t,URL.createObjectURL(r))},async _fetchCurrencyImage(t){const e=`${yr.baseUrl}/public/getCurrencyImage/${t}`,r=await yr.getBlob({path:e,params:Q._getSdkProperties()});br.setCurrencyImage(t,URL.createObjectURL(r))},async _fetchTokenImage(t){const e=`${yr.baseUrl}/public/getTokenImage/${t}`,r=await yr.getBlob({path:e,params:Q._getSdkProperties()});br.setTokenImage(t,URL.createObjectURL(r))},_filterWalletsByPlatform(t){return Y.isMobile()?t?.filter(r=>r.mobile_link||r.id===jn.COINBASE.id?!0:I.state.activeChain==="solana"&&(r.id===jn.SOLFLARE.id||r.id===jn.PHANTOM.id)):t},async fetchProjectConfig(){return(await yr.get({path:"/appkit/v1/config",params:Q._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await yr.get({path:"/projects/v1/origins",params:Q._getSdkProperties()});return t}catch{return[]}},async fetchNetworkImages(){const e=I.getAllRequestedCaipNetworks()?.map(({assets:r})=>r?.imageId).filter(Boolean).filter(r=>!wt.getNetworkImageById(r));e&&await Promise.allSettled(e.map(r=>Q._fetchNetworkImage(r)))},async fetchConnectorImages(){const{connectors:t}=V.state,e=t.map(({imageId:r})=>r).filter(Boolean);await Promise.allSettled(e.map(r=>Q._fetchConnectorImage(r)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>Q._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>Q._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];Q._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(jn).map(s=>s.id));const n=await yr.get({path:"/getWallets",params:{...Q._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}});return{data:Q._filterWalletsByPlatform(n?.data)||[],count:n?.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=W.state;if(t?.length){const e={...Q._getSdkProperties(),page:1,entries:t?.length??J5,include:t},{data:r}=await Q.fetchWallets(e),n=[...r].sort((s,o)=>t.indexOf(s.id)-t.indexOf(o.id)),i=n.map(s=>s.image_id).filter(Boolean);await Promise.allSettled(i.map(s=>Q._fetchWalletImage(s))),Ae.featured=n,Ae.allFeatured=n}},async fetchRecommendedWallets(){try{Ae.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:r}=W.state,n=[...e??[],...r??[]].filter(Boolean),i=I.getRequestedCaipNetworkIds().join(","),s={page:1,entries:J5,include:t,exclude:n,chains:i},{data:o,count:a}=await Q.fetchWallets(s),c=le.getRecentWallets(),l=o.map(d=>d.image_id).filter(Boolean),u=c.map(d=>d.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(d=>Q._fetchWalletImage(d))),Ae.recommended=o,Ae.allRecommended=o,Ae.count=a??0}catch{}finally{Ae.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:r,featuredWalletIds:n}=W.state,i=I.getRequestedCaipNetworkIds().join(","),s=[...Ae.recommended.map(({id:u})=>u),...r??[],...n??[]].filter(Boolean),o={page:t,entries:BF,include:e,exclude:s,chains:i},{data:a,count:c}=await Q.fetchWallets(o),l=a.slice(0,RF).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>Q._fetchWalletImage(u))),Ae.wallets=Y.uniqueBy([...Ae.wallets,...Q._filterOutExtensions(a)],"id").filter(u=>u.chains?.some(d=>i.includes(d))),Ae.count=c>Ae.count?c:Ae.count,Ae.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:r}=await Q.fetchWallets(e);r&&r.forEach(n=>{Ae.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:r,excludeWalletIds:n}=W.state,i=I.getRequestedCaipNetworkIds().join(",");Ae.search=[];const s={page:1,entries:100,search:t?.trim(),badge_type:e,include:r,exclude:n,chains:i},{data:o}=await Q.fetchWallets(s);Te.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>Q._fetchWalletImage(c)),Y.wait(300)]),Ae.search=Q._filterOutExtensions(o)},initPromise(t,e){const r=Ae.promises[t];return r||(Ae.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:r=!0,fetchNetworkImages:n=!0}={}){const i=[t&&Q.initPromise("connectorImages",Q.fetchConnectorImages),e&&Q.initPromise("featuredWallets",Q.fetchFeaturedWallets),r&&Q.initPromise("recommendedWallets",Q.fetchRecommendedWallets),n&&Q.initPromise("networkImages",Q.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){W.state.features?.analytics&&Q.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await yr.get({path:"/getAnalyticsConfig",params:Q._getSdkProperties()});W.setFeatures({analytics:t})}catch{W.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){Ae.featured=Ae.allFeatured,Ae.recommended=Ae.allRecommended;return}const e=I.getRequestedCaipNetworkIds().join(",");Ae.featured=Ae.allFeatured.filter(r=>r.chains?.some(n=>e.includes(n))),Ae.recommended=Ae.allRecommended.filter(r=>r.chains?.some(n=>e.includes(n))),Ae.filteredWallets=Ae.wallets.filter(r=>r.chains?.some(n=>e.includes(n)))},clearFilterByNamespaces(){Ae.filteredWallets=[]},setFilterByNamespace(t){if(!t){Ae.featured=Ae.allFeatured,Ae.recommended=Ae.allRecommended;return}const e=I.getRequestedCaipNetworkIds().join(",");Ae.featured=Ae.allFeatured.filter(r=>r.chains?.some(n=>e.includes(n))),Ae.recommended=Ae.allRecommended.filter(r=>r.chains?.some(n=>e.includes(n))),Ae.filteredWallets=Ae.wallets.filter(r=>r.chains?.some(n=>e.includes(n)))}},Je=Ye({view:"Connect",history:["Connect"],transactionStack:[]}),Z=nr({state:Je,subscribeKey(t,e){return St(Je,t,e)},pushTransactionStack(t){Je.transactionStack.push(t)},popTransactionStack(t){const e=Je.transactionStack.pop();if(!e)return;const{onSuccess:r,onError:n,onCancel:i}=e;switch(t){case"success":r?.();break;case"error":n?.(),Z.goBack();break;case"cancel":i?.(),Z.goBack();break}},push(t,e){t!==Je.view&&(Je.view=t,Je.history.push(t),Je.data=e)},reset(t,e){Je.view=t,Je.history=[t],Je.data=e},replace(t,e){Je.history.at(-1)===t||(Je.view=t,Je.history[Je.history.length-1]=t,Je.data=e)},goBack(){const t=I.state.activeCaipAddress,e=Z.state.view==="ConnectingFarcaster",r=!t&&e;if(Je.history.length>1){Je.history.pop();const[n]=Je.history.slice(-1);n&&(t&&n==="Connect"?Je.view="Account":Je.view=n)}else We.close();Je.data?.wallet&&(Je.data.wallet=void 0),setTimeout(()=>{if(r){ae.setFarcasterUrl(void 0,I.state.activeChain);const n=V.getAuthConnector();n?.provider?.reload();const i=Cl(W.state);n?.provider?.syncDappData?.({metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType})}},100)},goBackToIndex(t){if(Je.history.length>1){Je.history=Je.history.slice(0,t+1);const[e]=Je.history.slice(-1);e&&(Je.view=e)}},goBackOrCloseModal(){Z.state.history.length>1?Z.goBack():We.close()}}),pi=Ye({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),P1={state:pi,subscribe(t){return At(pi,()=>t(pi))},setThemeMode(t){pi.themeMode=t;try{const e=V.getAuthConnector();if(e){const r=P1.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:r,w3mThemeVariables:ts(r,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){pi.themeVariables={...pi.themeVariables,...t};try{const e=V.getAuthConnector();if(e){const r=P1.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:r,w3mThemeVariables:ts(pi.themeVariables,pi.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Cl(pi)}},Lt=nr(P1),X5={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},Le=Ye({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...X5},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),V=nr({state:Le,subscribe(t){return At(Le,()=>{t(Le)})},subscribeKey(t,e){return St(Le,t,e)},initialize(t){t.forEach(e=>{const r=le.getConnectedConnectorId(e);r&&V.setConnectorId(r,e)})},setActiveConnector(t){t&&(Le.activeConnector=Qs(t))},setConnectors(t){t.filter(i=>!Le.allConnectors.some(s=>s.id===i.id&&V.getConnectorName(s.name)===V.getConnectorName(i.name)&&s.chain===i.chain)).forEach(i=>{i.type!=="MULTI_CHAIN"&&Le.allConnectors.push(Qs(i))});const r=V.getEnabledNamespaces(),n=V.getEnabledConnectors(r);Le.connectors=V.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(Le.filterByNamespaceMap).forEach(e=>{Le.filterByNamespaceMap[e]=!1}),t.forEach(e=>{Le.filterByNamespaceMap[e]=!0}),V.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){Le.filterByNamespaceMap[t]=e,V.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=V.getEnabledNamespaces(),e=V.getEnabledConnectors(t),r=V.areAllNamespacesEnabled();Le.connectors=V.mergeMultiChainConnectors(e),r?Q.clearFilterByNamespaces():Q.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(Le.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return Le.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(Le.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=V.generateConnectorMapByName(t),r=[];return e.forEach(n=>{const i=n[0],s=i?.id===oe.CONNECTOR_ID.AUTH;n.length>1&&i?r.push({name:i.name,imageUrl:i.imageUrl,imageId:i.imageId,connectors:[...n],type:s?"AUTH":"MULTI_CHAIN",chain:"eip155",id:i?.id||""}):i&&r.push(i)}),r},generateConnectorMapByName(t){const e=new Map;return t.forEach(r=>{const{name:n}=r,i=V.getConnectorName(n);if(!i)return;const s=e.get(i)||[];s.find(a=>a.chain===r.chain)||s.push(r),e.set(i,s)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(r=>{e.find(n=>n.chain===r.chain)||e.push(r)}),e},addConnector(t){if(t.id===oe.CONNECTOR_ID.AUTH){const e=t,r=Cl(W.state),n=Lt.getSnapshot().themeMode,i=Lt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType}),e?.provider?.syncTheme({themeMode:n,themeVariables:i,w3mThemeVariables:ts(i,n)}),V.setConnectors([t])}else V.setConnectors([t])},getAuthConnector(t){const e=t||I.state.activeChain,r=Le.connectors.find(n=>n.id===oe.CONNECTOR_ID.AUTH);if(r)return r?.connectors?.length?r.connectors.find(i=>i.chain===e):r},getAnnouncedConnectorRdns(){return Le.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return Le.allConnectors.find(e=>e.id===t)},getConnector(t,e){return Le.allConnectors.filter(n=>n.chain===I.state.activeChain).find(n=>n.explorerId===t||n.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,r=Cl(W.state),n=Lt.getSnapshot().themeMode,i=Lt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,sdkType:r.sdkType,projectId:r.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:i,w3mThemeVariables:ts(i,n)})},getConnectorsByNamespace(t){const e=Le.allConnectors.filter(r=>r.chain===t);return V.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=V.getConnector(t.id,t.rdns),r=I.state.activeChain;NF.handleMobileDeeplinkRedirect(e?.explorerId||t.id,r),e?Z.push("ConnectingExternal",{connector:e}):Z.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?V.getConnectorsByNamespace(t):V.mergeMultiChainConnectors(Le.allConnectors)},setFilterByNamespace(t){Le.filterByNamespace=t,Le.connectors=V.getConnectors(t),Q.setFilterByNamespace(t)},setConnectorId(t,e){t&&(Le.activeConnectorIds={...Le.activeConnectorIds,[e]:t},le.setConnectedConnectorId(e,t))},removeConnectorId(t){Le.activeConnectorIds={...Le.activeConnectorIds,[t]:void 0},le.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return Le.activeConnectorIds[t]},isConnected(t){return t?!!Le.activeConnectorIds[t]:Object.values(Le.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Le.activeConnectorIds={...X5}}}),UF="https://secure.walletconnect.org/sdk";typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const ss={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},eo=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),mt=Ye({...eo}),ke={state:mt,subscribeKey(t,e){return St(mt,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=Y.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){mt.message=eo.message,mt.variant=eo.variant,mt.svg=eo.svg,mt.open=eo.open,mt.autoClose=eo.autoClose},_showMessage({message:t,svg:e,variant:r="success",autoClose:n=eo.autoClose}){mt.open?(mt.open=!1,setTimeout(()=>{mt.message=t,mt.variant=r,mt.svg=e,mt.open=!0,mt.autoClose=n},150)):(mt.message=t,mt.variant=r,mt.svg=e,mt.open=!0,mt.autoClose=n)}},rt=Ye({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),_l=nr({state:rt,subscribe(t){return At(rt,()=>t(rt))},setLastNetworkInView(t){rt.lastNetworkInView=t},async fetchTransactions(t,e){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");rt.loading=!0;try{const r=await de.fetchTransactions({account:t,cursor:rt.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:I.state.activeCaipNetwork?.caipNetworkId}),n=_l.filterSpamTransactions(r.data),i=_l.filterByConnectedChain(n),s=[...rt.transactions,...i];rt.loading=!1,e==="coinbase"?rt.coinbaseTransactions=_l.groupTransactionsByYearAndMonth(rt.coinbaseTransactions,r.data):(rt.transactions=s,rt.transactionsByYear=_l.groupTransactionsByYearAndMonth(rt.transactionsByYear,i)),rt.empty=s.length===0,rt.next=r.next?r.next:void 0}catch{const n=I.state.activeChain;Te.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:W.state.projectId,cursor:rt.next,isSmartAccount:ae.state.preferredAccountTypes?.[n]===ss.ACCOUNT_TYPES.SMART_ACCOUNT}}),ke.showError("Failed to fetch transactions"),rt.loading=!1,rt.empty=!0,rt.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const r=t;return e.forEach(n=>{const i=new Date(n.metadata.minedAt).getFullYear(),s=new Date(n.metadata.minedAt).getMonth(),o=r[i]??{},c=(o[s]??[]).filter(l=>l.id!==n.id);r[i]={...o,[s]:[...c,n].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),r},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=I.state.activeCaipNetwork?.caipNetworkId;return t.filter(n=>n.metadata.chain===e)},clearCursor(){rt.next=void 0},resetTransactions(){rt.transactions=[],rt.transactionsByYear={},rt.lastNetworkInView=void 0,rt.loading=!1,rt.empty=!1,rt.next=void 0}},"API_ERROR"),st=Ye({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let to;const X=nr({state:st,subscribeKey(t,e){return St(st,t,e)},_getClient(){return st._client},setClient(t){st._client=Qs(t)},async connectWalletConnect(){if(Y.isTelegram()||Y.isSafari()&&Y.isIos()){if(to){await to,to=void 0;return}if(!Y.isPairingExpired(st?.wcPairingExpiry)){const t=st.wcUri;st.wcUri=t;return}to=X._getClient()?.connectWalletConnect?.().catch(()=>{}),X.state.status="connecting",await to,to=void 0,st.wcPairingExpiry=void 0,X.state.status="connected"}else await X._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,r=!0){await X._getClient()?.connectExternal?.(t),r&&I.setActiveNamespace(e)},async reconnectExternal(t){await X._getClient()?.reconnectExternal?.(t);const e=t.chain||I.state.activeChain;e&&V.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){We.setLoading(!0,I.state.activeChain);const r=V.getAuthConnector();r&&(ae.setPreferredAccountType(t,e),await r.provider.setPreferredAccount(t),le.setPreferredAccountTypes(ae.state.preferredAccountTypes??{[e]:t}),await X.reconnectExternal(r),We.setLoading(!1,I.state.activeChain),Te.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:I.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return X._getClient()?.signMessage(t)},parseUnits(t,e){return X._getClient()?.parseUnits(t,e)},formatUnits(t,e){return X._getClient()?.formatUnits(t,e)},async sendTransaction(t){return X._getClient()?.sendTransaction(t)},async getCapabilities(t){return X._getClient()?.getCapabilities(t)},async grantPermissions(t){return X._getClient()?.grantPermissions(t)},async walletGetAssets(t){return X._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return X._getClient()?.estimateGas(t)},async writeContract(t){return X._getClient()?.writeContract(t)},async getEnsAddress(t){return X._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return X._getClient()?.getEnsAvatar(t)},checkInstalled(t){return X._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){st.wcUri=void 0,st.wcPairingExpiry=void 0,st.wcLinking=void 0,st.recentWallet=void 0,st.status="disconnected",_l.resetTransactions(),le.deleteWalletConnectDeepLink()},resetUri(){st.wcUri=void 0,st.wcPairingExpiry=void 0,to=void 0},finalizeWcConnection(){const{wcLinking:t,recentWallet:e}=X.state;t&&le.setWalletConnectDeepLink(t),e&&le.setAppKitRecent(e),Te.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:Z.state.data?.wallet?.name||"Unknown"}})},setWcBasic(t){st.wcBasic=t},setUri(t){st.wcUri=t,st.wcPairingExpiry=Y.getPairingExpiry()},setWcLinking(t){st.wcLinking=t},setWcError(t){st.wcError=t,st.buffering=!1},setRecentWallet(t){st.recentWallet=t},setBuffering(t){st.buffering=t},setStatus(t){st.status=t},async disconnect(t){try{await X._getClient()?.disconnect(t)}catch(e){throw new fa("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},setConnections(t,e){st.connections.set(e,t)},switchAccount({connection:t,address:e,namespace:r}){if(V.state.activeConnectorIds[r]===t.connectorId){const s=I.state.activeCaipNetwork;if(s){const o=`${r}:${s.id}:${e}`;ae.setCaipAddress(o,r)}else console.warn(`No current network found for namespace "${r}"`)}else{const s=V.getConnector(t.connectorId);s?X.connectExternal(s,r):console.warn(`No connector found for namespace "${r}"`)}}}),pa=Ye({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),os={state:pa,subscribe(t){return At(pa,()=>t(pa))},subscribeOpen(t){return St(pa,"open",t)},set(t){Object.assign(pa,{...pa,...t})}},D1={createBalance(t,e){const r={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:r.name,symbol:r.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:r.value,price:r.price,quantity:{decimals:r.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:r.decimals})},iconUrl:r.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return Fw(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const r=e[1],n=parseInt(r,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(r=>this.isValidAsset(r)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}},eh={async getMyTokensWithBalance(t){const e=ae.state.address,r=I.state.activeCaipNetwork;if(!e||!r)return[];if(r.chainNamespace==="eip155"){const i=await this.getEIP155Balances(e,r);if(i)return this.filterLowQualityTokens(i)}const n=await de.getBalance(e,r.caipNetworkId,t);return this.filterLowQualityTokens(n.balances)},async getEIP155Balances(t,e){try{const r=D1.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await X.getCapabilities(t))?.[r]?.assetDiscovery?.supported)return null;const i=await X.walletGetAssets({account:t,chainFilter:[r]});return D1.isWalletGetAssetsResponse(i)?(i[r]||[]).map(o=>D1.createBalance(o,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:I.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},Ke=Ye({tokenBalances:[],loading:!1}),Fe=nr({state:Ke,subscribe(t){return At(Ke,()=>t(Ke))},subscribeKey(t,e){return St(Ke,t,e)},setToken(t){t&&(Ke.token=Qs(t))},setTokenAmount(t){Ke.sendTokenAmount=t},setReceiverAddress(t){Ke.receiverAddress=t},setReceiverProfileImageUrl(t){Ke.receiverProfileImageUrl=t},setReceiverProfileName(t){Ke.receiverProfileName=t},setNetworkBalanceInUsd(t){Ke.networkBalanceInUSD=t},setLoading(t){Ke.loading=t},async sendToken(){try{switch(Fe.setLoading(!0),I.state.activeCaipNetwork?.chainNamespace){case"eip155":await Fe.sendEvmToken();return;case"solana":await Fe.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{Fe.setLoading(!1)}},async sendEvmToken(){const t=I.state.activeChain,e=ae.state.preferredAccountTypes?.[t];if(!Fe.state.sendTokenAmount||!Fe.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!Fe.state.token)throw new Error("A token is required");Fe.state.token?.address?(Te.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===ss.ACCOUNT_TYPES.SMART_ACCOUNT,token:Fe.state.token.address,amount:Fe.state.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),await Fe.sendERC20Token({receiverAddress:Fe.state.receiverAddress,tokenAddress:Fe.state.token.address,sendTokenAmount:Fe.state.sendTokenAmount,decimals:Fe.state.token.quantity.decimals})):(Te.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===ss.ACCOUNT_TYPES.SMART_ACCOUNT,token:Fe.state.token.symbol||"",amount:Fe.state.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),await Fe.sendNativeToken({receiverAddress:Fe.state.receiverAddress,sendTokenAmount:Fe.state.sendTokenAmount,decimals:Fe.state.token.quantity.decimals}))},async fetchTokenBalance(t){Ke.loading=!0;const e=I.state.activeCaipNetwork?.caipNetworkId,r=I.state.activeCaipNetwork?.chainNamespace,n=I.state.activeCaipAddress,i=n?Y.getPlainAddress(n):void 0;if(Ke.lastRetry&&!Y.isAllowedRetry(Ke.lastRetry,30*Me.ONE_SEC_MS))return Ke.loading=!1,[];try{if(i&&e&&r){const s=await eh.getMyTokensWithBalance();return Ke.tokenBalances=s,Ke.lastRetry=void 0,s}}catch(s){Ke.lastRetry=Date.now(),t?.(s),ke.showError("Token Balance Unavailable")}finally{Ke.loading=!1}return[]},fetchNetworkBalance(){if(Ke.tokenBalances.length===0)return;const t=eh.mapBalancesToSwapTokens(Ke.tokenBalances);if(!t)return;const e=t.find(r=>r.address===I.getActiveNetworkTokenAddress());e&&(Ke.networkBalanceInUSD=e?tt.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){Z.pushTransactionStack({});const e=t.receiverAddress,r=ae.state.address,n=X.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));await X.sendTransaction({chainNamespace:"eip155",to:e,address:r,data:"0x",value:n??BigInt(0)}),Te.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:ae.state.preferredAccountTypes?.eip155===ss.ACCOUNT_TYPES.SMART_ACCOUNT,token:Fe.state.token?.symbol||"",amount:t.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),X._getClient()?.updateBalance("eip155"),Fe.resetSend()},async sendERC20Token(t){Z.pushTransactionStack({onSuccess(){Z.replace("Account")}});const e=X.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(ae.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const r=Y.getPlainAddress(t.tokenAddress);await X.writeContract({fromAddress:ae.state.address,tokenAddress:r,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:gF.getERC20Abi(r),chainNamespace:"eip155"}),Fe.resetSend()}},async sendSolanaToken(){if(!Fe.state.sendTokenAmount||!Fe.state.receiverAddress)throw new Error("An amount and receiver address are required");Z.pushTransactionStack({onSuccess(){Z.replace("Account")}}),await X.sendTransaction({chainNamespace:"solana",to:Fe.state.receiverAddress,value:Fe.state.sendTokenAmount}),X._getClient()?.updateBalance("solana"),Fe.resetSend()},resetSend(){Ke.token=void 0,Ke.sendTokenAmount=void 0,Ke.receiverAddress=void 0,Ke.receiverProfileImageUrl=void 0,Ke.receiverProfileName=void 0,Ke.loading=!1,Ke.tokenBalances=[]}}),B1={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},th={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},ie=Ye({chains:CF(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),I=nr({state:ie,subscribe(t){return At(ie,()=>{t(ie)})},subscribeKey(t,e){return St(ie,t,e)},subscribeChainProp(t,e,r){let n;return At(ie.chains,()=>{const i=r||ie.activeChain;if(i){const s=ie.chains.get(i)?.[t];n!==s&&(n=s,e(s))}})},initialize(t,e,r){const{chainId:n,namespace:i}=le.getActiveNetworkProps(),s=e?.find(u=>u.id.toString()===n?.toString()),a=t.find(u=>u?.namespace===i)||t?.[0],c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=W.state.enableEmbedded?new Set([...c]):new Set([...e?.map(u=>u.chainNamespace)??[]]);(t?.length===0||!a)&&(ie.noAdapters=!0),ie.noAdapters||(ie.activeChain=a?.namespace,ie.activeCaipNetwork=s,I.setChainNetworkData(a?.namespace,{caipNetwork:s}),ie.activeChain&&os.set({activeChain:a?.namespace})),l.forEach(u=>{const d=e?.filter(h=>h.chainNamespace===u);I.state.chains.set(u,{namespace:u,networkState:Ye({...th,caipNetwork:d?.[0]}),accountState:Ye(B1),caipNetworks:d??[],...r}),I.setRequestedCaipNetworks(d??[],u)})},removeAdapter(t){if(ie.activeChain===t){const e=Array.from(ie.chains.entries()).find(([r])=>r!==t);if(e){const r=e[1]?.caipNetworks?.[0];r&&I.setActiveCaipNetwork(r)}}ie.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:r},n){ie.chains.set(t.namespace,{namespace:t.namespace,networkState:{...th,caipNetwork:n[0]},accountState:B1,caipNetworks:n,connectionControllerClient:r,networkControllerClient:e}),I.setRequestedCaipNetworks(n?.filter(i=>i.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=ie.chains.get(t.chainNamespace);if(e){const r=[...e.caipNetworks||[]];e.caipNetworks?.find(n=>n.id===t.id)||r.push(t),ie.chains.set(t.chainNamespace,{...e,caipNetworks:r}),I.setRequestedCaipNetworks(r,t.chainNamespace),V.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const r=ie.chains.get(t);if(r){const n=ie.activeCaipNetwork?.id===e,i=[...r.caipNetworks?.filter(s=>s.id!==e)||[]];n&&r?.caipNetworks?.[0]&&I.setActiveCaipNetwork(r.caipNetworks[0]),ie.chains.set(t,{...r,caipNetworks:i}),I.setRequestedCaipNetworks(i||[],t),i.length===0&&V.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const r=ie.chains.get(t);r&&(r.networkState={...r.networkState||th,...e},ie.chains.set(t,r))},setChainAccountData(t,e,r=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=ie.chains.get(t);if(n){const i={...n.accountState||B1,...e};ie.chains.set(t,{...n,accountState:i}),(ie.chains.size===1||ie.activeChain===t)&&(e.caipAddress&&(ie.activeCaipAddress=e.caipAddress),ae.replaceState(i))}},setChainNetworkData(t,e){if(!t)return;const r=ie.chains.get(t);if(r){const n={...r.networkState||th,...e};ie.chains.set(t,{...r,networkState:n})}},setAccountProp(t,e,r,n=!0){I.setChainAccountData(r,{[t]:e},n),t==="status"&&e==="disconnected"&&r&&V.removeConnectorId(r)},setActiveNamespace(t){ie.activeChain=t;const e=t?ie.chains.get(t):void 0,r=e?.networkState?.caipNetwork;r?.id&&t&&(ie.activeCaipAddress=e?.accountState?.caipAddress,ie.activeCaipNetwork=r,I.setChainNetworkData(t,{caipNetwork:r}),le.setActiveCaipNetworkId(r?.caipNetworkId),os.set({activeChain:t,selectedNetworkId:r?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;ie.activeChain!==t.chainNamespace&&I.setIsSwitchingNamespace(!0);const e=ie.chains.get(t.chainNamespace);ie.activeChain=t.chainNamespace,ie.activeCaipNetwork=t,I.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),e?.accountState?.address?ie.activeCaipAddress=`${t.chainNamespace}:${t.id}:${e?.accountState?.address}`:ie.activeCaipAddress=void 0,I.setAccountProp("caipAddress",ie.activeCaipAddress,t.chainNamespace),e&&ae.replaceState(e.accountState),Fe.resetSend(),os.set({activeChain:ie.activeChain,selectedNetworkId:ie.activeCaipNetwork?.caipNetworkId}),le.setActiveCaipNetworkId(t.caipNetworkId),!I.checkIfSupportedNetwork(t.chainNamespace)&&W.state.enableNetworkSwitch&&!W.state.allowUnsupportedChain&&!X.state.wcBasic&&I.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=ie.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==I.state.activeChain,r=I.getNetworkData(t)?.caipNetwork,n=I.getCaipNetworkByNamespace(t,r?.id);e&&n&&await I.switchActiveNetwork(n)},async switchActiveNetwork(t){const r=!I.state.chains.get(I.state.activeChain)?.caipNetworks?.some(i=>i.id===ie.activeCaipNetwork?.id),n=I.getNetworkControllerClient(t.chainNamespace);if(n){try{await n.switchCaipNetwork(t),r&&We.close()}catch{Z.goBack()}Te.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||ie.activeChain,r=ie.chains.get(e);if(!r)throw new Error("Chain adapter not found");if(!r.networkControllerClient)throw new Error("NetworkController client not set");return r.networkControllerClient},getConnectionControllerClient(t){const e=t||ie.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const r=ie.chains.get(e);if(!r?.connectionControllerClient)throw new Error("ConnectionController client not set");return r.connectionControllerClient},getAccountProp(t,e){let r=ie.activeChain;if(e&&(r=e),!r)return;const n=ie.chains.get(r)?.accountState;if(n)return n[t]},getNetworkProp(t,e){const r=ie.chains.get(e)?.networkState;if(r)return r[t]},getRequestedCaipNetworks(t){const e=ie.chains.get(t),{approvedCaipNetworkIds:r=[],requestedCaipNetworks:n=[]}=e?.networkState||{};return Y.sortRequestedNetworks(r,n)},getAllRequestedCaipNetworks(){const t=[];return ie.chains.forEach(e=>{const r=I.getRequestedCaipNetworks(e.namespace);t.push(...r)}),t},setRequestedCaipNetworks(t,e){I.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=I.getAllRequestedCaipNetworks().map(s=>s.chainNamespace),i=Array.from(new Set(n));V.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const t=[];return ie.chains.forEach(e=>{const r=I.getApprovedCaipNetworkIds(e.namespace);t.push(...r)}),t},getActiveCaipNetwork(){return ie.activeCaipNetwork},getActiveCaipAddress(){return ie.activeCaipAddress},getApprovedCaipNetworkIds(t){return ie.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(t){const r=await I.getNetworkControllerClient()?.getApprovedCaipNetworksData();I.setAdapterNetworkState(t,{approvedCaipNetworkIds:r?.approvedCaipNetworkIds,supportsAllNetworks:r?.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const r=e||ie.activeCaipNetwork,n=I.getRequestedCaipNetworks(t);return n.length?n?.some(i=>i.id===r?.id):!0},checkIfSupportedChainId(t){return ie.activeChain?I.getRequestedCaipNetworks(ie.activeChain)?.some(r=>r.id===t):!0},setSmartAccountEnabledNetworks(t,e){I.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){const t=W5.caipNetworkIdToNumber(ie.activeCaipNetwork?.caipNetworkId),e=ie.activeChain;return!e||!t?!1:!!I.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(t))},getActiveNetworkTokenAddress(){const t=ie.activeCaipNetwork?.chainNamespace||"eip155",e=ie.activeCaipNetwork?.id||1,r=Me.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${r}`},showUnsupportedChainUI(){We.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=ie.activeCaipNetwork;return!!(t?.chainNamespace&&Me.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){I.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");ie.activeCaipAddress=void 0,I.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),V.removeConnectorId(e)},setIsSwitchingNamespace(t){ie.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){const t=[];let e;if(ie.chains.forEach(r=>{oe.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&t.push(r.namespace)}),t.length>0){const r=t[0];return e=r?ie.chains.get(r)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){return t?I.state.chains.get(t)?.accountState:ae.state},getNetworkData(t){const e=t||ie.activeChain;if(e)return I.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const r=I.state.chains.get(t),n=r?.caipNetworks?.find(i=>i.id===e);return n||r?.networkState?.caipNetwork||r?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=V.state.filterByNamespace;return(t?[ie.chains.get(t)]:Array.from(ie.chains.values())).flatMap(r=>r?.caipNetworks||[]).map(r=>r.caipNetworkId)},getCaipNetworks(t){return t?I.getRequestedCaipNetworks(t):I.getAllRequestedCaipNetworks()}}),LF={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Q5=Y.getBlockchainApiUrl(),vr=Ye({clientId:null,api:new xl({baseUrl:Q5,clientId:null}),supportedChains:{http:[],ws:[]}}),de={state:vr,async get(t){const{st:e,sv:r}=de.getSdkProperties(),n=W.state.projectId,i={...t.params||{},st:e,sv:r,projectId:n};return vr.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=W.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{vr.supportedChains.http.length||await de.getSupportedNetworks()}catch{return!1}return vr.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await de.get({path:"v1/supported-chains"});return vr.supportedChains=t,t}catch{return vr.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await de.isNetworkSupported(e))return{avatar:"",name:""};const n=le.getIdentityFromCacheForAddress(t);if(n)return n;const i=await de.get({path:`/v1/identity/${t}`,params:{sender:I.state.activeCaipAddress?Y.getPlainAddress(I.state.activeCaipAddress):void 0}});return le.updateIdentityCache({address:t,identity:i,timestamp:Date.now()}),i},async fetchTransactions({account:t,cursor:e,onramp:r,signal:n,cache:i,chainId:s}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:`/v1/account/${t}/history`,params:{cursor:e,onramp:r,chainId:s},signal:n,cache:i}):{data:[],next:void 0}},async fetchSwapQuote({amount:t,userAddress:e,from:r,to:n,gasPrice:i}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:r,to:n,gasPrice:i}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?vr.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:W.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:r}=de.getSdkProperties();if(!await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return de.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:r}})},async generateSwapCalldata({amount:t,from:e,to:r,userAddress:n,disableEstimate:i}){if(!await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return vr.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:Me.CONVERT_SLIPPAGE_TOLERANCE},projectId:W.state.projectId,from:e,to:r,userAddress:n,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:r}){const{st:n,sv:i}=de.getSdkProperties();if(!await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return de.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:r,from:t,to:e,st:n,sv:i}})},async getBalance(t,e,r){const{st:n,sv:i}=de.getSdkProperties();if(!await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))return ke.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=le.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await de.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:r,st:n,sv:i}});return le.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:`/v1/profile/reverse/${t}`,params:{sender:ae.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:r,signature:n}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?vr.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:r,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:r,purchaseAmount:n,paymentAmount:i}){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?(await vr.api.post({path:"/v1/generators/onrampurl",params:{projectId:W.state.projectId},body:{destinationWallets:t,defaultNetwork:r,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:i}})).url:""},async getOnrampOptions(){if(!await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await de.get({path:"/v1/onramp/options"})}catch{return LF}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:r,network:n}){try{return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?await vr.api.post({path:"/v1/onramp/quote",params:{projectId:W.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:r,network:n}}):null}catch{return{coinbaseFee:{amount:r,currency:e.id},networkFee:{amount:r,currency:e.id},paymentSubtotal:{amount:r,currency:e.id},paymentTotal:{amount:r,currency:e.id},purchaseAmount:{amount:r,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?de.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,r){return await de.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?vr.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:W.state.projectId},body:{pci:e,signature:r}}):{success:!1}},setClientId(t){vr.clientId=t,vr.api=new xl({baseUrl:Q5,clientId:t})}},rn=Ye({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),ae=nr({state:rn,replaceState(t){t&&Object.assign(rn,Qs(t))},subscribe(t){return I.subscribeChainProp("accountState",e=>{if(e)return t(e)})},subscribeKey(t,e,r){let n;return I.subscribeChainProp("accountState",i=>{if(i){const s=i[t];n!==s&&(n=s,e(s))}},r)},setStatus(t,e){I.setAccountProp("status",t,e)},getCaipAddress(t){return I.getAccountProp("caipAddress",t)},setCaipAddress(t,e){const r=t?Y.getPlainAddress(t):void 0;e===I.state.activeChain&&(I.state.activeCaipAddress=t),I.setAccountProp("caipAddress",t,e),I.setAccountProp("address",r,e)},setBalance(t,e,r){I.setAccountProp("balance",t,r),I.setAccountProp("balanceSymbol",e,r)},setProfileName(t,e){I.setAccountProp("profileName",t,e)},setProfileImage(t,e){I.setAccountProp("profileImage",t,e)},setUser(t,e){I.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){I.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){I.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){I.setAccountProp("currentTab",t,I.state.activeChain)},setTokenBalance(t,e){t&&I.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){I.setAccountProp("shouldUpdateToAddress",t,e)},setAllAccounts(t,e){I.setAccountProp("allAccounts",t,e)},addAddressLabel(t,e,r){const n=I.getAccountProp("addressLabels",r)||new Map;n.set(t,e),I.setAccountProp("addressLabels",n,r)},removeAddressLabel(t,e){const r=I.getAccountProp("addressLabels",e)||new Map;r.delete(t),I.setAccountProp("addressLabels",r,e)},setConnectedWalletInfo(t,e){I.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){I.setAccountProp("preferredAccountTypes",{...rn.preferredAccountTypes,[e]:t},e)},setPreferredAccountTypes(t){rn.preferredAccountTypes=t},setSocialProvider(t,e){t&&I.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){I.setAccountProp("socialWindow",t?Qs(t):void 0,e)},setFarcasterUrl(t,e){I.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){rn.balanceLoading=!0;const e=I.state.activeCaipNetwork?.caipNetworkId,r=I.state.activeCaipNetwork?.chainNamespace,n=I.state.activeCaipAddress,i=n?Y.getPlainAddress(n):void 0;if(rn.lastRetry&&!Y.isAllowedRetry(rn.lastRetry,30*Me.ONE_SEC_MS))return rn.balanceLoading=!1,[];try{if(i&&e&&r){const o=(await de.getBalance(i,e)).balances.filter(a=>a.quantity.decimals!=="0");return ae.setTokenBalance(o,r),rn.lastRetry=void 0,rn.balanceLoading=!1,o}}catch(s){rn.lastRetry=Date.now(),t?.(s),ke.showError("Token Balance Unavailable")}finally{rn.balanceLoading=!1}return[]},resetAccount(t){I.resetAccount(t)}}),MF={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const r=I.state.activeCaipNetwork,n=Z.state.data;if(t.id===r?.id)return;const s=ae.getCaipAddress(I.state.activeChain),o=t.chainNamespace!==I.state.activeChain,a=ae.getCaipAddress(t.chainNamespace),l=V.getConnectorId(I.state.activeChain)===oe.CONNECTOR_ID.AUTH,u=oe.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(d=>d===t.chainNamespace);e||l&&u?Z.push("SwitchNetwork",{...n,network:t}):s&&o&&!a?Z.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):Z.push("SwitchNetwork",{...n,network:t})}},Cr=Ye({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),We=nr({state:Cr,subscribe(t){return At(Cr,()=>t(Cr))},subscribeKey(t,e){return St(Cr,t,e)},async open(t){const e=ae.state.status==="connected",r=t?.namespace,n=I.state.activeChain,i=r&&r!==n,s=I.getAccountData(t?.namespace)?.caipAddress;if(X.state.wcBasic?Q.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await Q.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),V.setFilterByNamespace(t?.namespace),We.setLoading(!0,r),r&&i){const o=I.getNetworkData(r)?.caipNetwork||I.getRequestedCaipNetworks(r)[0];o&&MF.onSwitchNetwork({network:o,ignoreSwitchConfirmation:!0})}else{const o=I.state.noAdapters;W.state.manualWCControl||o&&!s?Y.isMobile()?Z.reset("AllWallets"):Z.reset("ConnectingWalletConnectBasic"):t?.view?Z.reset(t.view,t.data):s?Z.reset("Account"):Z.reset("Connect")}Cr.open=!0,os.set({open:!0}),Te.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!s}})},close(){const t=W.state.enableEmbedded,e=!!I.state.activeCaipAddress;Cr.open&&Te.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Cr.open=!1,Z.reset("Connect"),We.clearLoading(),t?e?Z.replace("Account"):Z.push("Connect"):os.set({open:!1}),X.resetUri()},setLoading(t,e){e&&Cr.loadingNamespaceMap.set(e,t),Cr.loading=t,os.set({loading:t})},clearLoading(){Cr.loadingNamespaceMap.clear(),Cr.loading=!1},shake(){Cr.shake||(Cr.shake=!0,setTimeout(()=>{Cr.shake=!1},500))}}),Al={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},R1={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},Pe=Ye({providers:Z5,selectedProvider:null,error:null,purchaseCurrency:Al,paymentCurrency:R1,purchaseCurrencies:[Al],paymentCurrencies:[],quotesLoading:!1}),U1=nr({state:Pe,subscribe(t){return At(Pe,()=>t(Pe))},subscribeKey(t,e){return St(Pe,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=I.state.activeChain===oe.CHAIN.SOLANA?"SOL":"USDC",r=ae.state.address??"",n=new URL(t.url);n.searchParams.append("publicKey",EF),n.searchParams.append("destinationCurrencyCode",e),n.searchParams.append("walletAddress",r),n.searchParams.append("externalCustomerId",W.state.projectId),Pe.selectedProvider={...t,url:n.toString()}}else Pe.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,r=Z5.filter(n=>e.includes(n.name));Pe.providers=r}else Pe.providers=[]},setPurchaseCurrency(t){Pe.purchaseCurrency=t},setPaymentCurrency(t){Pe.paymentCurrency=t},setPurchaseAmount(t){U1.state.purchaseAmount=t},setPaymentAmount(t){U1.state.paymentAmount=t},async getAvailableCurrencies(){const t=await de.getOnrampOptions();Pe.purchaseCurrencies=t.purchaseCurrencies,Pe.paymentCurrencies=t.paymentCurrencies,Pe.paymentCurrency=t.paymentCurrencies[0]||R1,Pe.purchaseCurrency=t.purchaseCurrencies[0]||Al,await Q.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await Q.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){Pe.quotesLoading=!0;try{const t=await de.getOnrampQuote({purchaseCurrency:Pe.purchaseCurrency,paymentCurrency:Pe.paymentCurrency,amount:Pe.paymentAmount?.toString()||"0",network:Pe.purchaseCurrency?.symbol});return Pe.quotesLoading=!1,Pe.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return Pe.error=t.message,Pe.quotesLoading=!1,null}finally{Pe.quotesLoading=!1}},resetState(){Pe.selectedProvider=null,Pe.error=null,Pe.purchaseCurrency=Al,Pe.paymentCurrency=R1,Pe.purchaseCurrencies=[Al],Pe.paymentCurrencies=[],Pe.paymentAmount=void 0,Pe.purchaseAmount=void 0,Pe.quotesLoading=!1}}),L1={async getTokenList(){const t=I.state.activeCaipNetwork;return(await de.fetchSwapTokens({chainId:t?.caipNetworkId}))?.tokens?.map(n=>({...n,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){const t=I.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const e=(await X?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:e,fast:e,instant:e};case"eip155":default:return await de.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:r,sourceTokenDecimals:n}){const i=await de.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(i?.allowance&&r&&n){const s=X.parseUnits(r,n)||0;return BigInt(i.allowance)>=s}return!1},async getMyTokensWithBalance(t){const e=ae.state.address,r=I.state.activeCaipNetwork;if(!e||!r)return[];const i=(await de.getBalance(e,r.caipNetworkId,t)).balances.filter(s=>s.quantity.decimals!=="0");return ae.setTokenBalance(i,I.state.activeChain),this.mapBalancesToSwapTokens(i)},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:I.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},as={getGasPriceInEther(t,e){const r=e*t;return Number(r)/1e18},getGasPriceInUSD(t,e,r){const n=as.getGasPriceInEther(e,r);return tt.bigNumber(t).times(n).toNumber()},getPriceImpact({sourceTokenAmount:t,sourceTokenPriceInUSD:e,toTokenPriceInUSD:r,toTokenAmount:n}){const i=tt.bigNumber(t).times(e),s=tt.bigNumber(n).times(r);return i.minus(s).div(i).times(100).toNumber()},getMaxSlippage(t,e){const r=tt.bigNumber(t).div(100);return tt.multiply(e,r).toNumber()},getProviderFee(t,e=.0085){return tt.bigNumber(t).times(e).toString()},isInsufficientNetworkTokenForGas(t,e){const r=e||"0";return tt.bigNumber(t).eq(0)?!0:tt.bigNumber(tt.bigNumber(r)).gt(t)},isInsufficientSourceTokenForSwap(t,e,r){const n=r?.find(s=>s.address===e)?.quantity?.numeric;return tt.bigNumber(n||"0").lt(t)},getToTokenAmount({sourceToken:t,toToken:e,sourceTokenPrice:r,toTokenPrice:n,sourceTokenAmount:i}){if(i==="0"||!t||!e)return"0";const s=t.decimals,o=r,a=e.decimals,c=n;if(c<=0)return"0";const l=tt.bigNumber(i).times(.0085),d=tt.bigNumber(i).minus(l).times(tt.bigNumber(10).pow(s)),h=tt.bigNumber(o).div(c),f=s-a;return d.times(h).div(tt.bigNumber(10).pow(f)).div(tt.bigNumber(10).pow(a)).toFixed(a).toString()}},e4=15e4,FF=6,ir={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:Me.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},F=Ye(ir),rh={state:F,subscribe(t){return At(F,()=>t(F))},subscribeKey(t,e){return St(F,t,e)},getParams(){const t=I.state.activeCaipAddress,e=I.state.activeChain,r=Y.getPlainAddress(t),n=I.getActiveNetworkTokenAddress(),i=V.getConnectorId(e);if(!r)throw new Error("No address found to swap the tokens from.");const s=!F.toToken?.address||!F.toToken?.decimals,o=!F.sourceToken?.address||!F.sourceToken?.decimals||!tt.bigNumber(F.sourceTokenAmount).gt(0),a=!F.sourceTokenAmount;return{networkAddress:n,fromAddress:r,fromCaipAddress:t,sourceTokenAddress:F.sourceToken?.address,toTokenAddress:F.toToken?.address,toTokenAmount:F.toTokenAmount,toTokenDecimals:F.toToken?.decimals,sourceTokenAmount:F.sourceTokenAmount,sourceTokenDecimals:F.sourceToken?.decimals,invalidToToken:s,invalidSourceToken:o,invalidSourceTokenAmount:a,availableToSwap:t&&!s&&!o&&!a,isAuthConnector:i===oe.CONNECTOR_ID.AUTH}},setSourceToken(t){if(!t){F.sourceToken=t,F.sourceTokenAmount="",F.sourceTokenPriceInUSD=0;return}F.sourceToken=t,ye.setTokenPrice(t.address,"sourceToken")},setSourceTokenAmount(t){F.sourceTokenAmount=t},setToToken(t){if(!t){F.toToken=t,F.toTokenAmount="",F.toTokenPriceInUSD=0;return}F.toToken=t,ye.setTokenPrice(t.address,"toToken")},setToTokenAmount(t){F.toTokenAmount=t?tt.formatNumberToLocalString(t,FF):""},async setTokenPrice(t,e){let r=F.tokensPriceMap[t]||0;r||(F.loadingPrices=!0,r=await ye.getAddressPrice(t)),e==="sourceToken"?F.sourceTokenPriceInUSD=r:e==="toToken"&&(F.toTokenPriceInUSD=r),F.loadingPrices&&(F.loadingPrices=!1),ye.getParams().availableToSwap&&ye.swapTokens()},switchTokens(){if(F.initializing||!F.initialized)return;const t=F.toToken?{...F.toToken}:void 0,e=F.sourceToken?{...F.sourceToken}:void 0,r=t&&F.toTokenAmount===""?"1":F.toTokenAmount;ye.setSourceToken(t),ye.setToToken(e),ye.setSourceTokenAmount(r),ye.setToTokenAmount(""),ye.swapTokens()},resetState(){F.myTokensWithBalance=ir.myTokensWithBalance,F.tokensPriceMap=ir.tokensPriceMap,F.initialized=ir.initialized,F.sourceToken=ir.sourceToken,F.sourceTokenAmount=ir.sourceTokenAmount,F.sourceTokenPriceInUSD=ir.sourceTokenPriceInUSD,F.toToken=ir.toToken,F.toTokenAmount=ir.toTokenAmount,F.toTokenPriceInUSD=ir.toTokenPriceInUSD,F.networkPrice=ir.networkPrice,F.networkTokenSymbol=ir.networkTokenSymbol,F.networkBalanceInUSD=ir.networkBalanceInUSD,F.inputError=ir.inputError,F.myTokensWithBalance=ir.myTokensWithBalance},resetValues(){const{networkAddress:t}=ye.getParams(),e=F.tokens?.find(r=>r.address===t);ye.setSourceToken(e),ye.setToToken(void 0)},getApprovalLoadingState(){return F.loadingApprovalTransaction},clearError(){F.transactionError=void 0},async initializeState(){if(!F.initializing){if(F.initializing=!0,!F.initialized)try{await ye.fetchTokens(),F.initialized=!0}catch{F.initialized=!1,ke.showError("Failed to initialize swap"),Z.goBack()}F.initializing=!1}},async fetchTokens(){const{networkAddress:t}=ye.getParams();await ye.getTokenList(),await ye.getNetworkTokenPrice(),await ye.getMyTokensWithBalance();const e=F.tokens?.find(r=>r.address===t);e&&(F.networkTokenSymbol=e.symbol,ye.setSourceToken(e),ye.setSourceTokenAmount("1"))},async getTokenList(){const t=await L1.getTokenList();F.tokens=t,F.popularTokens=t.sort((e,r)=>e.symbol<r.symbol?-1:e.symbol>r.symbol?1:0),F.suggestedTokens=t.filter(e=>!!Me.SWAP_SUGGESTED_TOKENS.includes(e.symbol),{})},async getAddressPrice(t){const e=F.tokensPriceMap[t];if(e)return e;const n=(await de.fetchTokenPrice({addresses:[t]}))?.fungibles||[],s=[...F.tokens||[],...F.myTokensWithBalance||[]]?.find(c=>c.address===t)?.symbol,o=n.find(c=>c.symbol.toLowerCase()===s?.toLowerCase())?.price||0,a=parseFloat(o.toString());return F.tokensPriceMap[t]=a,a},async getNetworkTokenPrice(){const{networkAddress:t}=ye.getParams(),r=(await de.fetchTokenPrice({addresses:[t]}).catch(()=>(ke.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],n=r?.price.toString()||"0";F.tokensPriceMap[t]=parseFloat(n),F.networkTokenSymbol=r?.symbol||"",F.networkPrice=n},async getMyTokensWithBalance(t){const e=await eh.getMyTokensWithBalance(t),r=eh.mapBalancesToSwapTokens(e);r&&(await ye.getInitialGasPrice(),ye.setBalances(r))},setBalances(t){const{networkAddress:e}=ye.getParams(),r=I.state.activeCaipNetwork;if(!r)return;const n=t.find(i=>i.address===e);t.forEach(i=>{F.tokensPriceMap[i.address]=i.price||0}),F.myTokensWithBalance=t.filter(i=>i.address.startsWith(r.caipNetworkId)),F.networkBalanceInUSD=n?tt.multiply(n.quantity.numeric,n.price).toString():"0"},async getInitialGasPrice(){const t=await L1.fetchGasPrice();if(!t)return{gasPrice:null,gasPriceInUSD:null};switch(I.state?.activeCaipNetwork?.chainNamespace){case"solana":return F.gasFee=t.standard??"0",F.gasPriceInUSD=tt.multiply(t.standard,F.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(F.gasFee),gasPriceInUSD:Number(F.gasPriceInUSD)};case"eip155":default:const e=t.standard??"0",r=BigInt(e),n=BigInt(e4),i=as.getGasPriceInUSD(F.networkPrice,n,r);return F.gasFee=e,F.gasPriceInUSD=i,{gasPrice:r,gasPriceInUSD:i}}},async swapTokens(){const t=ae.state.address,e=F.sourceToken,r=F.toToken,n=tt.bigNumber(F.sourceTokenAmount).gt(0);if(n||ye.setToTokenAmount(""),!r||!e||F.loadingPrices||!n)return;F.loadingQuote=!0;const i=tt.bigNumber(F.sourceTokenAmount).times(10**e.decimals).round(0);try{const s=await de.fetchSwapQuote({userAddress:t,from:e.address,to:r.address,gasPrice:F.gasFee,amount:i.toString()});F.loadingQuote=!1;const o=s?.quotes?.[0]?.toAmount;if(!o){tn.open({shortMessage:"Incorrect amount",longMessage:"Please enter a valid amount"},"error");return}const a=tt.bigNumber(o).div(10**r.decimals).toString();ye.setToTokenAmount(a),ye.hasInsufficientToken(F.sourceTokenAmount,e.address)?F.inputError="Insufficient balance":(F.inputError=void 0,ye.setTransactionDetails())}catch{F.loadingQuote=!1,F.inputError="Insufficient balance"}},async getTransaction(){const{fromCaipAddress:t,availableToSwap:e}=ye.getParams(),r=F.sourceToken,n=F.toToken;if(!(!t||!e||!r||!n||F.loadingQuote))try{F.loadingBuildTransaction=!0;const i=await L1.fetchSwapAllowance({userAddress:t,tokenAddress:r.address,sourceTokenAmount:F.sourceTokenAmount,sourceTokenDecimals:r.decimals});let s;return i?s=await ye.createSwapTransaction():s=await ye.createAllowanceTransaction(),F.loadingBuildTransaction=!1,F.fetchError=!1,s}catch{Z.goBack(),ke.showError("Failed to check allowance"),F.loadingBuildTransaction=!1,F.approvalTransaction=void 0,F.swapTransaction=void 0,F.fetchError=!0;return}},async createAllowanceTransaction(){const{fromCaipAddress:t,sourceTokenAddress:e,toTokenAddress:r}=ye.getParams();if(!(!t||!r)){if(!e)throw new Error("createAllowanceTransaction - No source token address found.");try{const n=await de.generateApproveCalldata({from:e,to:r,userAddress:t}),i={data:n.tx.data,to:Y.getPlainAddress(n.tx.from),gasPrice:BigInt(n.tx.eip155.gasPrice),value:BigInt(n.tx.value),toAmount:F.toTokenAmount};return F.swapTransaction=void 0,F.approvalTransaction={data:i.data,to:i.to,gasPrice:i.gasPrice,value:i.value,toAmount:i.toAmount},{data:i.data,to:i.to,gasPrice:i.gasPrice,value:i.value,toAmount:i.toAmount}}catch{Z.goBack(),ke.showError("Failed to create approval transaction"),F.approvalTransaction=void 0,F.swapTransaction=void 0,F.fetchError=!0;return}}},async createSwapTransaction(){const{networkAddress:t,fromCaipAddress:e,sourceTokenAmount:r}=ye.getParams(),n=F.sourceToken,i=F.toToken;if(!e||!r||!n||!i)return;const s=X.parseUnits(r,n.decimals)?.toString();try{const o=await de.generateSwapCalldata({userAddress:e,from:n.address,to:i.address,amount:s,disableEstimate:!0}),a=n.address===t,c=BigInt(o.tx.eip155.gas),l=BigInt(o.tx.eip155.gasPrice),u={data:o.tx.data,to:Y.getPlainAddress(o.tx.to),gas:c,gasPrice:l,value:BigInt(a?s??"0":"0"),toAmount:F.toTokenAmount};return F.gasPriceInUSD=as.getGasPriceInUSD(F.networkPrice,c,l),F.approvalTransaction=void 0,F.swapTransaction=u,u}catch{Z.goBack(),ke.showError("Failed to create transaction"),F.approvalTransaction=void 0,F.swapTransaction=void 0,F.fetchError=!0;return}},async sendTransactionForApproval(t){const{fromAddress:e,isAuthConnector:r}=ye.getParams();F.loadingApprovalTransaction=!0;const n="Approve limit increase in your wallet";r?Z.pushTransactionStack({onSuccess(){ke.showLoading(n)}}):ke.showLoading(n);try{await X.sendTransaction({address:e,to:t.to,data:t.data,value:t.value,chainNamespace:"eip155"}),await ye.swapTokens(),await ye.getTransaction(),F.approvalTransaction=void 0,F.loadingApprovalTransaction=!1}catch(i){const s=i;F.transactionError=s?.shortMessage,F.loadingApprovalTransaction=!1,ke.showError(s?.shortMessage||"Transaction error"),Te.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.shortMessage||s?.message||"Unknown",network:I.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ye.state.sourceToken?.symbol||"",swapToToken:ye.state.toToken?.symbol||"",swapFromAmount:ye.state.sourceTokenAmount||"",swapToAmount:ye.state.toTokenAmount||"",isSmartAccount:ae.state.preferredAccountTypes?.eip155===ss.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(t){if(!t)return;const{fromAddress:e,toTokenAmount:r,isAuthConnector:n}=ye.getParams();F.loadingTransaction=!0;const i=`Swapping ${F.sourceToken?.symbol} to ${tt.formatNumberToLocalString(r,3)} ${F.toToken?.symbol}`,s=`Swapped ${F.sourceToken?.symbol} to ${tt.formatNumberToLocalString(r,3)} ${F.toToken?.symbol}`;n?Z.pushTransactionStack({onSuccess(){Z.replace("Account"),ke.showLoading(i),rh.resetState()}}):ke.showLoading("Confirm transaction in your wallet");try{const o=[F.sourceToken?.address,F.toToken?.address].join(","),a=await X.sendTransaction({address:e,to:t.to,data:t.data,value:t.value,chainNamespace:"eip155"});return F.loadingTransaction=!1,ke.showSuccess(s),Te.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:I.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ye.state.sourceToken?.symbol||"",swapToToken:ye.state.toToken?.symbol||"",swapFromAmount:ye.state.sourceTokenAmount||"",swapToAmount:ye.state.toTokenAmount||"",isSmartAccount:ae.state.preferredAccountTypes?.eip155===ss.ACCOUNT_TYPES.SMART_ACCOUNT}}),rh.resetState(),n||Z.replace("Account"),rh.getMyTokensWithBalance(o),a}catch(o){const a=o;F.transactionError=a?.shortMessage,F.loadingTransaction=!1,ke.showError(a?.shortMessage||"Transaction error"),Te.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:a?.shortMessage||a?.message||"Unknown",network:I.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ye.state.sourceToken?.symbol||"",swapToToken:ye.state.toToken?.symbol||"",swapFromAmount:ye.state.sourceTokenAmount||"",swapToAmount:ye.state.toTokenAmount||"",isSmartAccount:ae.state.preferredAccountTypes?.eip155===ss.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(t,e){return as.isInsufficientSourceTokenForSwap(t,e,F.myTokensWithBalance)},setTransactionDetails(){const{toTokenAddress:t,toTokenDecimals:e}=ye.getParams();!t||!e||(F.gasPriceInUSD=as.getGasPriceInUSD(F.networkPrice,BigInt(F.gasFee),BigInt(e4)),F.priceImpact=as.getPriceImpact({sourceTokenAmount:F.sourceTokenAmount,sourceTokenPriceInUSD:F.sourceTokenPriceInUSD,toTokenPriceInUSD:F.toTokenPriceInUSD,toTokenAmount:F.toTokenAmount}),F.maxSlippage=as.getMaxSlippage(F.slippage,F.toTokenAmount),F.providerFee=as.getProviderFee(F.sourceTokenAmount))}},ye=nr(rh),yn=Ye({message:"",open:!1,triggerRect:{width:0,height:0,top:0,left:0},variant:"shade"}),ga=nr({state:yn,subscribe(t){return At(yn,()=>t(yn))},subscribeKey(t,e){return St(yn,t,e)},showTooltip({message:t,triggerRect:e,variant:r}){yn.open=!0,yn.message=t,yn.triggerRect=e,yn.variant=r},hide(){yn.open=!1,yn.message="",yn.triggerRect={width:0,height:0,top:0,left:0}}}),t4=2147483648,jF={convertEVMChainIdToCoinType(t){if(t>=t4)throw new Error("Invalid chainId");return(t4|t)>>>0}},nn=Ye({suggestions:[],loading:!1}),Sl=nr({state:nn,subscribe(t){return At(nn,()=>t(nn))},subscribeKey(t,e){return St(nn,t,e)},async resolveName(t){try{return await de.lookupEnsName(t)}catch(e){const r=e;throw new Error(r?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await de.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{nn.loading=!0,nn.suggestions=[];const e=await de.getEnsNameSuggestions(t);return nn.suggestions=e.suggestions.map(r=>({...r,name:r.name}))||[],nn.suggestions}catch(e){const r=Sl.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(r)}finally{nn.loading=!1}},async getNamesForAddress(t){try{if(!I.state.activeCaipNetwork)return[];const r=le.getEnsFromCacheForAddress(t);if(r)return r;const n=await de.reverseLookupEnsName({address:t});return le.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const r=Sl.parseEnsApiError(e,"Error fetching names for address");throw new Error(r)}},async registerName(t){const e=I.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const r=ae.state.address,n=V.getAuthConnector();if(!r||!n)throw new Error("Address or auth connector not found");nn.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});Z.pushTransactionStack({onCancel(){Z.replace("RegisterAccountName")}});const s=await X.signMessage(i);nn.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=jF.convertEVMChainIdToCoinType(Number(o));await de.registerEnsName({coinType:a,address:r,signature:s,message:i}),ae.setProfileName(t,e.chainNamespace),Z.replace("RegisterAccountNameSuccess")}catch(i){const s=Sl.parseEnsApiError(i,`Error registering name ${t}`);throw Z.replace("RegisterAccountName"),new Error(s)}finally{nn.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}});Ye({isLegalCheckboxChecked:!1});const ro={getSIWX(){return W.state.siwx},async initializeIfEnabled(){const t=W.state.siwx,e=I.getActiveCaipAddress();if(!(t&&e))return;const[r,n,i]=e.split(":");if(I.checkIfSupportedNetwork(r))try{if((await t.getSessions(`${r}:${n}`,i)).length)return;await We.open({view:"SIWXSignMessage"})}catch(s){console.error("SIWXUtil:initializeIfEnabled",s),Te.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await X._getClient()?.disconnect().catch(console.error),Z.reset("Connect"),ke.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=W.state.siwx,e=Y.getPlainAddress(I.getActiveCaipAddress()),r=I.getActiveCaipNetwork(),n=X._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!r)throw new Error("No ActiveCaipNetwork or client found");if(!n)throw new Error("No ConnectionController client found");try{const i=await t.createMessage({chainId:r.caipNetworkId,accountAddress:e}),s=i.toString();V.getConnectorId(r.chainNamespace)===oe.CONNECTOR_ID.AUTH&&Z.pushTransactionStack({});const a=await n.signMessage(s);await t.addSession({data:i,message:s,signature:a}),We.close(),Te.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){const s=this.getSIWXEventProperties();(!We.state.open||Z.state.view==="ApproveTransaction")&&await We.open({view:"SIWXSignMessage"}),s.isSmartAccount?ke.showError("This application might not support Smart Accounts"):ke.showError("Signature declined"),Te.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:s}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){try{this.getSIWX()?.getRequired?.()?await X.disconnect():We.close(),Z.reset("Connect"),Te.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getSessions(){const t=W.state.siwx,e=Y.getPlainAddress(I.getActiveCaipAddress()),r=I.getActiveCaipNetwork();return t&&e&&r?t.getSessions(r.caipNetworkId,e):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=Z.state.view==="ApproveTransaction",r=Z.state.view==="SIWXSignMessage";if(e||r)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:r}){const n=ro.getSIWX(),i=new Set(e.map(a=>a.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const s=await n.createMessage({chainId:I.getActiveCaipNetwork()?.caipNetworkId||"",accountAddress:""}),o=await t.authenticate({nonce:s.nonce,domain:s.domain,uri:s.uri,exp:s.expirationTime,iat:s.issuedAt,nbf:s.notBefore,requestId:s.requestId,version:s.version,resources:s.resources,statement:s.statement,chainId:s.chainId,methods:r,chains:[s.chainId,...e.filter(a=>a!==s.chainId)]});if(ke.showLoading("Authenticating...",{autoClose:!1}),ae.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(i)[0]),o?.auths?.length){const a=o.auths.map(c=>{const l=t.client.formatAuthMessage({request:c.p,iss:c.p.iss});return{data:{...c.p,accountAddress:c.p.iss.split(":").slice(-1).join(""),chainId:c.p.iss.split(":").slice(2,4).join(":"),uri:c.p.aud,version:c.p.version||s.version,expirationTime:c.p.exp,issuedAt:c.p.iat,notBefore:c.p.nbf},message:l,signature:c.s.s,cacao:c}});try{await n.setSessions(a),Te.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:ro.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),Te.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:ro.getSIWXEventProperties()}),await t.disconnect().catch(console.error),c}finally{ke.hide()}}return!0},getSIWXEventProperties(){const t=I.state.activeChain;return{network:I.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:ae.state.preferredAccountTypes?.[t]===ss.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}},r4={isUnsupportedChainView(){return Z.state.view==="UnsupportedChain"||Z.state.view==="SwitchNetwork"&&Z.state.history.includes("UnsupportedChain")},async safeClose(){if(this.isUnsupportedChainView()){We.shake();return}if(await ro.isSIWXCloseDisabled()){We.shake();return}We.close()}};function nh(t,e){return V.getConnectorId(t)===e}function zF(t){const e=Array.from(I.state.chains.keys());let r=[];return t?(r.push([t,I.state.chains.get(t)]),nh(t,oe.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(n=>{n!==t&&nh(n,oe.CONNECTOR_ID.WALLET_CONNECT)&&r.push([n,I.state.chains.get(n)])}):nh(t,oe.CONNECTOR_ID.AUTH)&&e.forEach(n=>{n!==t&&nh(n,oe.CONNECTOR_ID.AUTH)&&r.push([n,I.state.chains.get(n)])})):r=Array.from(I.state.chains.entries()),r}const bt={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"},ih={ConnectorExplorerIds:{[oe.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[oe.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[oe.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[oe.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[oe.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[bt.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[bt.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[bt.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[bt.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[bt.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[bt.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[bt.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[bt.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[bt.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[bt.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[bt.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[oe.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[oe.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[oe.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[oe.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[oe.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[oe.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[oe.CONNECTOR_ID.INJECTED]:"Browser Wallet",[oe.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[oe.CONNECTOR_ID.COINBASE]:"Coinbase",[oe.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[oe.CONNECTOR_ID.LEDGER]:"Ledger",[oe.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[oe.CONNECTOR_ID.INJECTED]:"INJECTED",[oe.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[oe.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[oe.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},M1={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([r,n])=>{e[`${bt.EIP155}:${r}`]=n}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===e?.toLowerCase()}},wa={EmbeddedWalletAbortController:new AbortController,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${WF()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function WF(){return typeof window<"u"}const HF={createLogger(t,e="error"){const r=nl({level:e}),{logger:n}=F3({opts:r});return n.error=(...i)=>{for(const s of i)if(s instanceof Error){t(s,...i);return}t(void 0,...i)},n}},qF="rpc.walletconnect.org";function n4(t,e){const r=new URL("https://rpc.walletconnect.org/v1/");return r.searchParams.set("chainId",t),r.searchParams.set("projectId",e),r.toString()}const F1=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],ma={extendRpcUrlWithProjectId(t,e){let r=!1;try{r=new URL(t).host===qF}catch{r=!1}if(r){const n=new URL(t);return n.searchParams.has("projectId")||n.searchParams.set("projectId",e),n.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:oe.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${oe.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,r){const n=t.rpcUrls?.default?.http?.[0];return F1.includes(e)?n4(e,r):n||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:r,customRpcUrls:n}){const i=this.getChainNamespace(t),s=this.getCaipNetworkId(t),o=t.rpcUrls.default.http?.[0],a=this.getDefaultRpcUrl(t,s,r),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=n?.[s]?.map(h=>h.url)||[],u=[...l,a],d=[...l];return c&&!d.includes(c)&&d.push(c),{...t,chainNamespace:i,caipNetworkId:s,assets:{imageId:ih.NetworkImageIds[t.id],imageUrl:e?.[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:d}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:r,customRpcUrls:n}){return t.map(i=>ma.extendCaipNetwork(i,{customNetworkImageUrls:e,customRpcUrls:n,projectId:r}))},getViemTransport(t,e,r){const n=[];return r?.forEach(i=>{n.push($u(i.url,i.config))}),F1.includes(t.caipNetworkId)&&n.push($u(n4(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(i=>{n.push($u(i))}),dm(n)},extendWagmiTransports(t,e,r){if(F1.includes(t.caipNetworkId)){const n=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return dm([r,$u(n)])}return r},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:oe.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=le.getActiveCaipNetworkId(),r=I.getAllRequestedCaipNetworks(),n=Array.from(I.state.chains?.keys()||[]),i=e?.split(":")[0],s=i?n.includes(i):!1,o=r?.find(c=>c.caipNetworkId===e);return s&&!o&&e?this.getUnsupportedNetwork(e):o||t||r?.[0]}},sh={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},Er=Ye({providers:{...sh},providerIds:{...sh}}),ot={state:Er,subscribeKey(t,e){return St(Er,t,e)},subscribe(t){return At(Er,()=>{t(Er)})},subscribeProviders(t){return At(Er.providers,()=>t(Er.providers))},setProvider(t,e){e&&(Er.providers[t]=Qs(e))},getProvider(t){return Er.providers[t]},setProviderId(t,e){e&&(Er.providerIds[t]=e)},getProviderId(t){if(t)return Er.providerIds[t]},reset(){Er.providers={...sh},Er.providerIds={...sh}},resetChain(t){Er.providers[t]=void 0,Er.providerIds[t]=void 0}};var i4;(function(t){t.Google="google",t.Github="github",t.Apple="apple",t.Facebook="facebook",t.X="x",t.Discord="discord",t.Farcaster="farcaster"})(i4||(i4={}));const cs={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},no={filterOutDuplicatesByRDNS(t){const e=W.state.enableEIP6963?V.state.connectors:[],r=le.getRecentWallets(),n=e.map(a=>a.info?.rdns).filter(Boolean),i=r.map(a=>a.rdns).filter(Boolean),s=n.concat(i);if(s.includes("io.metamask.mobile")&&Y.isMobile()){const a=s.indexOf("io.metamask.mobile");s[a]="io.metamask"}return t.filter(a=>!s.includes(String(a?.rdns)))},filterOutDuplicatesByIds(t){const e=V.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),r=le.getRecentWallets(),n=e.map(a=>a.explorerId),i=r.map(a=>a.id),s=n.concat(i);return t.filter(a=>!s.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=V.state,{featuredWalletIds:r}=W.state,n=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!n[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(r?.length){const l=r.indexOf(o.id),u=r.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){const r=t?.connectMethodsOrder||W.state.features?.connectMethodsOrder,n=e||V.state.connectors;if(r)return r;const{injected:i,announced:s}=gi.getConnectorsByType(n,Q.state.recommended,Q.state.featured),o=i.filter(gi.showConnector),a=s.filter(gi.showConnector);return o.length||a.length?["wallet","email","social"]:cs.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&Q.state.excludedWallets.some(n=>n.rdns===t.rdns),r=!!t.name&&Q.state.excludedWallets.some(n=>M1.isLowerCaseMatch(n.name,t.name));return e||r}},gi={getConnectorsByType(t,e,r){const{customWallets:n}=W.state,i=le.getRecentWallets(),s=no.filterOutDuplicateWallets(e),o=no.filterOutDuplicateWallets(r),a=t.filter(d=>d.type==="MULTI_CHAIN"),c=t.filter(d=>d.type==="ANNOUNCED"),l=t.filter(d=>d.type==="INJECTED"),u=t.filter(d=>d.type==="EXTERNAL");return{custom:n,recent:i,external:u,multiChain:a,announced:c,injected:l,recommended:s,featured:o}},showConnector(t){const e=t.info?.rdns,r=!!e&&Q.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),n=!!t.name&&Q.state.excludedWallets.some(i=>M1.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!Y.isMobile()||Y.isMobile()&&!e&&!X.checkInstalled())||r||n)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(r||n))},getIsConnectedWithWC(){return Array.from(I.state.chains.values()).some(r=>V.getConnectorId(r.namespace)===oe.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:r,recent:n,announced:i,injected:s,multiChain:o,external:a,overriddenConnectors:c=W.state.features?.connectorTypeOrder??[]}){const l=gi.getIsConnectedWithWC(),h=[{type:"walletConnect",isEnabled:W.state.enableWalletConnect&&!l},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...s,...i,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:r&&r.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(b=>b.isEnabled),f=new Set(h.map(b=>b.type)),p=c.filter(b=>f.has(b)).map(b=>({type:b,isEnabled:!0})),g=h.filter(({type:b})=>!p.some(({type:x})=>x===b));return Array.from(new Set([...p,...g].map(({type:b})=>b)))}};/**
|
|
49
49
|
* @license
|