@walletconnect/ethereum-provider 2.22.3 → 2.22.4
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 +1 -1
- 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
|
@@ -37,7 +37,7 @@ ${e.length}`,n=new TextEncoder().encode(t+e);return"0x"+Buffer.from(Mce(n)).toSt
|
|
|
37
37
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
38
38
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
39
39
|
PERFORMANCE OF THIS SOFTWARE.
|
|
40
|
-
***************************************************************************** */var x9=function(e,t){return x9=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},x9(e,t)};function the(e,t){x9(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var $9=function(){return $9=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},$9.apply(this,arguments)};function nhe(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}function rhe(e,t,n,r){var s=arguments.length,i=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(i=(s<3?o(i):s>3?o(t,n,i):o(t,n))||i);return s>3&&i&&Object.defineProperty(t,n,i),i}function she(e,t){return function(n,r){t(n,r,e)}}function ihe(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function ohe(e,t,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(f){o(f)}}function c(u){try{l(r.throw(u))}catch(f){o(f)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function ahe(e,t){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,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(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){n.label=l[1];break}if(l[0]===6&&n.label<i[1]){n.label=i[1],i=l;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(l);break}i[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],s=0}finally{r=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function che(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}function lhe(e,t){for(var n in e)n!=="default"&&!t.hasOwnProperty(n)&&(t[n]=e[n])}function A9(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function mR(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),s,i=[],o;try{for(;(t===void 0||t-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function uhe(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(mR(arguments[t]));return e}function dhe(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),s=0,t=0;t<n;t++)for(var i=arguments[t],o=0,a=i.length;o<a;o++,s++)r[s]=i[o];return r}function Dg(e){return this instanceof Dg?(this.v=e,this):new Dg(e)}function fhe(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){r[d]&&(s[d]=function(h){return new Promise(function(p,g){i.push([d,h,p,g])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(i[0][3],p)}}function c(d){d.value instanceof Dg?Promise.resolve(d.value.v).then(l,u):f(i[0][2],d)}function l(d){a("next",d)}function u(d){a("throw",d)}function f(d,h){d(h),i.shift(),i.length&&a(i[0][0],i[0][1])}}function hhe(e){var t,n;return t={},r("next"),r("throw",function(s){throw s}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(s,i){t[s]=e[s]?function(o){return(n=!n)?{value:Dg(e[s](o)),done:s==="return"}:i?i(o):o}:i}}function phe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof A9=="function"?A9(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=e[i]&&function(o){return new Promise(function(a,c){o=e[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function ghe(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function mhe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function yhe(e){return e&&e.__esModule?e:{default:e}}function bhe(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function whe(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}var vhe=Object.freeze({__proto__:null,__extends:the,get __assign(){return $9},__rest:nhe,__decorate:rhe,__param:she,__metadata:ihe,__awaiter:ohe,__generator:ahe,__createBinding:che,__exportStar:lhe,__values:A9,__read:mR,__spread:uhe,__spreadArrays:dhe,__await:Dg,__asyncGenerator:fhe,__asyncDelegator:hhe,__asyncValues:phe,__makeTemplateObject:ghe,__importStar:mhe,__importDefault:yhe,__classPrivateFieldGet:bhe,__classPrivateFieldSet:whe}),Ehe=w_(vhe),ml={},yR;function xhe(){if(yR)return ml;yR=1,Object.defineProperty(ml,"__esModule",{value:!0}),ml.isBrowserCryptoAvailable=ml.getSubtleCrypto=ml.getBrowerCrypto=void 0;function e(){return Tn?.crypto||Tn?.msCrypto||{}}ml.getBrowerCrypto=e;function t(){const r=e();return r.subtle||r.webkitSubtle}ml.getSubtleCrypto=t;function n(){return!!e()&&!!t()}return ml.isBrowserCryptoAvailable=n,ml}var yl={},bR;function $he(){if(bR)return yl;bR=1,Object.defineProperty(yl,"__esModule",{value:!0}),yl.isBrowser=yl.isNode=yl.isReactNative=void 0;function e(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}yl.isReactNative=e;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}yl.isNode=t;function n(){return!e()&&!t()}return yl.isBrowser=n,yl}(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=Ehe;t.__exportStar(xhe(),e),t.__exportStar($he(),e)})(gR);function Dn(e=3){const t=Date.now()*Math.pow(10,e),n=Math.floor(Math.random()*Math.pow(10,e));return t+n}function Wr(e=6){return BigInt(Dn(e))}function rn(e,t,n){return{id:n||Dn(),jsonrpc:"2.0",method:e,params:t}}function ua(e,t){return{id:e,jsonrpc:"2.0",result:t}}function Rh(e,t,n){return{id:e,jsonrpc:"2.0",error:Ahe(t,n)}}function Ahe(e,t){return typeof e>"u"?hR(dR):(typeof e=="string"&&(e=Object.assign(Object.assign({},hR(E9)),{message:e})),typeof t<"u"&&(e.data=t),Qfe(e.code)&&(e=ehe(e.code)),e)}class Che{}class She extends Che{constructor(){super()}}class Ihe extends She{constructor(t){super()}}const _he="^https?:",Ohe="^wss?:";function Phe(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function wR(e,t){const n=Phe(e);return typeof n>"u"?!1:new RegExp(t).test(n)}function vR(e){return wR(e,_he)}function ER(e){return wR(e,Ohe)}function The(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function xR(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function Dh(e){return xR(e)&&"method"in e}function A0(e){return xR(e)&&(wn(e)||Xt(e))}function wn(e){return"result"in e}function Xt(e){return"error"in e}class Mh extends Ihe{constructor(t){super(t),this.events=new Ot.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async request(t,n){return this.requestStrict(rn(t.method,t.params||[],t.id||Wr().toString()),n)}async requestStrict(t,n){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(i){s(i)}this.events.on(`${t.id}`,i=>{Xt(i)?s(i.error):r(i.result)});try{await this.connection.send(t,n)}catch(i){s(i)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),A0(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const Nhe=()=>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"),Bhe=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",$R=e=>e.split("?")[0],AR=10,khe=Nhe();class CR{constructor(t){if(this.url=t,this.events=new Ot.exports.EventEmitter,this.registering=!1,!ER(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ws(t))}catch(n){this.onError(t.id,n)}}register(t=this.url){if(!ER(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const s=gR.isReactNative()?void 0:{rejectUnauthorized:!The(t)},i=new khe(t,[],s);Bhe()?i.onerror=o=>{const a=o;r(this.emitError(a.error))}:i.on("error",o=>{r(this.emitError(o))}),i.onopen=()=>{this.onOpen(i),n(i)}})}onOpen(t){t.onmessage=n=>this.onPayload(n),t.onclose=n=>this.onClose(n),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;const n=typeof t.data=="string"?sl(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),s=r.message||r.toString(),i=Rh(t,s);this.events.emit("payload",i)}parseError(t,n=this.url){return pR(t,$R(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>AR&&this.events.setMaxListeners(AR)}emitError(t){const n=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${$R(this.url)}`));return this.events.emit("register_error",n),n}}var Rhe=Object.defineProperty,SR=Object.getOwnPropertySymbols,Dhe=Object.prototype.hasOwnProperty,Mhe=Object.prototype.propertyIsEnumerable,IR=(e,t,n)=>t in e?Rhe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kr=(e,t)=>{for(var n in t||(t={}))Dhe.call(t,n)&&IR(e,n,t[n]);if(SR)for(var n of SR(t))Mhe.call(t,n)&&IR(e,n,t[n]);return e};const _R="wc",OR=2,c6="core",da=`${_R}@2:${c6}:`,Uhe={name:c6,logger:"error"},Lhe={database:":memory:"},Fhe="crypto",PR="client_ed25519_seed",jhe=Q.ONE_DAY,zhe="keychain",Hhe="0.3",Vhe="messages",qhe="0.3",Zhe=Q.SIX_HOURS,Whe="publisher",TR="irn",Khe="error",NR="wss://relay.walletconnect.org",Ghe="relayer",sn={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"},Yhe="_subscription",Mi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Xhe=.1,C9="2.22.3",Lt={link_mode:"link_mode",relay:"relay"},l6={inbound:"inbound",outbound:"outbound"},Jhe="0.3",Qhe="WALLETCONNECT_CLIENT_ID",BR="WALLETCONNECT_LINK_MODE_APPS",di={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},e1e="subscription",t1e="0.3",n1e="pairing",r1e="0.3",Mg={wc_pairingDelete:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Q.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Q.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:0},res:{ttl:Q.ONE_DAY,prompt:!1,tag:0}}},C0={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xo={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},s1e="history",i1e="0.3",o1e="expirer",Ui={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},a1e="0.3",c1e="verify-api",l1e="https://verify.walletconnect.com",kR="https://verify.walletconnect.org",Ug=kR,u1e=`${Ug}/v3`,d1e=[l1e,kR],f1e="echo",h1e="https://echo.walletconnect.com",fa={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"},bl={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"},$o={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},S0={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},I0={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"},Lg={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"},p1e=.1,g1e="event-client",m1e=86400,y1e="https://pulse.walletconnect.org/batch";function b1e(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(n[o]!==255)throw new TypeError(i+" is ambiguous");n[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(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,y=0,$=0,_=p.length;$!==_&&p[$]===0;)$++,g++;for(var x=(_-$)*u+1>>>0,E=new Uint8Array(x);$!==_;){for(var P=p[$],N=0,k=x-1;(P!==0||N<y)&&k!==-1;k--,N++)P+=256*E[k]>>>0,E[k]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");y=N,$++}for(var R=x-y;R!==x&&E[R]===0;)R++;for(var T=c.repeat(g);R<x;++R)T+=e.charAt(E[R]);return T}function d(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 y=0,$=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,x=new Uint8Array(_);p[g];){var E=n[p.charCodeAt(g)];if(E===255)return;for(var P=0,N=_-1;(E!==0||P<$)&&N!==-1;N--,P++)E+=a*x[N]>>>0,x[N]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");$=P,g++}if(p[g]!==" "){for(var k=_-$;k!==_&&x[k]===0;)k++;for(var R=new Uint8Array(y+(_-k)),T=y;k!==_;)R[T++]=x[k++];return R}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var w1e=b1e,v1e=w1e;const RR=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},E1e=e=>new TextEncoder().encode(e),x1e=e=>new TextDecoder().decode(e);class $1e{constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class A1e{constructor(t,n,r){if(this.name=t,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return DR(this,t)}}class C1e{constructor(t){this.decoders=t}or(t){return DR(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const DR=(e,t)=>new C1e(Kr(Kr({},e.decoders||{[e.prefix]:e}),t.decoders||{[t.prefix]:t}));class S1e{constructor(t,n,r,s){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new $1e(t,n,r),this.decoder=new A1e(t,n,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const u6=({name:e,prefix:t,encode:n,decode:r})=>new S1e(e,t,n,r),Fg=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:s}=v1e(n,t);return u6({prefix:e,name:t,encode:r,decode:i=>RR(s(i))})},I1e=(e,t,n,r)=>{const s={};for(let u=0;u<t.length;++u)s[t[u]]=u;let i=e.length;for(;e[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const f=s[e[u]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},_1e=(e,t,n)=>{const r=t[t.length-1]==="=",s=(1<<n)-1;let i="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,i+=t[s&a>>o];if(o&&(i+=t[s&a<<n-o]),r)for(;i.length*n&7;)i+="=";return i},Xn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>u6({prefix:t,name:e,encode(s){return _1e(s,r,n)},decode(s){return I1e(s,r,n,e)}}),O1e=u6({prefix:"\0",name:"identity",encode:e=>x1e(e),decode:e=>E1e(e)});var P1e=Object.freeze({__proto__:null,identity:O1e});const T1e=Xn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var N1e=Object.freeze({__proto__:null,base2:T1e});const B1e=Xn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var k1e=Object.freeze({__proto__:null,base8:B1e});const R1e=Fg({prefix:"9",name:"base10",alphabet:"0123456789"});var D1e=Object.freeze({__proto__:null,base10:R1e});const M1e=Xn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),U1e=Xn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var L1e=Object.freeze({__proto__:null,base16:M1e,base16upper:U1e});const F1e=Xn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),j1e=Xn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),z1e=Xn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H1e=Xn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V1e=Xn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),q1e=Xn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Z1e=Xn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),W1e=Xn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),K1e=Xn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var G1e=Object.freeze({__proto__:null,base32:F1e,base32upper:j1e,base32pad:z1e,base32padupper:H1e,base32hex:V1e,base32hexupper:q1e,base32hexpad:Z1e,base32hexpadupper:W1e,base32z:K1e});const Y1e=Fg({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),X1e=Fg({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J1e=Object.freeze({__proto__:null,base36:Y1e,base36upper:X1e});const Q1e=Fg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),epe=Fg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tpe=Object.freeze({__proto__:null,base58btc:Q1e,base58flickr:epe});const npe=Xn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rpe=Xn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),spe=Xn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ipe=Xn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ope=Object.freeze({__proto__:null,base64:npe,base64pad:rpe,base64url:spe,base64urlpad:ipe});const MR=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}"),ape=MR.reduce((e,t,n)=>(e[n]=t,e),[]),cpe=MR.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function lpe(e){return e.reduce((t,n)=>(t+=ape[n],t),"")}function upe(e){const t=[];for(const n of e){const r=cpe[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const dpe=u6({prefix:"\u{1F680}",name:"base256emoji",encode:lpe,decode:upe});var fpe=Object.freeze({__proto__:null,base256emoji:dpe}),hpe=LR,UR=128,ppe=127,gpe=~ppe,mpe=Math.pow(2,31);function LR(e,t,n){t=t||[],n=n||0;for(var r=n;e>=mpe;)t[n++]=e&255|UR,e/=128;for(;e&gpe;)t[n++]=e&255|UR,e>>>=7;return t[n]=e|0,LR.bytes=n-r+1,t}var ype=S9,bpe=128,FR=127;function S9(e,r){var n=0,r=r||0,s=0,i=r,o,a=e.length;do{if(i>=a)throw S9.bytes=0,new RangeError("Could not decode varint");o=e[i++],n+=s<28?(o&FR)<<s:(o&FR)*Math.pow(2,s),s+=7}while(o>=bpe);return S9.bytes=i-r,n}var wpe=Math.pow(2,7),vpe=Math.pow(2,14),Epe=Math.pow(2,21),xpe=Math.pow(2,28),$pe=Math.pow(2,35),Ape=Math.pow(2,42),Cpe=Math.pow(2,49),Spe=Math.pow(2,56),Ipe=Math.pow(2,63),_pe=function(e){return e<wpe?1:e<vpe?2:e<Epe?3:e<xpe?4:e<$pe?5:e<Ape?6:e<Cpe?7:e<Spe?8:e<Ipe?9:10},Ope={encode:hpe,decode:ype,encodingLength:_pe},jR=Ope;const zR=(e,t,n=0)=>(jR.encode(e,t,n),t),HR=e=>jR.encodingLength(e),I9=(e,t)=>{const n=t.byteLength,r=HR(e),s=r+HR(n),i=new Uint8Array(s+n);return zR(e,i,0),zR(n,i,r),i.set(t,s),new Ppe(e,n,t,i)};class Ppe{constructor(t,n,r,s){this.code=t,this.size=n,this.digest=r,this.bytes=s}}const VR=({name:e,code:t,encode:n})=>new Tpe(e,t,n);class Tpe{constructor(t,n,r){this.name=t,this.code=n,this.encode=r}digest(t){if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?I9(this.code,n):n.then(r=>I9(this.code,r))}else throw Error("Unknown type, must be binary type")}}const qR=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Npe=VR({name:"sha2-256",code:18,encode:qR("SHA-256")}),Bpe=VR({name:"sha2-512",code:19,encode:qR("SHA-512")});var kpe=Object.freeze({__proto__:null,sha256:Npe,sha512:Bpe});const ZR=0,Rpe="identity",WR=RR;var Dpe=Object.freeze({__proto__:null,identity:{code:ZR,name:Rpe,encode:WR,digest:e=>I9(ZR,WR(e))}});new TextEncoder,new TextDecoder;const KR=Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr({},P1e),N1e),k1e),D1e),L1e),G1e),J1e),tpe),ope),fpe);Kr(Kr({},kpe),Dpe);function GR(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Mpe(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?GR(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function YR(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const XR=YR("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),_9=YR("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=Mpe(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Upe=Kr({utf8:XR,"utf-8":XR,hex:KR.base16,latin1:_9,ascii:_9,binary:_9},KR);function Lpe(e,t="utf8"){const n=Upe[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?GR(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}var Fpe=Object.defineProperty,jpe=(e,t,n)=>t in e?Fpe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ha=(e,t,n)=>jpe(e,typeof t!="symbol"?t+"":t,n);class zpe{constructor(t,n){this.core=t,this.logger=n,ha(this,"keychain",new Map),ha(this,"name",zhe),ha(this,"version",Hhe),ha(this,"initialized",!1),ha(this,"storagePrefix",da),ha(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ha(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ha(this,"set",async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()}),ha(this,"get",r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:i}=pe("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(i)}return s}),ha(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=t,this.logger=ui(n,this.name)}get context(){return li(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,CE(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?SE(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Hpe=Object.defineProperty,Vpe=(e,t,n)=>t in e?Hpe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t,n)=>Vpe(e,typeof t!="symbol"?t+"":t,n);class qpe{constructor(t,n,r){this.core=t,this.logger=n,Mn(this,"name",Fhe),Mn(this,"keychain"),Mn(this,"randomSessionIdentifier",i9()),Mn(this,"initialized",!1),Mn(this,"clientId"),Mn(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Mn(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Mn(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),i=bw(s),o=lE(i.publicKey);return this.clientId=o,o}),Mn(this,"generateKeyPair",()=>{this.isInitialized();const s=que();return this.setPrivateKey(s.publicKey,s.privateKey)}),Mn(this,"signJWT",async s=>{this.isInitialized();const i=await this.getClientSeed(),o=bw(i),a=this.randomSessionIdentifier;return await tN(a,s,jhe,o)}),Mn(this,"generateSharedKey",(s,i,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=Zue(a,i);return this.setSymKey(c,o)}),Mn(this,"setSymKey",async(s,i)=>{this.isInitialized();const o=i||Ww(s);return await this.keychain.set(o,s),o}),Mn(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Mn(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Mn(this,"encode",async(s,i,o)=>{this.isInitialized();const a=Ok(o),c=ws(i);if(Tk(a))return Gue(c,o?.encoding);if(Pk(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;s=await this.generateSharedKey(d,h)}const l=this.getSymKey(s),{type:u,senderPublicKey:f}=a;return Wue({type:u,symKey:l,message:c,senderPublicKey:f,encoding:o?.encoding})}),Mn(this,"decode",async(s,i,o)=>{this.isInitialized();const a=Xue(i,o);if(Tk(a)){const c=Yue(i,o?.encoding);return sl(c)}if(Pk(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=Kue({symKey:c,encoded:i,encoding:o?.encoding});return sl(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Mn(this,"getPayloadType",(s,i=$s)=>{const o=Tg({encoded:s,encoding:i});return E0(o.type)}),Mn(this,"getPayloadSenderPublicKey",(s,i=$s)=>{const o=Tg({encoded:s,encoding:i});return o.senderPublicKey?St(o.senderPublicKey,Zr):void 0}),this.core=t,this.logger=ui(n,this.name),this.keychain=r||new zpe(this.core,this.logger)}get context(){return li(this.logger)}async setPrivateKey(t,n){return await this.keychain.set(t,n),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(PR)}catch{t=i9(),await this.keychain.set(PR,t)}return Lpe(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Zpe=Object.defineProperty,Wpe=Object.defineProperties,Kpe=Object.getOwnPropertyDescriptors,JR=Object.getOwnPropertySymbols,Gpe=Object.prototype.hasOwnProperty,Ype=Object.prototype.propertyIsEnumerable,O9=(e,t,n)=>t in e?Zpe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Xpe=(e,t)=>{for(var n in t||(t={}))Gpe.call(t,n)&&O9(e,n,t[n]);if(JR)for(var n of JR(t))Ype.call(t,n)&&O9(e,n,t[n]);return e},Jpe=(e,t)=>Wpe(e,Kpe(t)),fi=(e,t,n)=>O9(e,typeof t!="symbol"?t+"":t,n);class Qpe extends Rfe{constructor(t,n){super(t,n),this.logger=t,this.core=n,fi(this,"messages",new Map),fi(this,"messagesWithoutClientAck",new Map),fi(this,"name",Vhe),fi(this,"version",qhe),fi(this,"initialized",!1),fi(this,"storagePrefix",da),fi(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),fi(this,"set",async(r,s,i)=>{this.isInitialized();const o=Ri(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),i===l6.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,Jpe(Xpe({},c),{[o]:s}))}return await this.persist(),o}),fi(this,"get",r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s}),fi(this,"getWithoutAck",r=>{this.isInitialized();const s={};for(const i of r){const o=this.messagesWithoutClientAck.get(i)||{};s[i]=Object.values(o)}return s}),fi(this,"has",(r,s)=>{this.isInitialized();const i=this.get(r),o=Ri(s);return typeof i[o]<"u"}),fi(this,"ack",async(r,s)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(r);if(typeof i>"u")return;const o=Ri(s);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,i),await this.persist()}),fi(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=ui(t,this.name),this.core=n}get context(){return li(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(t){await this.core.storage.setItem(this.storageKey,CE(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,CE(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?SE(t):void 0}async getRelayerMessagesWithoutClientAck(){const t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?SE(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var ege=Object.defineProperty,tge=Object.defineProperties,nge=Object.getOwnPropertyDescriptors,QR=Object.getOwnPropertySymbols,rge=Object.prototype.hasOwnProperty,sge=Object.prototype.propertyIsEnumerable,P9=(e,t,n)=>t in e?ege(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Uh=(e,t)=>{for(var n in t||(t={}))rge.call(t,n)&&P9(e,n,t[n]);if(QR)for(var n of QR(t))sge.call(t,n)&&P9(e,n,t[n]);return e},eD=(e,t)=>tge(e,nge(t)),Li=(e,t,n)=>P9(e,typeof t!="symbol"?t+"":t,n);class ige extends Dfe{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Li(this,"events",new Ot.exports.EventEmitter),Li(this,"name",Whe),Li(this,"queue",new Map),Li(this,"publishTimeout",Q.toMiliseconds(Q.ONE_MINUTE)),Li(this,"initialPublishTimeout",Q.toMiliseconds(Q.ONE_SECOND*15)),Li(this,"needsTransportRestart",!1),Li(this,"publish",async(r,s,i)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:i}});const f=i?.ttl||Zhe,d=i?.prompt||!1,h=i?.tag||0,p=i?.id||Wr().toString(),g=Th(Kw().protocol),y={id:p,method:i?.publishMethod||g.publish,params:Uh({topic:r,message:s,ttl:f,prompt:d,tag:h,attestation:i?.attestation},i?.tvf)},$=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{bn((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),bn((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const _=new Promise(async x=>{const E=({id:N})=>{var k;((k=y.id)==null?void 0:k.toString())===N.toString()&&(this.removeRequestFromQueue(N),this.relayer.events.removeListener(sn.publish,E),x())};this.relayer.events.on(sn.publish,E);const P=sa(new Promise((N,k)=>{this.rpcPublish(y,i).then(N).catch(R=>{this.logger.warn(R,R?.message),k(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await P,this.events.removeListener(sn.publish,E)}catch(N){this.queue.set(p,{request:y,opts:i,attempt:1}),this.logger.warn(N,N?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:s,opts:i}}),await sa(_,this.publishTimeout,$)}catch(_){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(_),(u=i?.internal)!=null&&u.throwOnFailedPublish)throw _}finally{this.queue.delete(p)}}),Li(this,"publishCustom",async r=>{var s,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:f,tvf:d,publishMethod:h,prompt:p,tag:g,ttl:y=Q.FIVE_MINUTES}=u,$=u.id||Wr().toString(),_=Th(Kw().protocol),x=h||_.publish,E={id:$,method:x,params:Uh(eD(Uh({},l),{ttl:y,prompt:p,tag:g,attestation:f}),d)},P=`Failed to publish custom payload, please try again. id:${$} tag:${g}`;try{bn((s=E.params)==null?void 0:s.prompt)&&((i=E.params)==null||delete i.prompt),bn((o=E.params)==null?void 0:o.tag)&&((a=E.params)==null||delete a.tag);const N=new Promise(async k=>{const R=({id:L})=>{var M;((M=E.id)==null?void 0:M.toString())===L.toString()&&(this.removeRequestFromQueue(L),this.relayer.events.removeListener(sn.publish,R),k())};this.relayer.events.on(sn.publish,R);const T=sa(new Promise((L,M)=>{this.rpcPublish(E,u).then(L).catch(S=>{this.logger.warn(S,S?.message),M(S)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${x} id:${$} tag:${g}`);try{await T,this.events.removeListener(sn.publish,R)}catch(L){this.queue.set($,{request:E,opts:u,attempt:1}),this.logger.warn(L,L?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:$,payload:l,opts:u}}),await sa(N,this.publishTimeout,P)}catch(N){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(N),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw N}finally{this.queue.delete($)}}),Li(this,"on",(r,s)=>{this.events.on(r,s)}),Li(this,"once",(r,s)=>{this.events.once(r,s)}),Li(this,"off",(r,s)=>{this.events.off(r,s)}),Li(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.relayer=t,this.logger=ui(n,this.name),this.registerEventListeners()}get context(){return li(this.logger)}async rpcPublish(t,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});const r=await this.relayer.request(t);return this.relayer.events.emit(sn.publish,Uh(Uh({},t),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,n)=>{var r;const s=t.attempt+1;this.queue.set(n,eD(Uh({},t),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(r=t.request.params)==null?void 0:r.tag}, attempt: ${s}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(ci.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(sn.connection_stalled);return}this.checkQueue()}),this.relayer.on(sn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}var oge=Object.defineProperty,age=(e,t,n)=>t in e?oge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lh=(e,t,n)=>age(e,typeof t!="symbol"?t+"":t,n);class cge{constructor(){Lh(this,"map",new Map),Lh(this,"set",(t,n)=>{const r=this.get(t);this.exists(t,n)||this.map.set(t,[...r,n])}),Lh(this,"get",t=>this.map.get(t)||[]),Lh(this,"exists",(t,n)=>this.get(t).includes(n)),Lh(this,"delete",(t,n)=>{if(typeof n>"u"){this.map.delete(t);return}if(!this.map.has(t))return;const r=this.get(t);if(!this.exists(t,n))return;const s=r.filter(i=>i!==n);if(!s.length){this.map.delete(t);return}this.map.set(t,s)}),Lh(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var lge=Object.defineProperty,uge=Object.defineProperties,dge=Object.getOwnPropertyDescriptors,tD=Object.getOwnPropertySymbols,fge=Object.prototype.hasOwnProperty,hge=Object.prototype.propertyIsEnumerable,T9=(e,t,n)=>t in e?lge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,jg=(e,t)=>{for(var n in t||(t={}))fge.call(t,n)&&T9(e,n,t[n]);if(tD)for(var n of tD(t))hge.call(t,n)&&T9(e,n,t[n]);return e},N9=(e,t)=>uge(e,dge(t)),Tt=(e,t,n)=>T9(e,typeof t!="symbol"?t+"":t,n);class pge extends Lfe{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Tt(this,"subscriptions",new Map),Tt(this,"topicMap",new cge),Tt(this,"events",new Ot.exports.EventEmitter),Tt(this,"name",e1e),Tt(this,"version",t1e),Tt(this,"pending",new Map),Tt(this,"cached",[]),Tt(this,"initialized",!1),Tt(this,"storagePrefix",da),Tt(this,"subscribeTimeout",Q.toMiliseconds(Q.ONE_MINUTE)),Tt(this,"initialSubscribeTimeout",Q.toMiliseconds(Q.ONE_SECOND*15)),Tt(this,"clientId"),Tt(this,"batchSubscribeTopicsLimit",500),Tt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Tt(this,"subscribe",async(r,s)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const o=Kw(s),a={topic:r,relay:o,transportType:s?.transportType};(i=s?.internal)!=null&&i.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Tt(this,"unsubscribe",async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)}),Tt(this,"isSubscribed",r=>new Promise(s=>{s(this.topicMap.topics.includes(r))})),Tt(this,"isKnownTopic",r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(i=>i.topic===r))})),Tt(this,"on",(r,s)=>{this.events.on(r,s)}),Tt(this,"once",(r,s)=>{this.events.once(r,s)}),Tt(this,"off",(r,s)=>{this.events.off(r,s)}),Tt(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),Tt(this,"start",async()=>{await this.onConnect()}),Tt(this,"stop",async()=>{await this.onDisconnect()}),Tt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Tt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)}),Tt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ci.pulse,async()=>{await this.checkPending()}),this.events.on(di.created,async r=>{const s=di.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(di.deleted,async r=>{const s=di.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})}),this.relayer=t,this.logger=ui(n,this.name),this.clientId=""}get context(){return li(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(t,n){let r=!1;try{r=this.getSubscription(t).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,n){const r=this.topicMap.get(t);await Promise.all(r.map(async s=>await this.unsubscribeById(t,s,n)))}async unsubscribeById(t,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}});try{const s=Kw(r);await this.restartToComplete({topic:t,id:n,relay:s}),await this.rpcUnsubscribe(t,n,s);const i=Ut("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,n,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(t,n,r){var s,i;const o=await this.getSubscriptionId(t);if((s=r?.internal)!=null&&s.skipSubscribe)return o;(!r||r?.transportType===Lt.relay)&&await this.restartToComplete({topic:t,id:t,relay:n});const a={method:Th(n.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=r?.internal)==null?void 0:i.throwOnFailedPublish;try{if(r?.transportType===Lt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},Q.toMiliseconds(Q.ONE_SECOND)),o;const l=new Promise(async f=>{const d=h=>{h.topic===t&&(this.events.removeListener(di.created,d),f(h.id))};this.events.on(di.created,d);try{const h=await sa(new Promise((p,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(di.created,d),f(h)}catch{}}),u=await sa(l,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(sn.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(t){if(!t.length)return;const n=t[0].relay,r={method:Th(n.protocol).batchSubscribe,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await sa(new Promise(s=>{this.relayer.request(r).catch(i=>this.logger.warn(i)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(sn.connection_stalled)}}async rpcBatchFetchMessages(t){if(!t.length)return;const n=t[0].relay,r={method:Th(n.protocol).batchFetchMessages,params:{topics:t.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await sa(new Promise((i,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(sn.connection_stalled)}return s}rpcUnsubscribe(t,n,r){const s={method:Th(r.protocol).unsubscribe,params:{topic:t,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(t,n){this.setSubscription(t,N9(jg({},n),{id:t})),this.pending.delete(n.topic)}onBatchSubscribe(t){t.length&&t.forEach(n=>{this.setSubscription(n.id,jg({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(t,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,t)&&this.deleteSubscription(n,r),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:n}),this.addSubscription(t,n)}addSubscription(t,n){this.subscriptions.set(t,jg({},n)),this.topicMap.set(n.topic,t),this.events.emit(di.created,n)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});const n=this.subscriptions.get(t);if(!n){const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}deleteSubscription(t,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:n});const r=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(r.topic,t),this.events.emit(di.deleted,N9(jg({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(di.sync)}async onRestart(){if(this.cached.length){const t=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const s=t.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(di.resubscribed)}async restore(){try{const t=await this.getRelayerSubscriptions();if(typeof t>"u"||!t.length)return;if(this.subscriptions.size&&!t.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){t.length&&(await this.rpcBatchSubscribe(t),this.onBatchSubscribe(await Promise.all(t.map(async n=>N9(jg({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);const n=await this.rpcBatchFetchMessages(t);n&&n.messages&&(await hce(Q.toMiliseconds(Q.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Ri(t+await this.getClientId())}}var gge=Object.defineProperty,nD=Object.getOwnPropertySymbols,mge=Object.prototype.hasOwnProperty,yge=Object.prototype.propertyIsEnumerable,B9=(e,t,n)=>t in e?gge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,rD=(e,t)=>{for(var n in t||(t={}))mge.call(t,n)&&B9(e,n,t[n]);if(nD)for(var n of nD(t))yge.call(t,n)&&B9(e,n,t[n]);return e},lt=(e,t,n)=>B9(e,typeof t!="symbol"?t+"":t,n);class bge extends Mfe{constructor(t){var n;super(t),lt(this,"protocol","wc"),lt(this,"version",2),lt(this,"core"),lt(this,"logger"),lt(this,"events",new Ot.exports.EventEmitter),lt(this,"provider"),lt(this,"messages"),lt(this,"subscriber"),lt(this,"publisher"),lt(this,"name",Ghe),lt(this,"transportExplicitlyClosed",!1),lt(this,"initialized",!1),lt(this,"connectionAttemptInProgress",!1),lt(this,"relayUrl"),lt(this,"projectId"),lt(this,"packageName"),lt(this,"bundleId"),lt(this,"hasExperiencedNetworkDisruption",!1),lt(this,"pingTimeout"),lt(this,"heartBeatTimeout",Q.toMiliseconds(Q.THIRTY_SECONDS+Q.FIVE_SECONDS)),lt(this,"reconnectTimeout"),lt(this,"connectPromise"),lt(this,"reconnectInProgress",!1),lt(this,"requestsInFlight",[]),lt(this,"connectTimeout",Q.toMiliseconds(Q.ONE_SECOND*15)),lt(this,"request",async r=>{var s,i;this.logger.debug("Publishing Request Payload");const o=r.id||Wr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(s=r.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),lt(this,"resetPingTimeout",()=>{Iw()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,s,i,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(i=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null?void 0:i.terminate)==null||o.call(i)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),lt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),lt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(sn.connect)}),lt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),lt(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(sn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),lt(this,"registerProviderListeners",()=>{this.provider.on(Mi.payload,this.onPayloadHandler),this.provider.on(Mi.connect,this.onConnectHandler),this.provider.on(Mi.disconnect,this.onDisconnectHandler),this.provider.on(Mi.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=d9({logger:(n=t.logger)!=null?n:Khe,name:this.name}),this.messages=new Qpe(this.logger,t.core),this.subscriber=new pge(this,this.logger),this.publisher=new ige(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||NR,Xae()?this.packageName=JN():Jae()&&(this.bundleId=JN()),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(t=>this.logger.warn(t,t?.message))}get context(){return li(this.logger)}get connected(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,n,r){this.isInitialized(),await this.publisher.publish(t,n,r),await this.recordMessageEvent({topic:t,message:n,publishedAt:Date.now(),transportType:Lt.relay},l6.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,n){var r,s,i;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(s=n?.internal)==null?void 0:s.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(t))==null?void 0:i[0])||"",c;const l=u=>{u.topic===t&&(this.subscriber.off(di.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(di.created,l)}),new Promise(async(u,f)=>{a=await this.subscriber.subscribe(t,rD({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||a,u()})]),a}async unsubscribe(t,n){this.isInitialized(),await this.subscriber.unsubscribe(t,n)}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await sa(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(t){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(n,r)=>{await this.connect(t).then(n).catch(r).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(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Zk())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=t.sort((r,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(t,n){const{topic:r}=t;if(!n.sessionExists){const s=cn(Q.FIVE_MINUTES),i={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,i)}this.events.emit(sn.message,t),await this.recordMessageEvent(t,l6.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(Mi.disconnect,i),await sa(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(Mi.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Mi.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Mi.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,Q.toMiliseconds(n*1))),n++}}startPingTimeout(){var t,n,r,s,i;if(Iw())try{(n=(t=this.provider)==null?void 0:t.connection)!=null&&n.socket&&((i=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Mh(new CR(rce({sdkVersion:C9,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,n){const{topic:r,message:s}=t;await this.messages.set(r,s,n)}async shouldIgnoreMessageEvent(t){const{topic:n,message:r}=t;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const s=this.messages.has(n,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Dh(t)){if(!t.method.endsWith(Yhe))return;const n=t.params,{topic:r,message:s,publishedAt:i,attestation:o}=n.data,a={topic:r,message:s,publishedAt:i,transportType:Lt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(rD({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else A0(t)&&this.events.emit(sn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,l6.inbound),this.events.emit(sn.message,t))}async acknowledgePayload(t){const n=ua(t.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(Mi.payload,this.onPayloadHandler),this.provider.off(Mi.connect,this.onConnectHandler),this.provider.off(Mi.disconnect,this.onDisconnectHandler),this.provider.off(Mi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await Zk();Yde(async n=>{t!==n&&(t=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ci.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Qde())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(sn.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(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},Q.toMiliseconds(Xhe)))))}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function wge(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function sD(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function iD(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vge="[object RegExp]",Ege="[object String]",xge="[object Number]",$ge="[object Boolean]",oD="[object Arguments]",Age="[object Symbol]",Cge="[object Date]",Sge="[object Map]",Ige="[object Set]",_ge="[object Array]",Oge="[object Function]",Pge="[object ArrayBuffer]",k9="[object Object]",Tge="[object Error]",Nge="[object DataView]",Bge="[object Uint8Array]",kge="[object Uint8ClampedArray]",Rge="[object Uint16Array]",Dge="[object Uint32Array]",Mge="[object BigUint64Array]",Uge="[object Int8Array]",Lge="[object Int16Array]",Fge="[object Int32Array]",jge="[object BigInt64Array]",zge="[object Float32Array]",Hge="[object Float64Array]";function Vge(){}function aD(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function qge(e,t,n){return zg(e,t,void 0,void 0,void 0,void 0,n)}function zg(e,t,n,r,s,i,o){const a=o(e,t,n,r,s,i);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return Hg(e,t,i,o)}return Hg(e,t,i,o)}function Hg(e,t,n,r){if(Object.is(e,t))return!0;let s=iD(e),i=iD(t);if(s===oD&&(s=k9),i===oD&&(i=k9),s!==i)return!1;switch(s){case Ege:return e.toString()===t.toString();case xge:{const c=e.valueOf(),l=t.valueOf();return wge(c,l)}case $ge:case Cge:case Age:return Object.is(e.valueOf(),t.valueOf());case vge:return e.source===t.source&&e.flags===t.flags;case Oge:return e===t}n=n??new Map;const o=n.get(e),a=n.get(t);if(o!=null&&a!=null)return o===t;n.set(e,t),n.set(t,e);try{switch(s){case Sge:{if(e.size!==t.size)return!1;for(const[c,l]of e.entries())if(!t.has(c)||!zg(l,t.get(c),c,e,t,n,r))return!1;return!0}case Ige:{if(e.size!==t.size)return!1;const c=Array.from(e.values()),l=Array.from(t.values());for(let u=0;u<c.length;u++){const f=c[u],d=l.findIndex(h=>zg(f,h,void 0,e,t,n,r));if(d===-1)return!1;l.splice(d,1)}return!0}case _ge:case Bge:case kge:case Rge:case Dge:case Mge:case Uge:case Lge:case Fge:case jge:case zge:case Hge:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c<e.length;c++)if(!zg(e[c],t[c],c,e,t,n,r))return!1;return!0}case Pge:return e.byteLength!==t.byteLength?!1:Hg(new Uint8Array(e),new Uint8Array(t),n,r);case Nge:return e.byteLength!==t.byteLength||e.byteOffset!==t.byteOffset?!1:Hg(new Uint8Array(e),new Uint8Array(t),n,r);case Tge:return e.name===t.name&&e.message===t.message;case k9:{if(!(Hg(e.constructor,t.constructor,n,r)||aD(e)&&aD(t)))return!1;const c=[...Object.keys(e),...sD(e)],l=[...Object.keys(t),...sD(t)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const f=c[u],d=e[f];if(!Object.hasOwn(t,f))return!1;const h=t[f];if(!zg(d,h,f,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Zge(e,t){return qge(e,t,Vge)}var Wge=Object.defineProperty,cD=Object.getOwnPropertySymbols,Kge=Object.prototype.hasOwnProperty,Gge=Object.prototype.propertyIsEnumerable,R9=(e,t,n)=>t in e?Wge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lD=(e,t)=>{for(var n in t||(t={}))Kge.call(t,n)&&R9(e,n,t[n]);if(cD)for(var n of cD(t))Gge.call(t,n)&&R9(e,n,t[n]);return e},Ss=(e,t,n)=>R9(e,typeof t!="symbol"?t+"":t,n);class _0 extends Ufe{constructor(t,n,r,s=da,i=void 0){super(t,n,r,s),this.core=t,this.logger=n,this.name=r,Ss(this,"map",new Map),Ss(this,"version",Jhe),Ss(this,"cached",[]),Ss(this,"initialized",!1),Ss(this,"getKey"),Ss(this,"storagePrefix",da),Ss(this,"recentlyDeleted",[]),Ss(this,"recentlyDeletedLimit",200),Ss(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!bn(o)?this.map.set(this.getKey(o),o):Ide(o)?this.map.set(o.id,o):_de(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ss(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())}),Ss(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ss(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Zge(a[c],o[c]))):this.values)),Ss(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=lD(lD({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ss(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=ui(n,this.name),this.storagePrefix=s,this.getKey=i}get context(){return li(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(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){const n=this.map.get(t);if(!n){if(this.recentlyDeleted.includes(t)){const{message:s}=pe("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(s),new Error(s)}const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Yge=Object.defineProperty,Xge=(e,t,n)=>t in e?Yge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,et=(e,t,n)=>Xge(e,typeof t!="symbol"?t+"":t,n);class Jge{constructor(t,n){this.core=t,this.logger=n,et(this,"name",n1e),et(this,"version",r1e),et(this,"events",new Ot.exports),et(this,"pairings"),et(this,"initialized",!1),et(this,"storagePrefix",da),et(this,"ignoredPayloadTypes",[pl]),et(this,"registeredMethods",[]),et(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),et(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),et(this,"create",async r=>{this.isInitialized();const s=i9(),i=await this.core.crypto.setSymKey(s),o=cn(Q.FIVE_MINUTES),a={protocol:TR},c={topic:i,expiry:o,relay:a,active:!1,methods:r?.methods},l=Rk({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(C0.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:r?.transportType,internal:r?.internal}),{topic:i,uri:l}}),et(this,"pair",async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[fa.pairing_started]}});this.isValidPair(r,s);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=kk(r.uri);s.props.properties.topic=i,s.addTrace(fa.pairing_uri_validation_success),s.addTrace(fa.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(i)){if(u=this.pairings.get(i),s.addTrace(fa.existing_pairing),u.active)throw s.setError(bl.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);s.addTrace(fa.pairing_not_expired)}const f=c||cn(Q.FIVE_MINUTES),d={topic:i,relay:a,expiry:f,active:!1,methods:l};this.core.expirer.set(i,f),await this.pairings.set(i,d),s.addTrace(fa.store_new_pairing),r.activatePairing&&await this.activate({topic:i}),this.events.emit(C0.create,d),s.addTrace(fa.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),s.addTrace(fa.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(bl.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(h){throw s.setError(bl.subscribe_pairing_topic_failure),h}return s.addTrace(fa.subscribe_pairing_topic_success),d}),et(this,"activate",async({topic:r})=>{this.isInitialized();const s=cn(Q.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})}),et(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const i=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=g0();this.events.once(gt("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),et(this,"updateExpiry",async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})}),et(this,"updateMetadata",async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})}),et(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),et(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",Ut("USER_DISCONNECTED")),await this.deletePairing(s))}),et(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:s,relay:i,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return Rk({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),et(this,"sendRequest",async(r,s,i)=>{const o=rn(s,i),a=await this.core.crypto.encode(r,o),c=Mg[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),et(this,"sendResult",async(r,s,i)=>{const o=ua(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Mg[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),et(this,"sendError",async(r,s,i)=>{const o=Rh(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Mg[c]?Mg[c].res:Mg.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),et(this,"deletePairing",async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Ut("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])}),et(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(s=>ia(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))}),et(this,"onRelayEventRequest",async r=>{const{topic:s,payload:i}=r;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,i);default:return await this.onUnknownRpcMethodRequest(s,i)}}),et(this,"onRelayEventResponse",async r=>{const{topic:s,payload:i}=r,o=(await this.core.history.get(s,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,i);default:return this.onUnknownRpcMethodResponse(o)}}),et(this,"onPairingPingRequest",async(r,s)=>{const{id:i}=s;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.events.emit(C0.ping,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}}),et(this,"onPairingPingResponse",(r,s)=>{const{id:i}=s;setTimeout(()=>{wn(s)?this.events.emit(gt("pairing_ping",i),{}):Xt(s)&&this.events.emit(gt("pairing_ping",i),{error:s.error})},500)}),et(this,"onPairingDeleteRequest",async(r,s)=>{const{id:i}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(C0.delete,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}}),et(this,"onUnknownRpcMethodRequest",async(r,s)=>{const{id:i,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=Ut("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,r,a),this.logger.error(a)}catch(a){await this.sendError(i,r,a),this.logger.error(a)}}),et(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Ut("WC_METHOD_UNSUPPORTED",r))}),et(this,"isValidPair",(r,s)=>{var i;if(!As(r)){const{message:a}=pe("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(bl.malformed_pairing_uri),new Error(a)}if(!Sde(r.uri)){const{message:a}=pe("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(bl.malformed_pairing_uri),new Error(a)}const o=kk(r?.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:a}=pe("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(bl.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=pe("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(bl.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&Q.toMiliseconds(o?.expiryTimestamp)<Date.now()){s.setError(bl.pairing_expired);const{message:a}=pe("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),et(this,"isValidPing",async r=>{if(!As(r)){const{message:i}=pe("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)}),et(this,"isValidDisconnect",async r=>{if(!As(r)){const{message:i}=pe("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)}),et(this,"isValidPairingTopic",async r=>{if(!ln(r,!1)){const{message:s}=pe("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=pe("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(ia(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=pe("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}}),this.core=t,this.logger=ui(n,this.name),this.pairings=new _0(this.core,this.logger,this.name,this.storagePrefix)}get context(){return li(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(sn.message,async t=>{const{topic:n,message:r,transportType:s}=t;if(this.pairings.keys.includes(n)&&s!==Lt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const i=await this.core.crypto.decode(n,r);Dh(i)?(this.core.history.set(n,i),await this.onRelayEventRequest({topic:n,payload:i})):A0(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:n,payload:i}),this.core.history.delete(n,i.id)),await this.core.relayer.messages.ack(n,r)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(Ui.expired,async t=>{const{topic:n}=nB(t.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(C0.expire,{topic:n}))})}}var Qge=Object.defineProperty,e2e=(e,t,n)=>t in e?Qge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Jn=(e,t,n)=>e2e(e,typeof t!="symbol"?t+"":t,n);class t2e extends kfe{constructor(t,n){super(t,n),this.core=t,this.logger=n,Jn(this,"records",new Map),Jn(this,"events",new Ot.exports.EventEmitter),Jn(this,"name",s1e),Jn(this,"version",i1e),Jn(this,"cached",[]),Jn(this,"initialized",!1),Jn(this,"storagePrefix",da),Jn(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Jn(this,"set",(r,s,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:i}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:i,expiry:cn(Q.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(xo.created,o)}),Jn(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response>"u"&&(s.response=Xt(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(xo.updated,s))}),Jn(this,"get",async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s))),Jn(this,"delete",(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(i=>{if(i.topic===r){if(typeof s<"u"&&i.id!==s)return;this.records.delete(i.id),this.events.emit(xo.deleted,i)}}),this.persist()}),Jn(this,"exists",async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1)),Jn(this,"on",(r,s)=>{this.events.on(r,s)}),Jn(this,"once",(r,s)=>{this.events.once(r,s)}),Jn(this,"off",(r,s)=>{this.events.off(r,s)}),Jn(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=ui(n,this.name)}get context(){return li(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 t=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:rn(n.request.method,n.request.params,n.id),chainId:n.chainId};return t.push(r)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();const n=this.records.get(t);if(!n){const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(xo.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(xo.created,t=>{const n=xo.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(xo.updated,t=>{const n=xo.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(xo.deleted,t=>{const n=xo.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.core.heartbeat.on(ci.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(n=>{Q.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(xo.deleted,n,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var n2e=Object.defineProperty,r2e=(e,t,n)=>t in e?n2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xr=(e,t,n)=>r2e(e,typeof t!="symbol"?t+"":t,n);class s2e extends Ffe{constructor(t,n){super(t,n),this.core=t,this.logger=n,xr(this,"expirations",new Map),xr(this,"events",new Ot.exports.EventEmitter),xr(this,"name",o1e),xr(this,"version",a1e),xr(this,"cached",[]),xr(this,"initialized",!1),xr(this,"storagePrefix",da),xr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),xr(this,"has",r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}}),xr(this,"set",(r,s)=>{this.isInitialized();const i=this.formatTarget(r),o={target:i,expiry:s};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Ui.created,{target:i,expiration:o})}),xr(this,"get",r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)}),xr(this,"del",r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),i=this.getExpiration(s);this.expirations.delete(s),this.events.emit(Ui.deleted,{target:s,expiration:i})}}),xr(this,"on",(r,s)=>{this.events.on(r,s)}),xr(this,"once",(r,s)=>{this.events.once(r,s)}),xr(this,"off",(r,s)=>{this.events.off(r,s)}),xr(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=ui(n,this.name)}get context(){return li(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(t){if(typeof t=="string")return sce(t);if(typeof t=="number")return ice(t);const{message:n}=pe("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(n)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ui.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){const n=this.expirations.get(t);if(!n){const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(t,n){const{expiry:r}=n;Q.toMiliseconds(r)-Date.now()<=0&&this.expire(t,n)}expire(t,n){this.expirations.delete(t),this.events.emit(Ui.expired,{target:t,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,n)=>this.checkExpiry(n,t))}registerEventListeners(){this.core.heartbeat.on(ci.pulse,()=>this.checkExpirations()),this.events.on(Ui.created,t=>{const n=Ui.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Ui.expired,t=>{const n=Ui.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Ui.deleted,t=>{const n=Ui.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var i2e=Object.defineProperty,o2e=(e,t,n)=>t in e?i2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,un=(e,t,n)=>o2e(e,typeof t!="symbol"?t+"":t,n);class a2e extends jfe{constructor(t,n,r){super(t,n,r),this.core=t,this.logger=n,this.store=r,un(this,"name",c1e),un(this,"abortController"),un(this,"isDevEnv"),un(this,"verifyUrlV3",u1e),un(this,"storagePrefix",da),un(this,"version",OR),un(this,"publicKey"),un(this,"fetchPromise"),un(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&Q.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),un(this,"register",async s=>{if(!$h()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=ei(),u=this.startAbortTimer(Q.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",y),l.body.removeChild(g),h("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 y=$=>{if($.data&&typeof $.data=="string")try{const _=JSON.parse($.data);if(_.type==="verify_attestation"){if(vh(_.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),d(_.attestation===null?"":_.attestation)}}catch(_){this.logger.warn(_)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(l){this.logger.warn(l)}return""}),un(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=s;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(vh(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);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(s?.verifyUrl);return this.fetchAttestation(o,c)}),un(this,"fetchAttestation",async(s,i)=>{this.logger.debug(`resolving attestation: ${s} from url: ${i}`);const o=this.startAbortTimer(Q.ONE_SECOND*5),a=await fetch(`${i}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),un(this,"getVerifyUrl",s=>{let i=s||Ug;return d1e.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Ug}`),i=Ug),i}),un(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(Q.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await i.json()}catch(s){this.logger.warn(s)}}),un(this,"persistPublicKey",async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s}),un(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),un(this,"isValidJwtAttestation",async s=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(s,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),un(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),un(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),un(this,"validateAttestation",(s,i)=>{const o=Que(s,i.publicKey),a={hasExpired:Q.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=ui(n,this.name),this.abortController=new AbortController,this.isDevEnv=IE(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return li(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Q.toMiliseconds(t))}}var c2e=Object.defineProperty,l2e=(e,t,n)=>t in e?c2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,uD=(e,t,n)=>l2e(e,typeof t!="symbol"?t+"":t,n);class u2e extends zfe{constructor(t,n){super(t,n),this.projectId=t,this.logger=n,uD(this,"context",f1e),uD(this,"registerDeviceToken",async r=>{const{clientId:s,token:i,notificationType:o,enableEncrypted:a=!1}=r,c=`${h1e}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:i,always_raw:a})})}),this.logger=ui(n,this.context)}}var d2e=Object.defineProperty,dD=Object.getOwnPropertySymbols,f2e=Object.prototype.hasOwnProperty,h2e=Object.prototype.propertyIsEnumerable,D9=(e,t,n)=>t in e?d2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Vg=(e,t)=>{for(var n in t||(t={}))f2e.call(t,n)&&D9(e,n,t[n]);if(dD)for(var n of dD(t))h2e.call(t,n)&&D9(e,n,t[n]);return e},Un=(e,t,n)=>D9(e,typeof t!="symbol"?t+"":t,n);class p2e extends Hfe{constructor(t,n,r=!0){super(t,n,r),this.core=t,this.logger=n,Un(this,"context",g1e),Un(this,"storagePrefix",da),Un(this,"storageVersion",p1e),Un(this,"events",new Map),Un(this,"shouldPersist",!1),Un(this,"init",async()=>{if(!IE())try{const s={eventId:sB(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:eB(this.core.relayer.protocol,this.core.relayer.version,C9)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),Un(this,"createEvent",s=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=sB(),u=this.core.projectId||"",f=Date.now(),d=Vg({eventId:l,timestamp:f,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),Un(this,"getEvent",s=>{const{eventId:i,topic:o}=s;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Vg(Vg({},a),this.setMethods(a.eventId))}),Un(this,"deleteEvent",s=>{const{eventId:i}=s;this.events.delete(i),this.shouldPersist=!0}),Un(this,"setEventListeners",()=>{this.core.heartbeat.on(ci.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{Q.fromMiliseconds(Date.now())-Q.fromMiliseconds(s.timestamp)>m1e&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),Un(this,"setMethods",s=>({addTrace:i=>this.addTrace(s,i),setError:i=>this.setError(s,i)})),Un(this,"addTrace",(s,i)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(i),this.events.set(s,o),this.shouldPersist=!0)}),Un(this,"setError",(s,i)=>{const o=this.events.get(s);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),Un(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Un(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(i=>{this.events.set(i.eventId,Vg(Vg({},i),this.setMethods(i.eventId)))})}catch(s){this.logger.warn(s)}}),Un(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[i,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const i of s)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),Un(this,"sendEvent",async s=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${y1e}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${C9}${i}`,{method:"POST",body:JSON.stringify(s)})}),Un(this,"getAppDomain",()=>QN().url),this.logger=ui(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var g2e=Object.defineProperty,fD=Object.getOwnPropertySymbols,m2e=Object.prototype.hasOwnProperty,y2e=Object.prototype.propertyIsEnumerable,M9=(e,t,n)=>t in e?g2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hD=(e,t)=>{for(var n in t||(t={}))m2e.call(t,n)&&M9(e,n,t[n]);if(fD)for(var n of fD(t))y2e.call(t,n)&&M9(e,n,t[n]);return e},Rt=(e,t,n)=>M9(e,typeof t!="symbol"?t+"":t,n);class U9 extends Pfe{constructor(t){var n;super(t),Rt(this,"protocol",_R),Rt(this,"version",OR),Rt(this,"name",c6),Rt(this,"relayUrl"),Rt(this,"projectId"),Rt(this,"customStoragePrefix"),Rt(this,"events",new Ot.exports.EventEmitter),Rt(this,"logger"),Rt(this,"heartbeat"),Rt(this,"relayer"),Rt(this,"crypto"),Rt(this,"storage"),Rt(this,"history"),Rt(this,"expirer"),Rt(this,"pairing"),Rt(this,"verify"),Rt(this,"echoClient"),Rt(this,"linkModeSupportedApps"),Rt(this,"eventClient"),Rt(this,"initialized",!1),Rt(this,"logChunkController"),Rt(this,"on",(a,c)=>this.events.on(a,c)),Rt(this,"once",(a,c)=>this.events.once(a,c)),Rt(this,"off",(a,c)=>this.events.off(a,c)),Rt(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Rt(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Lt.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||NR,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const s=xfe({level:typeof t?.logger=="string"&&t.logger?t.logger:Uhe.logger,name:c6}),{logger:i,chunkLoggerController:o}=Ife({opts:s,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.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=ui(i,this.name),this.heartbeat=new Jw,this.crypto=new qpe(this,this.logger,t?.keychain),this.history=new t2e(this,this.logger),this.expirer=new s2e(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new Qk(hD(hD({},Lhe),t?.storageOptions)),this.relayer=new bge({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Jge(this,this.logger),this.verify=new a2e(this,this.logger,this.storage),this.echoClient=new u2e(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new p2e(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new U9(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(Qhe,r),n}get context(){return li(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(BR,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(BR)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${t}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(t){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=t.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const b2e=U9;var L9={exports:{}};const pD=Aw;L9.exports=wl;const qg=B2e().console||{},w2e={mapHttpRequest:d6,mapHttpResponse:d6,wrapRequestSerializer:V9,wrapResponseSerializer:V9,wrapErrorSerializer:V9,req:d6,res:d6,err:mD,errWithCause:mD};function Vu(e,t){return e==="silent"?1/0:t.levels.values[e]}const F9=Symbol("pino.logFuncs"),j9=Symbol("pino.hierarchy"),v2e={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function gD(e,t){const n={logger:t,parent:e[j9]};t[j9]=n}function E2e(e,t,n){const r={};t.forEach(s=>{r[s]=n[s]?n[s]:qg[s]||qg[v2e[s]||"log"]||Fh}),e[F9]=r}function x2e(e,t){return Array.isArray(e)?e.filter(function(r){return r!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function wl(e){e=e||{},e.browser=e.browser||{};const t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");const n=e.browser.write||qg;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},s=x2e(e.browser.serialize,r);let i=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(n);l.log||(l.log=Fh),E2e(l,a,n),gD({},l),Object.defineProperty(l,"levelVal",{get:f}),Object.defineProperty(l,"level",{get:d,set:h});const u={transmit:t,serialize:s,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:P2e(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Fh};l.levels=$2e(e),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Fh,l.serializers=r,l._serialize=s,l._stdErrSerialize=i,l.child=function(...g){return p.call(this,u,...g)},t&&(l._logEvent=H9());function f(){return Vu(this.level,this)}function d(){return this._level}function h(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,O0(this,u,l,"error"),O0(this,u,l,"fatal"),O0(this,u,l,"warn"),O0(this,u,l,"info"),O0(this,u,l,"debug"),O0(this,u,l,"trace"),o.forEach(y=>{O0(this,u,l,y)})}function p(g,y,$){if(!y)throw new Error("missing bindings for child Pino");$=$||{},s&&y.serializers&&($.serializers=y.serializers);const _=$.serializers;if(s&&_){var x=Object.assign({},r,_),E=e.browser.serialize===!0?Object.keys(x):s;delete y.serializers,z9([y],E,x,this._stdErrSerialize)}function P(k){this._childLevel=(k._childLevel|0)+1,this.bindings=y,x&&(this.serializers=x,this._serialize=E),t&&(this._logEvent=H9([].concat(k._logEvent.bindings,y)))}P.prototype=this;const N=new P(this);return gD(this,N),N.child=function(...k){return p.call(this,g,...k)},N.level=$.level||this.level,g.onChild(N),N}return l}function $2e(e){const t=e.customLevels||{},n=Object.assign({},wl.levels.values,t),r=Object.assign({},wl.levels.labels,A2e(t));return{values:n,labels:r}}function A2e(e){const t={};return Object.keys(e).forEach(function(n){t[e[n]]=n}),t}wl.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},wl.stdSerializers=w2e,wl.stdTimeFunctions=Object.assign({},{nullTime:yD,epochTime:bD,unixTime:T2e,isoTime:N2e});function C2e(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[j9];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}function O0(e,t,n,r){if(Object.defineProperty(e,r,{value:Vu(e.level,n)>Vu(r,n)?Fh:n[F9][r],writable:!0,enumerable:!0,configurable:!0}),e[r]===Fh){if(!t.transmit)return;const i=t.transmit.level||e.level,o=Vu(i,n);if(Vu(r,n)<o)return}e[r]=I2e(e,t,n,r);const s=C2e(e);s.length!==0&&(e[r]=S2e(s,e[r]))}function S2e(e,t){return function(){return t.apply(this,[...e,...arguments])}}function I2e(e,t,n,r){return function(s){return function(){const o=t.timestamp(),a=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===qg?qg:this;for(var l=0;l<a.length;l++)a[l]=arguments[l];var u=!1;if(t.serialize&&(z9(a,this._serialize,this.serializers,this._stdErrSerialize),u=!0),t.asObject||t.formatters?s.call(c,..._2e(this,r,a,o,t)):s.apply(c,a),t.transmit){const f=t.transmit.level||e._level,d=Vu(f,n),h=Vu(r,n);if(h<d)return;O2e(this,{ts:o,methodLevel:r,methodValue:h,transmitLevel:f,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Vu(e._level,n)},a,u)}}}(e[F9][r])}function _2e(e,t,n,r,s){const{level:i,log:o=f=>f}=s.formatters||{},a=n.slice();let c=a[0];const l={};let u=(e._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),i){const f=i(t,e.levels.values[t]);Object.assign(l,f)}else l.level=e.levels.values[t];if(s.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?pD(a.shift(),a):void 0}else typeof c=="string"&&(c=pD(a.shift(),a));return c!==void 0&&(l[s.messageKey]=c),[o(l)]}}function z9(e,t,n,r){for(const s in e)if(r&&e[s]instanceof Error)e[s]=wl.stdSerializers.err(e[s]);else if(typeof e[s]=="object"&&!Array.isArray(e[s])&&t)for(const i in e[s])t.indexOf(i)>-1&&i in n&&(e[s][i]=n[i](e[s][i]))}function O2e(e,t,n,r=!1){const s=t.send,i=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;r||z9(n,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=i,e._logEvent.messages=n.filter(function(u){return l.indexOf(u)===-1}),e._logEvent.level.label=o,e._logEvent.level.value=a,s(o,e._logEvent,c),e._logEvent=H9(l)}function H9(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function mD(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)t[n]===void 0&&(t[n]=e[n]);return t}function P2e(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?yD:bD}function d6(){return{}}function V9(e){return e}function Fh(){}function yD(){return!1}function bD(){return Date.now()}function T2e(){return Math.round(Date.now()/1e3)}function N2e(){return new Date(Date.now()).toISOString()}function B2e(){function e(t){return typeof t<"u"&&t}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}L9.exports.default=wl,L9.exports.pino=wl;const k2e="custom_context";function R2e(e,t=k2e){return e[t]||""}const wD="wc",vD=2,ED="client",q9=`${wD}@${vD}:${ED}:`,Z9={name:ED,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},xD="WALLETCONNECT_DEEPLINK_CHOICE",D2e="proposal",$D="Proposal expired",M2e="session",jh=Q.SEVEN_DAYS,U2e="engine",Qn={wc_sessionPropose:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Q.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Q.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1119}}},W9={min:Q.FIVE_MINUTES,max:Q.SEVEN_DAYS},pa={idle:"IDLE",active:"ACTIVE"},L2e={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:""}},F2e="request",j2e=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],z2e="wc",H2e="auth",V2e="authKeys",q2e="pairingTopics",Z2e="requests",f6=`${z2e}@${1.5}:${H2e}:`,h6=`${f6}:PUB_KEY`;var W2e=Object.defineProperty,K2e=Object.defineProperties,G2e=Object.getOwnPropertyDescriptors,AD=Object.getOwnPropertySymbols,Y2e=Object.prototype.hasOwnProperty,X2e=Object.prototype.propertyIsEnumerable,K9=(e,t,n)=>t in e?W2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wt=(e,t)=>{for(var n in t||(t={}))Y2e.call(t,n)&&K9(e,n,t[n]);if(AD)for(var n of AD(t))X2e.call(t,n)&&K9(e,n,t[n]);return e},$r=(e,t)=>K2e(e,G2e(t)),le=(e,t,n)=>K9(e,typeof t!="symbol"?t+"":t,n);class J2e extends Wfe{constructor(t){super(t),le(this,"name",U2e),le(this,"events",new Ot.exports),le(this,"initialized",!1),le(this,"requestQueue",{state:pa.idle,queue:[]}),le(this,"sessionRequestQueue",{state:pa.idle,queue:[]}),le(this,"emittedSessionRequests",new pce({limit:500})),le(this,"requestQueueDelay",Q.ONE_SECOND),le(this,"expectedPairingMethodMap",new Map),le(this,"recentlyDeletedMap",new Map),le(this,"recentlyDeletedLimit",200),le(this,"relayMessageCache",[]),le(this,"pendingSessions",new Map),le(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(Qn)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Q.toMiliseconds(this.requestQueueDelay)))}),le(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=$r(wt({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=Ede(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=s,f,d=!1;try{if(u){const N=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),N}if(!u||!d){const{topic:N,uri:k}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=N,f=k}if(!u){const{message:N}=pe("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(N)}const h=await this.client.core.crypto.generateKeyPair(),p=Qn.wc_sessionPropose.req.ttl||Q.FIVE_MINUTES,g=cn(p),y=$r(wt(wt({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:TR}],proposer:{publicKey:h,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Dn()}),$=gt("session_connect",y.id),{reject:_,resolve:x,done:E}=g0(p,$D),P=({id:N})=>{N===y.id&&(this.client.events.off("proposal_expire",P),this.pendingSessions.delete(y.id),this.events.emit($,{error:{message:$D,code:0}}))};return this.client.events.on("proposal_expire",P),this.events.once($,({error:N,session:k})=>{this.client.events.off("proposal_expire",P),N?_(N):k&&x(k)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:f,approval:E}}),le(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),le(this,"approve",async n=>{var r,s,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[$o.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(T){throw o.setError(S0.no_internet_connection),T}try{await this.isValidProposalId(n?.id)}catch(T){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(S0.proposal_not_found),T}try{await this.isValidApprove(n)}catch(T){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(S0.session_approve_namespace_validation_failure),T}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:f,sessionConfig:d}=n,h=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:y,optionalNamespaces:$}=h;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:$o.session_approve_started,properties:{topic:p,trace:[$o.session_approve_started,$o.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),E=g.publicKey,P=await this.client.core.crypto.generateSharedKey(x,E),N=wt(wt(wt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:x,metadata:this.client.metadata},expiry:cn(jh)},u&&{sessionProperties:u}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),k=Lt.relay;_.addTrace($o.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:k,internal:{skipSubscribe:!0}})}catch(T){throw _.setError(S0.subscribe_session_topic_failure),T}_.addTrace($o.subscribe_session_topic_success);const R=$r(wt({},N),{topic:P,requiredNamespaces:y,optionalNamespaces:$,pairingTopic:p,acknowledged:!1,self:N.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:x,transportType:Lt.relay});await this.client.session.set(P,R),_.addTrace($o.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:h,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:N,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),_.addTrace($o.session_approve_publish_success)}catch(T){throw this.client.logger.error(T),this.client.session.delete(P,Ut("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),T}return this.client.core.eventClient.deleteEvent({eventId:_.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(P,cn(jh)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),le(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:s}=n;let i;try{i=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}i&&await this.sendError({id:r,topic:i,error:s,rpcOpts:Qn.wc_sessionPropose.reject}),await this.deleteProposal(r)}),le(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:s}=n,{done:i,resolve:o,reject:a}=g0(),c=Dn(),l=Wr().toString(),u=this.client.session.get(r).namespaces;return this.events.once(gt("session_update",c),({error:f})=>{f?a(f):o()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:u}),a(f)}),{acknowledged:i}}),le(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,s=Dn(),{done:i,resolve:o,reject:a}=g0();return this.events.once(gt("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,cn(jh)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),le(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:s,topic:i,expiry:o=Qn.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(i);a?.transportType===Lt.relay&&await this.confirmOnlineStateOrThrow();const c=Dn(),l=Wr().toString(),{done:u,resolve:f,reject:d}=g0(o,"Request expired. Please try again.");this.events.once(gt("session_request",c),({error:y,result:$})=>{y?d(y):f($)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:h,params:{request:$r(wt({},s),{expiryTimestamp:cn(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),await u();const g={request:$r(wt({},s),{expiryTimestamp:cn(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:h,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch($=>d($)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),y()}),new Promise(async y=>{var $;if(!(($=a.sessionConfig)!=null&&$.disableDeepLink)){const _=await lce(this.client.core.storage,xD);await oce({id:c,topic:i,wcDeepLink:_})}y()}),u()]).then(y=>y[2])}),le(this,"respond",async n=>{var r,s;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((s=(r=n?.response)==null?void 0:r.id)==null?void 0:s.toString()),trace:[$o.session_request_response_started]}});try{await this.isValidRespond(n)}catch(f){throw i.addTrace(f?.message),i.setError(S0.session_request_response_validation_failure),f}i.addTrace($o.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,l=this.client.session.get(o);l.transportType===Lt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace($o.session_request_response_publish_started),wn(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):Xt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(n)}catch(f){throw i.addTrace(f?.message),i.setError(S0.session_request_response_publish_failure),f}}),le(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=n;if(this.client.session.keys.includes(r)){const s=Dn(),i=Wr().toString(),{done:o,resolve:a,reject:c}=g0();this.events.once(gt("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),le(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:s,chainId:i}=n,o=Wr().toString(),a=Dn();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),le(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:Ut("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=pe("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}}),le(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>Ade(r,n)))),le(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),le(this,"authenticate",async(n,r)=>{var s;this.isInitialized(),this.isValidAuthenticate(n);const i=r&&this.client.core.linkModeSupportedApps.includes(r)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=i?Lt.link_mode:Lt.relay;o===Lt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:f,type:d,exp:h,nbf:p,methods:g=[],expiry:y}=n,$=[...n.resources||[]],{topic:_,uri:x}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:x}});const E=await this.client.core.crypto.generateKeyPair(),P=Ww(E);if(await Promise.all([this.client.auth.authKeys.set(h6,{responseTopic:P,publicKey:E}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:_})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${_}`),g.length>0){const{namespace:C}=cl(a[0]);let O=Ale(C,"request",g);Rw($)&&(O=Sle(O,$.pop())),$.push(O)}const N=y&&y>Qn.wc_sessionAuthenticate.req.ttl?y:Qn.wc_sessionAuthenticate.req.ttl,k={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:$},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:cn(N)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},T={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:cn(Qn.wc_sessionPropose.req.ttl),id:Dn()},{done:L,resolve:M,reject:S}=g0(N,"Request expired"),w=Dn(),v=gt("session_connect",T.id),m=gt("session_request",w),b=async({error:C,session:O})=>{this.events.off(m,A),C?S(C):O&&M({session:O})},A=async C=>{var O,B,D;if(await this.deletePendingAuthRequest(w,{message:"fulfilled",code:0}),C.error){const Z=Ut("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===Z.code?void 0:(this.events.off(v,b),S(C.error.message))}await this.deleteProposal(T.id),this.events.off(v,b);const{cacaos:z,responder:j}=C.result,U=[],V=[];for(const Z of z){await OB({cacao:Z,projectId:this.client.core.projectId})||(this.client.logger.error(Z,"Signature verification failed"),S(Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=Z,fe=Rw(Y.resources),me=[DE(Y.iss)],we=kw(Y.iss);if(fe){const Re=NB(fe),We=BB(fe);U.push(...Re),me.push(...We)}for(const Re of me)V.push(`${Re}:${we}`)}const q=await this.client.core.crypto.generateSharedKey(E,j.publicKey);let X;U.length>0&&(X={topic:q,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:j,controller:j.publicKey,expiry:cn(jh),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:Lk([...new Set(U)],[...new Set(V)]),transportType:o},await this.client.core.relayer.subscribe(q,{transportType:o}),await this.client.session.set(q,X),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:j.metadata}),X=this.client.session.get(q)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(B=j.metadata.redirect)!=null&&B.linkMode&&(D=j.metadata.redirect)!=null&&D.universal&&r&&(this.client.core.addLinkModeSupportedApp(j.metadata.redirect.universal),this.client.session.update(q,{transportType:Lt.link_mode})),M({auths:z,session:X})};this.events.once(v,b),this.events.once(m,A);let I;try{if(i){const C=rn("wc_sessionAuthenticate",k,w);this.client.core.history.set(_,C);const O=await this.client.core.crypto.encode("",C,{type:Og,encoding:ju});I=Gw(r,_,O)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:k,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:w}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:T,expiry:Qn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:T.id})])}catch(C){throw this.events.off(v,b),this.events.off(m,A),C}return await this.setProposal(T.id,T),await this.setAuthRequest(w,{request:$r(wt({},k),{verifyContext:{}}),pairingTopic:_,transportType:o}),{uri:I??x,response:L}}),le(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:s}=n,i=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[I0.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Lg.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw i.setError(Lg.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Lt.relay;a===Lt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Ww(c),f={type:pl,receiverPublicKey:c,senderPublicKey:l},d=[],h=[];for(const y of s){if(!await OB({cacao:y,projectId:this.client.core.projectId})){i.setError(Lg.invalid_cacao);const P=Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:P,encodeOpts:f}),new Error(P.message)}i.addTrace(I0.cacaos_verified);const{p:$}=y,_=Rw($.resources),x=[DE($.iss)],E=kw($.iss);if(_){const P=NB(_),N=BB(_);d.push(...P),x.push(...N)}for(const P of x)h.push(`${P}:${E}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(I0.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:cn(jh),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Lk([...new Set(d)],[...new Set(h)]),transportType:a},i.addTrace(I0.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw i.setError(Lg.subscribe_authenticated_session_topic_failure),y}i.addTrace(I0.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),i.addTrace(I0.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(I0.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw i.setError(Lg.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:g}}),le(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:s}=n,i=this.getPendingAuthRequest(r);if(!i)throw new Error(`Could not find pending auth request with id ${r}`);i.transportType===Lt.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ww(o),l={type:pl,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:l,rpcOpts:Qn.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),le(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:s}=n;return PB(r,s)}),le(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),le(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&i.topic&&i.topic!==r.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),le(this,"deleteSession",async n=>{var r;const{topic:s,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,Ut("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(xD).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===s&&this.deletePendingSessionRequest(l.id,Ut("USER_DISCONNECTED"))}),s===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=pa.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),le(this,"deleteProposal",async(n,r)=>{if(r)try{const s=this.client.proposal.get(n),i=this.client.core.eventClient.getEvent({topic:s.pairingTopic});i?.setError(S0.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Ut("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),le(this,"deletePendingSessionRequest",async(n,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==n),s&&(this.sessionRequestQueue.state=pa.idle,this.client.events.emit("session_request_expire",{id:n}))}),le(this,"deletePendingAuthRequest",async(n,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)])}),le(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),le(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,cn(Qn.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),le(this,"setAuthRequest",async(n,r)=>{const{request:s,pairingTopic:i,transportType:o=Lt.relay}=r;this.client.core.expirer.set(n,s.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:n,pairingTopic:i,verifyContext:s.verifyContext,transportType:o})}),le(this,"setPendingSessionRequest",async n=>{const{id:r,topic:s,params:i,verifyContext:o}=n,a=i.request.expiryTimestamp||cn(Qn.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:i,verifyContext:o})}),le(this,"sendRequest",async n=>{const{topic:r,method:s,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:f,publishOpts:d={}}=n,h=rn(s,i,c);let p;const g=!!u;try{const _=g?ju:$s;p=await this.client.core.crypto.encode(r,h,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),_}let y;if(j2e.includes(s)){const _=Ri(JSON.stringify(h)),x=Ri(p);y=await this.client.core.verify.register({id:x,decryptedId:_})}const $=wt(wt({},Qn[s].req),d);if($.attestation=y,o&&($.ttl=o),a&&($.id=a),this.client.core.history.set(r,h),g){const _=Gw(u,r,p);await global.Linking.openURL(_,this.client.name)}else $.tvf=$r(wt({},f),{correlationId:h.id}),l?($.internal=$r(wt({},$.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,$)):this.client.core.relayer.publish(r,p,$).catch(_=>this.client.logger.error(_));return h.id}),le(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:s}=n,i=rn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,i);const o=await this.client.core.crypto.encode(r.pairingTopic,i,{encoding:$s}),a=Ri(JSON.stringify(i)),c=Ri(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:$r(wt({},s),{publishMethod:"wc_proposeSession",attestation:l})})}),le(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:s,proposal:i,sessionSettleRequest:o,publishOpts:a}=n,c=ua(i.id,s),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:$s}),u=rn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,u,{encoding:$s});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:f},opts:$r(wt({},a),{publishMethod:"wc_approveSession"})})}),le(this,"sendResult",async n=>{const{id:r,topic:s,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=ua(r,i);let u;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?ju:$s;u=await this.client.core.crypto.encode(s,l,$r(wt({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),p}let d,h;try{d=await this.client.core.history.get(s,r);const p=d.request;try{h=this.getTVFParams(r,p.params,i)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),p}if(f){const p=Gw(c,s,u);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=Qn[p].res;g.tvf=$r(wt({},h),{correlationId:r}),o?(g.internal=$r(wt({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,g)):this.client.core.relayer.publish(s,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),le(this,"sendError",async n=>{const{id:r,topic:s,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=Rh(r,i);let u;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?ju:$s;u=await this.client.core.crypto.encode(s,l,$r(wt({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),h}let d;try{d=await this.client.core.history.get(s,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),h}if(f){const h=Gw(c,s,u);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||Qn[h].res;this.client.core.relayer.publish(s,u,p)}await this.client.core.history.resolve(l)}),le(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(s=>{let i=!1;ia(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&n.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{ia(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...n.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])}),le(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),le(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),le(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===pa.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=pa.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=pa.idle}),le(this,"processRequest",async n=>{const{topic:r,payload:s,attestation:i,transportType:o,encryptedId:a}=n,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),le(this,"onRelayEventResponse",async n=>{const{topic:r,payload:s,transportType:i}=n,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),le(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:s}=pe("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),le(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:s}=n,i=this.expectedPairingMethodMap.get(r);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),le(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o}=n,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(bl.proposal_listener_not_found)),this.isValidConnect(wt({},s.params));const u=a.expiryTimestamp||cn(Qn.wc_sessionPropose.req.ttl),f=wt({id:c,pairingTopic:r,expiryTimestamp:u,attestation:i,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:i,hash:Ri(JSON.stringify(s)),encryptedId:o,metadata:f.proposer.metadata});l?.addTrace(fa.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Qn.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),le(this,"onSessionProposeResponse",async(n,r,s)=>{const{id:i}=r;if(wn(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);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(i,{sessionTopic:u,pairingTopic:n,proposalId:i,publicKey:c});const f=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:n})}else if(Xt(r)){await this.deleteProposal(i);const o=gt("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),le(this,"onSessionSettleRequest",async(n,r)=>{const{id:s,params:i}=r;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:f,sessionConfig:d}=r.params,h=[...this.pendingSessions.values()].find(y=>y.sessionTopic===n);if(!h)return this.client.logger.error(`Pending session not found for topic ${n}`);const p=this.client.proposal.get(h.proposalId),g=$r(wt(wt(wt({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:h.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:h.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:Lt.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:h.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(gt("session_connect",h.proposalId),{session:g}),this.pendingSessions.delete(h.proposalId),this.deleteProposal(h.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),le(this,"onSessionSettleResponse",async(n,r)=>{const{id:s}=r;wn(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(gt("session_approve",s),{})):Xt(r)&&(await this.client.session.delete(n,Ut("USER_DISCONNECTED")),this.events.emit(gt("session_approve",s),{error:r.error}))}),le(this,"onSessionUpdateRequest",async(n,r)=>{const{params:s,id:i}=r;try{const o=`${n}_session_update`,a=Ng.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:n,error:Ut("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(wt({topic:n},s));try{Ng.set(o,i),await this.client.session.update(n,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:n,result:!0})}catch(c){throw Ng.delete(o),c}this.client.events.emit("session_update",{id:i,topic:n,params:s})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),le(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),le(this,"onSessionUpdateResponse",(n,r)=>{const{id:s}=r,i=gt("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);wn(r)?this.events.emit(gt("session_update",s),{}):Xt(r)&&this.events.emit(gt("session_update",s),{error:r.error})}),le(this,"onSessionExtendRequest",async(n,r)=>{const{id:s}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,cn(jh)),await this.sendResult({id:s,topic:n,result:!0}),this.client.events.emit("session_extend",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}}),le(this,"onSessionExtendResponse",(n,r)=>{const{id:s}=r,i=gt("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);wn(r)?this.events.emit(gt("session_extend",s),{}):Xt(r)&&this.events.emit(gt("session_extend",s),{error:r.error})}),le(this,"onSessionPingRequest",async(n,r)=>{const{id:s}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:s,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}}),le(this,"onSessionPingResponse",(n,r)=>{const{id:s}=r,i=gt("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);wn(r)?this.events.emit(gt("session_ping",s),{}):Xt(r)&&this.events.emit(gt("session_ping",s),{error:r.error})},500)}),le(this,"onSessionDeleteRequest",async(n,r)=>{const{id:s}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(sn.publish,async()=>{i(await this.deleteSession({topic:n,id:s}))})}),this.sendResult({id:s,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Ut("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),le(this,"onSessionRequest",async n=>{var r,s,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:f,params:d}=a;try{await this.isValidRequest(wt({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Ri(JSON.stringify(rn("wc_sessionRequest",d,f))),encryptedId:l,metadata:h.peer.metadata,transportType:u}),g={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(g),u===Lt.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((s=h.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),le(this,"onSessionRequestResponse",(n,r)=>{const{id:s}=r,i=gt("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);wn(r)?this.events.emit(gt("session_request",s),{result:r.result}):Xt(r)&&this.events.emit(gt("session_request",s),{error:r.error})}),le(this,"onSessionEventRequest",async(n,r)=>{const{id:s,params:i}=r;try{const o=`${n}_session_event_${i.event.name}`,a=Ng.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(wt({topic:n},i)),this.client.events.emit("session_event",{id:s,topic:n,params:i}),Ng.set(o,s)}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),le(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),wn(r)?this.events.emit(gt("session_request",s),{result:r.result}):Xt(r)&&this.events.emit(gt("session_request",s),{error:r.error})}),le(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:s,payload:i,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:f}=i.params,d=await this.getVerifyContext({attestationId:o,hash:Ri(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),h={requester:l,pairingTopic:s,id:i.id,authPayload:u,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(i.id,{request:h,pairingTopic:s,transportType:c}),c===Lt.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:d})}catch(l){this.client.logger.error(l);const u=i.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(i.params.requester.metadata,c),h={type:pl,receiverPublicKey:u,senderPublicKey:f};await this.sendError({id:i.id,topic:s,error:l,encodeOpts:h,rpcOpts:Qn.wc_sessionAuthenticate.autoReject,appLink:d})}}),le(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),le(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=pa.idle,this.processSessionRequestQueue()},Q.toMiliseconds(this.requestQueueDelay))}),le(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===n&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=gt("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(gt("session_request",i.request.id),{error:r})})}),le(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===pa.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),le(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=pa.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),le(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:rn("wc_sessionPropose",$r(wt({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),le(this,"isValidConnect",async n=>{if(!As(n)){const{message:l}=pe("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=n;if(bn(r)||await this.isValidPairingTopic(r),!Dde(c,!0)){const{message:l}=pe("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!bn(s)&&ca(s)!==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(s,"requiredNamespaces")}if(i&&!bn(i)&&ca(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!bn(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!bn(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(i||{}));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)}`)}}),le(this,"validateNamespaces",(n,r)=>{const s=Rde(n,"connect()",r);if(s)throw new Error(s.message)}),le(this,"isValidApprove",async n=>{if(!As(n))throw new Error(pe("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:s,relayProtocol:i,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=c9(s,"approve()");if(l)throw new Error(l.message);const u=Vk(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!ln(i,!0)){const{message:f}=pe("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(f)}if(o&&!bn(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!bn(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(s));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),le(this,"isValidReject",async n=>{if(!As(n)){const{message:i}=pe("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(i)}const{id:r,reason:s}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!Ude(s)){const{message:i}=pe("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}}),le(this,"isValidSessionSettleRequest",n=>{if(!As(n)){const{message:l}=pe("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:s,namespaces:i,expiry:o}=n;if(!zk(r)){const{message:l}=pe("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Ode(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=c9(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ia(o)){const{message:l}=pe("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),le(this,"isValidUpdate",async n=>{if(!As(n)){const{message:c}=pe("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:s}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const i=this.client.session.get(r),o=c9(s,"update()");if(o)throw new Error(o.message);const a=Vk(i.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),le(this,"isValidExtend",async n=>{if(!As(n)){const{message:s}=pe("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(s)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),le(this,"isValidRequest",async n=>{if(!As(n)){const{message:c}=pe("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:s,chainId:i,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Hk(a,i)){const{message:c}=pe("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!Lde(s)){const{message:c}=pe("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!zde(a,i,s.method)){const{message:c}=pe("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!Zde(o,W9)){const{message:c}=pe("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${W9.min} and ${W9.max}`);throw new Error(c)}}),le(this,"isValidRespond",async n=>{var r;if(!As(n)){const{message:a}=pe("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:s,response:i}=n;try{await this.isValidSessionTopic(s)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!Fde(i)){const{message:a}=pe("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(a)}const o=this.client.pendingRequest.get(i.id);if(o.topic!==s){const{message:a}=pe("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${s}`);throw new Error(a)}}),le(this,"isValidPing",async n=>{if(!As(n)){const{message:s}=pe("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),le(this,"isValidEmit",async n=>{if(!As(n)){const{message:a}=pe("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:s,chainId:i}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Hk(o,i)){const{message:a}=pe("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!jde(s)){const{message:a}=pe("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!Hde(o,i,s.name)){const{message:a}=pe("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),le(this,"isValidDisconnect",async n=>{if(!As(n)){const{message:s}=pe("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),le(this,"isValidAuthenticate",n=>{const{chains:r,uri:s,domain:i,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!ln(s,!1))throw new Error("uri is required parameter");if(!ln(i,!1))throw new Error("domain is required parameter");if(!ln(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>cl(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=cl(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),le(this,"getVerifyContext",async n=>{const{attestationId:r,hash:s,encryptedId:i,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Ug,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Lt.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:r,hash:s,encryptedId:i,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}),le(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((s,i)=>{if(s==null){const{message:o}=pe("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(n)[i]}`);throw new Error(o)}})}),le(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),le(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(o)}}}),le(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:s}=pe("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(s)}}),le(this,"isLinkModeEnabled",(n,r)=>{var s,i,o,a,c,l,u,f,d;return!n||r!==Lt.link_mode?!1:((i=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:i.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=n?.redirect)==null?void 0:u.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),le(this,"getAppLinkIfEnabled",(n,r)=>{var s;return this.isLinkModeEnabled(n,r)?(s=n?.redirect)==null?void 0:s.universal:void 0}),le(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=rB(n,"topic")||"",s=decodeURIComponent(rB(n,"wc_ev")||""),i=this.client.session.keys.includes(r);i&&this.client.session.update(r,{transportType:Lt.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:i})}),le(this,"registerLinkModeListeners",async()=>{var n;if(IE()||Iu()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await r.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),le(this,"getTVFParams",(n,r,s)=>{var i,o,a;if(!((i=r.request)!=null&&i.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,s);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),le(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const s=n?.data||((r=n?.[0])==null?void 0:r.data);if(!s.startsWith("0x"))return!1;const i=s.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),le(this,"extractTxHashesFromResult",(n,r)=>{var s;try{if(!r)return[];const i=n.method,o=L2e[i];if(i==="sui_signTransaction")return[ale(r.transactionBytes)];if(i==="near_signTransaction")return[CB(r)];if(i==="near_signTransactions")return r.map(c=>CB(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(s=r.tx_json)==null?void 0:s.hash];if(i==="polkadot_signTransaction")return[a0e({transaction:n.params.transactionPayload,signature:r.signature})];if(i==="algo_signTxn")return Di(r)?r.map(c=>SB(c)):[SB(r)];if(i==="cosmos_signDirect")return[lle(r)];if(i==="wallet_sendCalls")return ule(r);if(typeof r=="string")return[r];const a=r[o.key];if(Di(a))return i==="solana_signAllTransactions"?a.map(c=>ole(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn(i,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const t=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(t);for(const[r,s]of Object.entries(n))for(const i of s)try{await this.onProviderMessageEvent({topic:r,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${i}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(sn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){const{topic:n,message:r,attestation:s,transportType:i}=t,{publicKey:o}=this.client.auth.authKeys.keys.includes(h6)?this.client.auth.authKeys.get(h6):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:i===Lt.link_mode?ju:$s});Dh(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:s,transportType:i,encryptedId:Ri(r)})):A0(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:i}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ui.expired,async t=>{const{topic:n,id:r}=nB(t.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,pe("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,pe("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(C0.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(C0.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!ln(t,!1)){const{message:n}=pe("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:n}=pe("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(n)}if(ia(this.client.core.pairing.pairings.get(t).expiry)){const{message:n}=pe("EXPIRED",`pairing topic: ${t}`);throw new Error(n)}}async isValidSessionTopic(t){if(!ln(t,!1)){const{message:n}=pe("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(n)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){const{message:n}=pe("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(n)}if(ia(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});const{message:n}=pe("EXPIRED",`session topic: ${t}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(t)){const{message:n}=pe("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(n)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(ln(t,!1)){const{message:n}=pe("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(n)}else{const{message:n}=pe("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(n)}}async isValidProposalId(t){if(!Mde(t)){const{message:n}=pe("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(n)}if(!this.client.proposal.keys.includes(t)){const{message:n}=pe("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(n)}if(ia(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);const{message:n}=pe("EXPIRED",`proposal id: ${t}`);throw new Error(n)}}}class Q2e extends _0{constructor(t,n){super(t,n,D2e,q9),this.core=t,this.logger=n}}class eme extends _0{constructor(t,n){super(t,n,M2e,q9),this.core=t,this.logger=n}}class tme extends _0{constructor(t,n){super(t,n,F2e,q9,r=>r.id),this.core=t,this.logger=n}}class nme extends _0{constructor(t,n){super(t,n,V2e,f6,()=>h6),this.core=t,this.logger=n}}class rme extends _0{constructor(t,n){super(t,n,q2e,f6),this.core=t,this.logger=n}}class sme extends _0{constructor(t,n){super(t,n,Z2e,f6,r=>r.id),this.core=t,this.logger=n}}var ime=Object.defineProperty,ome=(e,t,n)=>t in e?ime(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G9=(e,t,n)=>ome(e,typeof t!="symbol"?t+"":t,n);class ame{constructor(t,n){this.core=t,this.logger=n,G9(this,"authKeys"),G9(this,"pairingTopics"),G9(this,"requests"),this.authKeys=new nme(this.core,this.logger),this.pairingTopics=new rme(this.core,this.logger),this.requests=new sme(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var cme=Object.defineProperty,lme=(e,t,n)=>t in e?cme(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,tt=(e,t,n)=>lme(e,typeof t!="symbol"?t+"":t,n);class Y9 extends Zfe{constructor(t){super(t),tt(this,"protocol",wD),tt(this,"version",vD),tt(this,"name",Z9.name),tt(this,"metadata"),tt(this,"core"),tt(this,"logger"),tt(this,"events",new Ot.exports.EventEmitter),tt(this,"engine"),tt(this,"session"),tt(this,"proposal"),tt(this,"pendingRequest"),tt(this,"auth"),tt(this,"signConfig"),tt(this,"on",(r,s)=>this.events.on(r,s)),tt(this,"once",(r,s)=>this.events.once(r,s)),tt(this,"off",(r,s)=>this.events.off(r,s)),tt(this,"removeListener",(r,s)=>this.events.removeListener(r,s)),tt(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),tt(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"update",async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"request",async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"find",r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),tt(this,"authenticate",async(r,s)=>{try{return await this.engine.authenticate(r,s)}catch(i){throw this.logger.error(i.message),i}}),tt(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),this.name=t?.name||Z9.name,this.metadata=ece(t?.metadata),this.signConfig=t?.signConfig;const n=d9({logger:t?.logger||Z9.logger,name:this.name});this.logger=n,this.core=t?.core||new b2e(t),this.session=new eme(this.core,this.logger),this.proposal=new Q2e(this.core,this.logger),this.pendingRequest=new tme(this.core,this.logger),this.engine=new J2e(this),this.auth=new ame(this.core,this.logger)}static async init(t){const n=new Y9(t);return await n.initialize(),n}get context(){return R2e(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(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}}const ume=Y9;var X9={exports:{}};(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Tn<"u"&&Tn,r=function(){function i(){this.fetch=!1,this.DOMException=n.DOMException}return i.prototype=n,new i}();(function(i){(function(o){var a=typeof i<"u"&&i||typeof self<"u"&&self||typeof Tn<"u"&&Tn||{},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(m){return m&&DataView.prototype.isPrototypeOf(m)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(m){return m&&u.indexOf(Object.prototype.toString.call(m))>-1};function d(m){if(typeof m!="string"&&(m=String(m)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(m)||m==="")throw new TypeError('Invalid character in header field name: "'+m+'"');return m.toLowerCase()}function h(m){return typeof m!="string"&&(m=String(m)),m}function p(m){var b={next:function(){var A=m.shift();return{done:A===void 0,value:A}}};return c.iterable&&(b[Symbol.iterator]=function(){return b}),b}function g(m){this.map={},m instanceof g?m.forEach(function(b,A){this.append(A,b)},this):Array.isArray(m)?m.forEach(function(b){if(b.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+b.length);this.append(b[0],b[1])},this):m&&Object.getOwnPropertyNames(m).forEach(function(b){this.append(b,m[b])},this)}g.prototype.append=function(m,b){m=d(m),b=h(b);var A=this.map[m];this.map[m]=A?A+", "+b:b},g.prototype.delete=function(m){delete this.map[d(m)]},g.prototype.get=function(m){return m=d(m),this.has(m)?this.map[m]:null},g.prototype.has=function(m){return this.map.hasOwnProperty(d(m))},g.prototype.set=function(m,b){this.map[d(m)]=h(b)},g.prototype.forEach=function(m,b){for(var A in this.map)this.map.hasOwnProperty(A)&&m.call(b,this.map[A],A,this)},g.prototype.keys=function(){var m=[];return this.forEach(function(b,A){m.push(A)}),p(m)},g.prototype.values=function(){var m=[];return this.forEach(function(b){m.push(b)}),p(m)},g.prototype.entries=function(){var m=[];return this.forEach(function(b,A){m.push([A,b])}),p(m)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function y(m){if(!m._noBody){if(m.bodyUsed)return Promise.reject(new TypeError("Already read"));m.bodyUsed=!0}}function $(m){return new Promise(function(b,A){m.onload=function(){b(m.result)},m.onerror=function(){A(m.error)}})}function _(m){var b=new FileReader,A=$(b);return b.readAsArrayBuffer(m),A}function x(m){var b=new FileReader,A=$(b),I=/charset=([A-Za-z0-9_-]+)/.exec(m.type),C=I?I[1]:"utf-8";return b.readAsText(m,C),A}function E(m){for(var b=new Uint8Array(m),A=new Array(b.length),I=0;I<b.length;I++)A[I]=String.fromCharCode(b[I]);return A.join("")}function P(m){if(m.slice)return m.slice(0);var b=new Uint8Array(m.byteLength);return b.set(new Uint8Array(m)),b.buffer}function N(){return this.bodyUsed=!1,this._initBody=function(m){this.bodyUsed=this.bodyUsed,this._bodyInit=m,m?typeof m=="string"?this._bodyText=m:c.blob&&Blob.prototype.isPrototypeOf(m)?this._bodyBlob=m:c.formData&&FormData.prototype.isPrototypeOf(m)?this._bodyFormData=m:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)?this._bodyText=m.toString():c.arrayBuffer&&c.blob&&l(m)?(this._bodyArrayBuffer=P(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||f(m))?this._bodyArrayBuffer=P(m):this._bodyText=m=Object.prototype.toString.call(m):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof m=="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(m)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var m=y(this);if(m)return m;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 m=y(this);return m||(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(_);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var m=y(this);if(m)return m;if(this._bodyBlob)return x(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(E(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(L)}),this.json=function(){return this.text().then(JSON.parse)},this}var k=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(m){var b=m.toUpperCase();return k.indexOf(b)>-1?b:m}function T(m,b){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var A=b.body;if(m instanceof T){if(m.bodyUsed)throw new TypeError("Already read");this.url=m.url,this.credentials=m.credentials,b.headers||(this.headers=new g(m.headers)),this.method=m.method,this.mode=m.mode,this.signal=m.signal,!A&&m._bodyInit!=null&&(A=m._bodyInit,m.bodyUsed=!0)}else this.url=String(m);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new g(b.headers)),this.method=R(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||function(){if("AbortController"in a){var O=new AbortController;return O.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")&&(b.cache==="no-store"||b.cache==="no-cache")){var I=/([?&])_=[^&]*/;if(I.test(this.url))this.url=this.url.replace(I,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function L(m){var b=new FormData;return m.trim().split("&").forEach(function(A){if(A){var I=A.split("="),C=I.shift().replace(/\+/g," "),O=I.join("=").replace(/\+/g," ");b.append(decodeURIComponent(C),decodeURIComponent(O))}}),b}function M(m){var b=new g,A=m.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(I){return I.indexOf(`
|
|
40
|
+
***************************************************************************** */var x9=function(e,t){return x9=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},x9(e,t)};function the(e,t){x9(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var $9=function(){return $9=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},$9.apply(this,arguments)};function nhe(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}function rhe(e,t,n,r){var s=arguments.length,i=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(i=(s<3?o(i):s>3?o(t,n,i):o(t,n))||i);return s>3&&i&&Object.defineProperty(t,n,i),i}function she(e,t){return function(n,r){t(n,r,e)}}function ihe(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function ohe(e,t,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(f){o(f)}}function c(u){try{l(r.throw(u))}catch(f){o(f)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function ahe(e,t){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,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(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){n.label=l[1];break}if(l[0]===6&&n.label<i[1]){n.label=i[1],i=l;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(l);break}i[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],s=0}finally{r=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function che(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}function lhe(e,t){for(var n in e)n!=="default"&&!t.hasOwnProperty(n)&&(t[n]=e[n])}function A9(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function mR(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),s,i=[],o;try{for(;(t===void 0||t-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function uhe(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(mR(arguments[t]));return e}function dhe(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),s=0,t=0;t<n;t++)for(var i=arguments[t],o=0,a=i.length;o<a;o++,s++)r[s]=i[o];return r}function Dg(e){return this instanceof Dg?(this.v=e,this):new Dg(e)}function fhe(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){r[d]&&(s[d]=function(h){return new Promise(function(p,g){i.push([d,h,p,g])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(i[0][3],p)}}function c(d){d.value instanceof Dg?Promise.resolve(d.value.v).then(l,u):f(i[0][2],d)}function l(d){a("next",d)}function u(d){a("throw",d)}function f(d,h){d(h),i.shift(),i.length&&a(i[0][0],i[0][1])}}function hhe(e){var t,n;return t={},r("next"),r("throw",function(s){throw s}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(s,i){t[s]=e[s]?function(o){return(n=!n)?{value:Dg(e[s](o)),done:s==="return"}:i?i(o):o}:i}}function phe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof A9=="function"?A9(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=e[i]&&function(o){return new Promise(function(a,c){o=e[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function ghe(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function mhe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function yhe(e){return e&&e.__esModule?e:{default:e}}function bhe(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function whe(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}var vhe=Object.freeze({__proto__:null,__extends:the,get __assign(){return $9},__rest:nhe,__decorate:rhe,__param:she,__metadata:ihe,__awaiter:ohe,__generator:ahe,__createBinding:che,__exportStar:lhe,__values:A9,__read:mR,__spread:uhe,__spreadArrays:dhe,__await:Dg,__asyncGenerator:fhe,__asyncDelegator:hhe,__asyncValues:phe,__makeTemplateObject:ghe,__importStar:mhe,__importDefault:yhe,__classPrivateFieldGet:bhe,__classPrivateFieldSet:whe}),Ehe=w_(vhe),ml={},yR;function xhe(){if(yR)return ml;yR=1,Object.defineProperty(ml,"__esModule",{value:!0}),ml.isBrowserCryptoAvailable=ml.getSubtleCrypto=ml.getBrowerCrypto=void 0;function e(){return Tn?.crypto||Tn?.msCrypto||{}}ml.getBrowerCrypto=e;function t(){const r=e();return r.subtle||r.webkitSubtle}ml.getSubtleCrypto=t;function n(){return!!e()&&!!t()}return ml.isBrowserCryptoAvailable=n,ml}var yl={},bR;function $he(){if(bR)return yl;bR=1,Object.defineProperty(yl,"__esModule",{value:!0}),yl.isBrowser=yl.isNode=yl.isReactNative=void 0;function e(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}yl.isReactNative=e;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}yl.isNode=t;function n(){return!e()&&!t()}return yl.isBrowser=n,yl}(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=Ehe;t.__exportStar(xhe(),e),t.__exportStar($he(),e)})(gR);function Dn(e=3){const t=Date.now()*Math.pow(10,e),n=Math.floor(Math.random()*Math.pow(10,e));return t+n}function Wr(e=6){return BigInt(Dn(e))}function rn(e,t,n){return{id:n||Dn(),jsonrpc:"2.0",method:e,params:t}}function ua(e,t){return{id:e,jsonrpc:"2.0",result:t}}function Rh(e,t,n){return{id:e,jsonrpc:"2.0",error:Ahe(t,n)}}function Ahe(e,t){return typeof e>"u"?hR(dR):(typeof e=="string"&&(e=Object.assign(Object.assign({},hR(E9)),{message:e})),typeof t<"u"&&(e.data=t),Qfe(e.code)&&(e=ehe(e.code)),e)}class Che{}class She extends Che{constructor(){super()}}class Ihe extends She{constructor(t){super()}}const _he="^https?:",Ohe="^wss?:";function Phe(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function wR(e,t){const n=Phe(e);return typeof n>"u"?!1:new RegExp(t).test(n)}function vR(e){return wR(e,_he)}function ER(e){return wR(e,Ohe)}function The(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function xR(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function Dh(e){return xR(e)&&"method"in e}function A0(e){return xR(e)&&(wn(e)||Xt(e))}function wn(e){return"result"in e}function Xt(e){return"error"in e}class Mh extends Ihe{constructor(t){super(t),this.events=new Ot.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async request(t,n){return this.requestStrict(rn(t.method,t.params||[],t.id||Wr().toString()),n)}async requestStrict(t,n){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(i){s(i)}this.events.on(`${t.id}`,i=>{Xt(i)?s(i.error):r(i.result)});try{await this.connection.send(t,n)}catch(i){s(i)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),A0(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const Nhe=()=>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"),Bhe=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",$R=e=>e.split("?")[0],AR=10,khe=Nhe();class CR{constructor(t){if(this.url=t,this.events=new Ot.exports.EventEmitter,this.registering=!1,!ER(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ws(t))}catch(n){this.onError(t.id,n)}}register(t=this.url){if(!ER(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const s=gR.isReactNative()?void 0:{rejectUnauthorized:!The(t)},i=new khe(t,[],s);Bhe()?i.onerror=o=>{const a=o;r(this.emitError(a.error))}:i.on("error",o=>{r(this.emitError(o))}),i.onopen=()=>{this.onOpen(i),n(i)}})}onOpen(t){t.onmessage=n=>this.onPayload(n),t.onclose=n=>this.onClose(n),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;const n=typeof t.data=="string"?sl(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),s=r.message||r.toString(),i=Rh(t,s);this.events.emit("payload",i)}parseError(t,n=this.url){return pR(t,$R(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>AR&&this.events.setMaxListeners(AR)}emitError(t){const n=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${$R(this.url)}`));return this.events.emit("register_error",n),n}}var Rhe=Object.defineProperty,SR=Object.getOwnPropertySymbols,Dhe=Object.prototype.hasOwnProperty,Mhe=Object.prototype.propertyIsEnumerable,IR=(e,t,n)=>t in e?Rhe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kr=(e,t)=>{for(var n in t||(t={}))Dhe.call(t,n)&&IR(e,n,t[n]);if(SR)for(var n of SR(t))Mhe.call(t,n)&&IR(e,n,t[n]);return e};const _R="wc",OR=2,c6="core",da=`${_R}@2:${c6}:`,Uhe={name:c6,logger:"error"},Lhe={database:":memory:"},Fhe="crypto",PR="client_ed25519_seed",jhe=Q.ONE_DAY,zhe="keychain",Hhe="0.3",Vhe="messages",qhe="0.3",Zhe=Q.SIX_HOURS,Whe="publisher",TR="irn",Khe="error",NR="wss://relay.walletconnect.org",Ghe="relayer",sn={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"},Yhe="_subscription",Mi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Xhe=.1,C9="2.22.4",Lt={link_mode:"link_mode",relay:"relay"},l6={inbound:"inbound",outbound:"outbound"},Jhe="0.3",Qhe="WALLETCONNECT_CLIENT_ID",BR="WALLETCONNECT_LINK_MODE_APPS",di={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},e1e="subscription",t1e="0.3",n1e="pairing",r1e="0.3",Mg={wc_pairingDelete:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Q.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Q.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:0},res:{ttl:Q.ONE_DAY,prompt:!1,tag:0}}},C0={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xo={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},s1e="history",i1e="0.3",o1e="expirer",Ui={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},a1e="0.3",c1e="verify-api",l1e="https://verify.walletconnect.com",kR="https://verify.walletconnect.org",Ug=kR,u1e=`${Ug}/v3`,d1e=[l1e,kR],f1e="echo",h1e="https://echo.walletconnect.com",fa={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"},bl={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"},$o={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},S0={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},I0={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"},Lg={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"},p1e=.1,g1e="event-client",m1e=86400,y1e="https://pulse.walletconnect.org/batch";function b1e(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(n[o]!==255)throw new TypeError(i+" is ambiguous");n[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(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,y=0,$=0,_=p.length;$!==_&&p[$]===0;)$++,g++;for(var x=(_-$)*u+1>>>0,E=new Uint8Array(x);$!==_;){for(var P=p[$],N=0,k=x-1;(P!==0||N<y)&&k!==-1;k--,N++)P+=256*E[k]>>>0,E[k]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");y=N,$++}for(var R=x-y;R!==x&&E[R]===0;)R++;for(var T=c.repeat(g);R<x;++R)T+=e.charAt(E[R]);return T}function d(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 y=0,$=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,x=new Uint8Array(_);p[g];){var E=n[p.charCodeAt(g)];if(E===255)return;for(var P=0,N=_-1;(E!==0||P<$)&&N!==-1;N--,P++)E+=a*x[N]>>>0,x[N]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");$=P,g++}if(p[g]!==" "){for(var k=_-$;k!==_&&x[k]===0;)k++;for(var R=new Uint8Array(y+(_-k)),T=y;k!==_;)R[T++]=x[k++];return R}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var w1e=b1e,v1e=w1e;const RR=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},E1e=e=>new TextEncoder().encode(e),x1e=e=>new TextDecoder().decode(e);class $1e{constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class A1e{constructor(t,n,r){if(this.name=t,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return DR(this,t)}}class C1e{constructor(t){this.decoders=t}or(t){return DR(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const DR=(e,t)=>new C1e(Kr(Kr({},e.decoders||{[e.prefix]:e}),t.decoders||{[t.prefix]:t}));class S1e{constructor(t,n,r,s){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new $1e(t,n,r),this.decoder=new A1e(t,n,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const u6=({name:e,prefix:t,encode:n,decode:r})=>new S1e(e,t,n,r),Fg=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:s}=v1e(n,t);return u6({prefix:e,name:t,encode:r,decode:i=>RR(s(i))})},I1e=(e,t,n,r)=>{const s={};for(let u=0;u<t.length;++u)s[t[u]]=u;let i=e.length;for(;e[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const f=s[e[u]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},_1e=(e,t,n)=>{const r=t[t.length-1]==="=",s=(1<<n)-1;let i="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,i+=t[s&a>>o];if(o&&(i+=t[s&a<<n-o]),r)for(;i.length*n&7;)i+="=";return i},Xn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>u6({prefix:t,name:e,encode(s){return _1e(s,r,n)},decode(s){return I1e(s,r,n,e)}}),O1e=u6({prefix:"\0",name:"identity",encode:e=>x1e(e),decode:e=>E1e(e)});var P1e=Object.freeze({__proto__:null,identity:O1e});const T1e=Xn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var N1e=Object.freeze({__proto__:null,base2:T1e});const B1e=Xn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var k1e=Object.freeze({__proto__:null,base8:B1e});const R1e=Fg({prefix:"9",name:"base10",alphabet:"0123456789"});var D1e=Object.freeze({__proto__:null,base10:R1e});const M1e=Xn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),U1e=Xn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var L1e=Object.freeze({__proto__:null,base16:M1e,base16upper:U1e});const F1e=Xn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),j1e=Xn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),z1e=Xn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H1e=Xn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V1e=Xn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),q1e=Xn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Z1e=Xn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),W1e=Xn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),K1e=Xn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var G1e=Object.freeze({__proto__:null,base32:F1e,base32upper:j1e,base32pad:z1e,base32padupper:H1e,base32hex:V1e,base32hexupper:q1e,base32hexpad:Z1e,base32hexpadupper:W1e,base32z:K1e});const Y1e=Fg({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),X1e=Fg({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J1e=Object.freeze({__proto__:null,base36:Y1e,base36upper:X1e});const Q1e=Fg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),epe=Fg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tpe=Object.freeze({__proto__:null,base58btc:Q1e,base58flickr:epe});const npe=Xn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rpe=Xn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),spe=Xn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ipe=Xn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ope=Object.freeze({__proto__:null,base64:npe,base64pad:rpe,base64url:spe,base64urlpad:ipe});const MR=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}"),ape=MR.reduce((e,t,n)=>(e[n]=t,e),[]),cpe=MR.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function lpe(e){return e.reduce((t,n)=>(t+=ape[n],t),"")}function upe(e){const t=[];for(const n of e){const r=cpe[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const dpe=u6({prefix:"\u{1F680}",name:"base256emoji",encode:lpe,decode:upe});var fpe=Object.freeze({__proto__:null,base256emoji:dpe}),hpe=LR,UR=128,ppe=127,gpe=~ppe,mpe=Math.pow(2,31);function LR(e,t,n){t=t||[],n=n||0;for(var r=n;e>=mpe;)t[n++]=e&255|UR,e/=128;for(;e&gpe;)t[n++]=e&255|UR,e>>>=7;return t[n]=e|0,LR.bytes=n-r+1,t}var ype=S9,bpe=128,FR=127;function S9(e,r){var n=0,r=r||0,s=0,i=r,o,a=e.length;do{if(i>=a)throw S9.bytes=0,new RangeError("Could not decode varint");o=e[i++],n+=s<28?(o&FR)<<s:(o&FR)*Math.pow(2,s),s+=7}while(o>=bpe);return S9.bytes=i-r,n}var wpe=Math.pow(2,7),vpe=Math.pow(2,14),Epe=Math.pow(2,21),xpe=Math.pow(2,28),$pe=Math.pow(2,35),Ape=Math.pow(2,42),Cpe=Math.pow(2,49),Spe=Math.pow(2,56),Ipe=Math.pow(2,63),_pe=function(e){return e<wpe?1:e<vpe?2:e<Epe?3:e<xpe?4:e<$pe?5:e<Ape?6:e<Cpe?7:e<Spe?8:e<Ipe?9:10},Ope={encode:hpe,decode:ype,encodingLength:_pe},jR=Ope;const zR=(e,t,n=0)=>(jR.encode(e,t,n),t),HR=e=>jR.encodingLength(e),I9=(e,t)=>{const n=t.byteLength,r=HR(e),s=r+HR(n),i=new Uint8Array(s+n);return zR(e,i,0),zR(n,i,r),i.set(t,s),new Ppe(e,n,t,i)};class Ppe{constructor(t,n,r,s){this.code=t,this.size=n,this.digest=r,this.bytes=s}}const VR=({name:e,code:t,encode:n})=>new Tpe(e,t,n);class Tpe{constructor(t,n,r){this.name=t,this.code=n,this.encode=r}digest(t){if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?I9(this.code,n):n.then(r=>I9(this.code,r))}else throw Error("Unknown type, must be binary type")}}const qR=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Npe=VR({name:"sha2-256",code:18,encode:qR("SHA-256")}),Bpe=VR({name:"sha2-512",code:19,encode:qR("SHA-512")});var kpe=Object.freeze({__proto__:null,sha256:Npe,sha512:Bpe});const ZR=0,Rpe="identity",WR=RR;var Dpe=Object.freeze({__proto__:null,identity:{code:ZR,name:Rpe,encode:WR,digest:e=>I9(ZR,WR(e))}});new TextEncoder,new TextDecoder;const KR=Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr({},P1e),N1e),k1e),D1e),L1e),G1e),J1e),tpe),ope),fpe);Kr(Kr({},kpe),Dpe);function GR(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Mpe(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?GR(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function YR(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const XR=YR("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),_9=YR("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=Mpe(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Upe=Kr({utf8:XR,"utf-8":XR,hex:KR.base16,latin1:_9,ascii:_9,binary:_9},KR);function Lpe(e,t="utf8"){const n=Upe[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?GR(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}var Fpe=Object.defineProperty,jpe=(e,t,n)=>t in e?Fpe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ha=(e,t,n)=>jpe(e,typeof t!="symbol"?t+"":t,n);class zpe{constructor(t,n){this.core=t,this.logger=n,ha(this,"keychain",new Map),ha(this,"name",zhe),ha(this,"version",Hhe),ha(this,"initialized",!1),ha(this,"storagePrefix",da),ha(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ha(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ha(this,"set",async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()}),ha(this,"get",r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:i}=pe("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(i)}return s}),ha(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=t,this.logger=ui(n,this.name)}get context(){return li(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,CE(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?SE(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Hpe=Object.defineProperty,Vpe=(e,t,n)=>t in e?Hpe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t,n)=>Vpe(e,typeof t!="symbol"?t+"":t,n);class qpe{constructor(t,n,r){this.core=t,this.logger=n,Mn(this,"name",Fhe),Mn(this,"keychain"),Mn(this,"randomSessionIdentifier",i9()),Mn(this,"initialized",!1),Mn(this,"clientId"),Mn(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Mn(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Mn(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),i=bw(s),o=lE(i.publicKey);return this.clientId=o,o}),Mn(this,"generateKeyPair",()=>{this.isInitialized();const s=que();return this.setPrivateKey(s.publicKey,s.privateKey)}),Mn(this,"signJWT",async s=>{this.isInitialized();const i=await this.getClientSeed(),o=bw(i),a=this.randomSessionIdentifier;return await tN(a,s,jhe,o)}),Mn(this,"generateSharedKey",(s,i,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=Zue(a,i);return this.setSymKey(c,o)}),Mn(this,"setSymKey",async(s,i)=>{this.isInitialized();const o=i||Ww(s);return await this.keychain.set(o,s),o}),Mn(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Mn(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Mn(this,"encode",async(s,i,o)=>{this.isInitialized();const a=Ok(o),c=ws(i);if(Tk(a))return Gue(c,o?.encoding);if(Pk(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;s=await this.generateSharedKey(d,h)}const l=this.getSymKey(s),{type:u,senderPublicKey:f}=a;return Wue({type:u,symKey:l,message:c,senderPublicKey:f,encoding:o?.encoding})}),Mn(this,"decode",async(s,i,o)=>{this.isInitialized();const a=Xue(i,o);if(Tk(a)){const c=Yue(i,o?.encoding);return sl(c)}if(Pk(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=Kue({symKey:c,encoded:i,encoding:o?.encoding});return sl(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Mn(this,"getPayloadType",(s,i=$s)=>{const o=Tg({encoded:s,encoding:i});return E0(o.type)}),Mn(this,"getPayloadSenderPublicKey",(s,i=$s)=>{const o=Tg({encoded:s,encoding:i});return o.senderPublicKey?St(o.senderPublicKey,Zr):void 0}),this.core=t,this.logger=ui(n,this.name),this.keychain=r||new zpe(this.core,this.logger)}get context(){return li(this.logger)}async setPrivateKey(t,n){return await this.keychain.set(t,n),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(PR)}catch{t=i9(),await this.keychain.set(PR,t)}return Lpe(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Zpe=Object.defineProperty,Wpe=Object.defineProperties,Kpe=Object.getOwnPropertyDescriptors,JR=Object.getOwnPropertySymbols,Gpe=Object.prototype.hasOwnProperty,Ype=Object.prototype.propertyIsEnumerable,O9=(e,t,n)=>t in e?Zpe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Xpe=(e,t)=>{for(var n in t||(t={}))Gpe.call(t,n)&&O9(e,n,t[n]);if(JR)for(var n of JR(t))Ype.call(t,n)&&O9(e,n,t[n]);return e},Jpe=(e,t)=>Wpe(e,Kpe(t)),fi=(e,t,n)=>O9(e,typeof t!="symbol"?t+"":t,n);class Qpe extends Rfe{constructor(t,n){super(t,n),this.logger=t,this.core=n,fi(this,"messages",new Map),fi(this,"messagesWithoutClientAck",new Map),fi(this,"name",Vhe),fi(this,"version",qhe),fi(this,"initialized",!1),fi(this,"storagePrefix",da),fi(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),fi(this,"set",async(r,s,i)=>{this.isInitialized();const o=Ri(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),i===l6.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,Jpe(Xpe({},c),{[o]:s}))}return await this.persist(),o}),fi(this,"get",r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s}),fi(this,"getWithoutAck",r=>{this.isInitialized();const s={};for(const i of r){const o=this.messagesWithoutClientAck.get(i)||{};s[i]=Object.values(o)}return s}),fi(this,"has",(r,s)=>{this.isInitialized();const i=this.get(r),o=Ri(s);return typeof i[o]<"u"}),fi(this,"ack",async(r,s)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(r);if(typeof i>"u")return;const o=Ri(s);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,i),await this.persist()}),fi(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=ui(t,this.name),this.core=n}get context(){return li(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(t){await this.core.storage.setItem(this.storageKey,CE(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,CE(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?SE(t):void 0}async getRelayerMessagesWithoutClientAck(){const t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?SE(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var ege=Object.defineProperty,tge=Object.defineProperties,nge=Object.getOwnPropertyDescriptors,QR=Object.getOwnPropertySymbols,rge=Object.prototype.hasOwnProperty,sge=Object.prototype.propertyIsEnumerable,P9=(e,t,n)=>t in e?ege(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Uh=(e,t)=>{for(var n in t||(t={}))rge.call(t,n)&&P9(e,n,t[n]);if(QR)for(var n of QR(t))sge.call(t,n)&&P9(e,n,t[n]);return e},eD=(e,t)=>tge(e,nge(t)),Li=(e,t,n)=>P9(e,typeof t!="symbol"?t+"":t,n);class ige extends Dfe{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Li(this,"events",new Ot.exports.EventEmitter),Li(this,"name",Whe),Li(this,"queue",new Map),Li(this,"publishTimeout",Q.toMiliseconds(Q.ONE_MINUTE)),Li(this,"initialPublishTimeout",Q.toMiliseconds(Q.ONE_SECOND*15)),Li(this,"needsTransportRestart",!1),Li(this,"publish",async(r,s,i)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:i}});const f=i?.ttl||Zhe,d=i?.prompt||!1,h=i?.tag||0,p=i?.id||Wr().toString(),g=Th(Kw().protocol),y={id:p,method:i?.publishMethod||g.publish,params:Uh({topic:r,message:s,ttl:f,prompt:d,tag:h,attestation:i?.attestation},i?.tvf)},$=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{bn((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),bn((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const _=new Promise(async x=>{const E=({id:N})=>{var k;((k=y.id)==null?void 0:k.toString())===N.toString()&&(this.removeRequestFromQueue(N),this.relayer.events.removeListener(sn.publish,E),x())};this.relayer.events.on(sn.publish,E);const P=sa(new Promise((N,k)=>{this.rpcPublish(y,i).then(N).catch(R=>{this.logger.warn(R,R?.message),k(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await P,this.events.removeListener(sn.publish,E)}catch(N){this.queue.set(p,{request:y,opts:i,attempt:1}),this.logger.warn(N,N?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:s,opts:i}}),await sa(_,this.publishTimeout,$)}catch(_){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(_),(u=i?.internal)!=null&&u.throwOnFailedPublish)throw _}finally{this.queue.delete(p)}}),Li(this,"publishCustom",async r=>{var s,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:f,tvf:d,publishMethod:h,prompt:p,tag:g,ttl:y=Q.FIVE_MINUTES}=u,$=u.id||Wr().toString(),_=Th(Kw().protocol),x=h||_.publish,E={id:$,method:x,params:Uh(eD(Uh({},l),{ttl:y,prompt:p,tag:g,attestation:f}),d)},P=`Failed to publish custom payload, please try again. id:${$} tag:${g}`;try{bn((s=E.params)==null?void 0:s.prompt)&&((i=E.params)==null||delete i.prompt),bn((o=E.params)==null?void 0:o.tag)&&((a=E.params)==null||delete a.tag);const N=new Promise(async k=>{const R=({id:L})=>{var M;((M=E.id)==null?void 0:M.toString())===L.toString()&&(this.removeRequestFromQueue(L),this.relayer.events.removeListener(sn.publish,R),k())};this.relayer.events.on(sn.publish,R);const T=sa(new Promise((L,M)=>{this.rpcPublish(E,u).then(L).catch(S=>{this.logger.warn(S,S?.message),M(S)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${x} id:${$} tag:${g}`);try{await T,this.events.removeListener(sn.publish,R)}catch(L){this.queue.set($,{request:E,opts:u,attempt:1}),this.logger.warn(L,L?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:$,payload:l,opts:u}}),await sa(N,this.publishTimeout,P)}catch(N){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(N),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw N}finally{this.queue.delete($)}}),Li(this,"on",(r,s)=>{this.events.on(r,s)}),Li(this,"once",(r,s)=>{this.events.once(r,s)}),Li(this,"off",(r,s)=>{this.events.off(r,s)}),Li(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.relayer=t,this.logger=ui(n,this.name),this.registerEventListeners()}get context(){return li(this.logger)}async rpcPublish(t,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});const r=await this.relayer.request(t);return this.relayer.events.emit(sn.publish,Uh(Uh({},t),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,n)=>{var r;const s=t.attempt+1;this.queue.set(n,eD(Uh({},t),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(r=t.request.params)==null?void 0:r.tag}, attempt: ${s}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(ci.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(sn.connection_stalled);return}this.checkQueue()}),this.relayer.on(sn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}var oge=Object.defineProperty,age=(e,t,n)=>t in e?oge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lh=(e,t,n)=>age(e,typeof t!="symbol"?t+"":t,n);class cge{constructor(){Lh(this,"map",new Map),Lh(this,"set",(t,n)=>{const r=this.get(t);this.exists(t,n)||this.map.set(t,[...r,n])}),Lh(this,"get",t=>this.map.get(t)||[]),Lh(this,"exists",(t,n)=>this.get(t).includes(n)),Lh(this,"delete",(t,n)=>{if(typeof n>"u"){this.map.delete(t);return}if(!this.map.has(t))return;const r=this.get(t);if(!this.exists(t,n))return;const s=r.filter(i=>i!==n);if(!s.length){this.map.delete(t);return}this.map.set(t,s)}),Lh(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var lge=Object.defineProperty,uge=Object.defineProperties,dge=Object.getOwnPropertyDescriptors,tD=Object.getOwnPropertySymbols,fge=Object.prototype.hasOwnProperty,hge=Object.prototype.propertyIsEnumerable,T9=(e,t,n)=>t in e?lge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,jg=(e,t)=>{for(var n in t||(t={}))fge.call(t,n)&&T9(e,n,t[n]);if(tD)for(var n of tD(t))hge.call(t,n)&&T9(e,n,t[n]);return e},N9=(e,t)=>uge(e,dge(t)),Tt=(e,t,n)=>T9(e,typeof t!="symbol"?t+"":t,n);class pge extends Lfe{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Tt(this,"subscriptions",new Map),Tt(this,"topicMap",new cge),Tt(this,"events",new Ot.exports.EventEmitter),Tt(this,"name",e1e),Tt(this,"version",t1e),Tt(this,"pending",new Map),Tt(this,"cached",[]),Tt(this,"initialized",!1),Tt(this,"storagePrefix",da),Tt(this,"subscribeTimeout",Q.toMiliseconds(Q.ONE_MINUTE)),Tt(this,"initialSubscribeTimeout",Q.toMiliseconds(Q.ONE_SECOND*15)),Tt(this,"clientId"),Tt(this,"batchSubscribeTopicsLimit",500),Tt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Tt(this,"subscribe",async(r,s)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const o=Kw(s),a={topic:r,relay:o,transportType:s?.transportType};(i=s?.internal)!=null&&i.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Tt(this,"unsubscribe",async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)}),Tt(this,"isSubscribed",r=>new Promise(s=>{s(this.topicMap.topics.includes(r))})),Tt(this,"isKnownTopic",r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(i=>i.topic===r))})),Tt(this,"on",(r,s)=>{this.events.on(r,s)}),Tt(this,"once",(r,s)=>{this.events.once(r,s)}),Tt(this,"off",(r,s)=>{this.events.off(r,s)}),Tt(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),Tt(this,"start",async()=>{await this.onConnect()}),Tt(this,"stop",async()=>{await this.onDisconnect()}),Tt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Tt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)}),Tt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ci.pulse,async()=>{await this.checkPending()}),this.events.on(di.created,async r=>{const s=di.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(di.deleted,async r=>{const s=di.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})}),this.relayer=t,this.logger=ui(n,this.name),this.clientId=""}get context(){return li(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(t,n){let r=!1;try{r=this.getSubscription(t).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,n){const r=this.topicMap.get(t);await Promise.all(r.map(async s=>await this.unsubscribeById(t,s,n)))}async unsubscribeById(t,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}});try{const s=Kw(r);await this.restartToComplete({topic:t,id:n,relay:s}),await this.rpcUnsubscribe(t,n,s);const i=Ut("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,n,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(t,n,r){var s,i;const o=await this.getSubscriptionId(t);if((s=r?.internal)!=null&&s.skipSubscribe)return o;(!r||r?.transportType===Lt.relay)&&await this.restartToComplete({topic:t,id:t,relay:n});const a={method:Th(n.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=r?.internal)==null?void 0:i.throwOnFailedPublish;try{if(r?.transportType===Lt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},Q.toMiliseconds(Q.ONE_SECOND)),o;const l=new Promise(async f=>{const d=h=>{h.topic===t&&(this.events.removeListener(di.created,d),f(h.id))};this.events.on(di.created,d);try{const h=await sa(new Promise((p,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(di.created,d),f(h)}catch{}}),u=await sa(l,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(sn.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(t){if(!t.length)return;const n=t[0].relay,r={method:Th(n.protocol).batchSubscribe,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await sa(new Promise(s=>{this.relayer.request(r).catch(i=>this.logger.warn(i)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(sn.connection_stalled)}}async rpcBatchFetchMessages(t){if(!t.length)return;const n=t[0].relay,r={method:Th(n.protocol).batchFetchMessages,params:{topics:t.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await sa(new Promise((i,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(sn.connection_stalled)}return s}rpcUnsubscribe(t,n,r){const s={method:Th(r.protocol).unsubscribe,params:{topic:t,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(t,n){this.setSubscription(t,N9(jg({},n),{id:t})),this.pending.delete(n.topic)}onBatchSubscribe(t){t.length&&t.forEach(n=>{this.setSubscription(n.id,jg({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(t,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,t)&&this.deleteSubscription(n,r),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:n}),this.addSubscription(t,n)}addSubscription(t,n){this.subscriptions.set(t,jg({},n)),this.topicMap.set(n.topic,t),this.events.emit(di.created,n)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});const n=this.subscriptions.get(t);if(!n){const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}deleteSubscription(t,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:n});const r=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(r.topic,t),this.events.emit(di.deleted,N9(jg({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(di.sync)}async onRestart(){if(this.cached.length){const t=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const s=t.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(di.resubscribed)}async restore(){try{const t=await this.getRelayerSubscriptions();if(typeof t>"u"||!t.length)return;if(this.subscriptions.size&&!t.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){t.length&&(await this.rpcBatchSubscribe(t),this.onBatchSubscribe(await Promise.all(t.map(async n=>N9(jg({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);const n=await this.rpcBatchFetchMessages(t);n&&n.messages&&(await hce(Q.toMiliseconds(Q.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Ri(t+await this.getClientId())}}var gge=Object.defineProperty,nD=Object.getOwnPropertySymbols,mge=Object.prototype.hasOwnProperty,yge=Object.prototype.propertyIsEnumerable,B9=(e,t,n)=>t in e?gge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,rD=(e,t)=>{for(var n in t||(t={}))mge.call(t,n)&&B9(e,n,t[n]);if(nD)for(var n of nD(t))yge.call(t,n)&&B9(e,n,t[n]);return e},lt=(e,t,n)=>B9(e,typeof t!="symbol"?t+"":t,n);class bge extends Mfe{constructor(t){var n;super(t),lt(this,"protocol","wc"),lt(this,"version",2),lt(this,"core"),lt(this,"logger"),lt(this,"events",new Ot.exports.EventEmitter),lt(this,"provider"),lt(this,"messages"),lt(this,"subscriber"),lt(this,"publisher"),lt(this,"name",Ghe),lt(this,"transportExplicitlyClosed",!1),lt(this,"initialized",!1),lt(this,"connectionAttemptInProgress",!1),lt(this,"relayUrl"),lt(this,"projectId"),lt(this,"packageName"),lt(this,"bundleId"),lt(this,"hasExperiencedNetworkDisruption",!1),lt(this,"pingTimeout"),lt(this,"heartBeatTimeout",Q.toMiliseconds(Q.THIRTY_SECONDS+Q.FIVE_SECONDS)),lt(this,"reconnectTimeout"),lt(this,"connectPromise"),lt(this,"reconnectInProgress",!1),lt(this,"requestsInFlight",[]),lt(this,"connectTimeout",Q.toMiliseconds(Q.ONE_SECOND*15)),lt(this,"request",async r=>{var s,i;this.logger.debug("Publishing Request Payload");const o=r.id||Wr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(s=r.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),lt(this,"resetPingTimeout",()=>{Iw()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,s,i,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(i=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null?void 0:i.terminate)==null||o.call(i)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),lt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),lt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(sn.connect)}),lt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),lt(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(sn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),lt(this,"registerProviderListeners",()=>{this.provider.on(Mi.payload,this.onPayloadHandler),this.provider.on(Mi.connect,this.onConnectHandler),this.provider.on(Mi.disconnect,this.onDisconnectHandler),this.provider.on(Mi.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=d9({logger:(n=t.logger)!=null?n:Khe,name:this.name}),this.messages=new Qpe(this.logger,t.core),this.subscriber=new pge(this,this.logger),this.publisher=new ige(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||NR,Xae()?this.packageName=JN():Jae()&&(this.bundleId=JN()),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(t=>this.logger.warn(t,t?.message))}get context(){return li(this.logger)}get connected(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,n,r){this.isInitialized(),await this.publisher.publish(t,n,r),await this.recordMessageEvent({topic:t,message:n,publishedAt:Date.now(),transportType:Lt.relay},l6.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,n){var r,s,i;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(s=n?.internal)==null?void 0:s.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(t))==null?void 0:i[0])||"",c;const l=u=>{u.topic===t&&(this.subscriber.off(di.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(di.created,l)}),new Promise(async(u,f)=>{a=await this.subscriber.subscribe(t,rD({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||a,u()})]),a}async unsubscribe(t,n){this.isInitialized(),await this.subscriber.unsubscribe(t,n)}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await sa(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(t){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(n,r)=>{await this.connect(t).then(n).catch(r).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(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Zk())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=t.sort((r,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(t,n){const{topic:r}=t;if(!n.sessionExists){const s=cn(Q.FIVE_MINUTES),i={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,i)}this.events.emit(sn.message,t),await this.recordMessageEvent(t,l6.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(Mi.disconnect,i),await sa(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(Mi.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Mi.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Mi.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,Q.toMiliseconds(n*1))),n++}}startPingTimeout(){var t,n,r,s,i;if(Iw())try{(n=(t=this.provider)==null?void 0:t.connection)!=null&&n.socket&&((i=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Mh(new CR(rce({sdkVersion:C9,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,n){const{topic:r,message:s}=t;await this.messages.set(r,s,n)}async shouldIgnoreMessageEvent(t){const{topic:n,message:r}=t;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const s=this.messages.has(n,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Dh(t)){if(!t.method.endsWith(Yhe))return;const n=t.params,{topic:r,message:s,publishedAt:i,attestation:o}=n.data,a={topic:r,message:s,publishedAt:i,transportType:Lt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(rD({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else A0(t)&&this.events.emit(sn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,l6.inbound),this.events.emit(sn.message,t))}async acknowledgePayload(t){const n=ua(t.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(Mi.payload,this.onPayloadHandler),this.provider.off(Mi.connect,this.onConnectHandler),this.provider.off(Mi.disconnect,this.onDisconnectHandler),this.provider.off(Mi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await Zk();Yde(async n=>{t!==n&&(t=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ci.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Qde())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(sn.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(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},Q.toMiliseconds(Xhe)))))}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function wge(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function sD(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function iD(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vge="[object RegExp]",Ege="[object String]",xge="[object Number]",$ge="[object Boolean]",oD="[object Arguments]",Age="[object Symbol]",Cge="[object Date]",Sge="[object Map]",Ige="[object Set]",_ge="[object Array]",Oge="[object Function]",Pge="[object ArrayBuffer]",k9="[object Object]",Tge="[object Error]",Nge="[object DataView]",Bge="[object Uint8Array]",kge="[object Uint8ClampedArray]",Rge="[object Uint16Array]",Dge="[object Uint32Array]",Mge="[object BigUint64Array]",Uge="[object Int8Array]",Lge="[object Int16Array]",Fge="[object Int32Array]",jge="[object BigInt64Array]",zge="[object Float32Array]",Hge="[object Float64Array]";function Vge(){}function aD(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function qge(e,t,n){return zg(e,t,void 0,void 0,void 0,void 0,n)}function zg(e,t,n,r,s,i,o){const a=o(e,t,n,r,s,i);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return Hg(e,t,i,o)}return Hg(e,t,i,o)}function Hg(e,t,n,r){if(Object.is(e,t))return!0;let s=iD(e),i=iD(t);if(s===oD&&(s=k9),i===oD&&(i=k9),s!==i)return!1;switch(s){case Ege:return e.toString()===t.toString();case xge:{const c=e.valueOf(),l=t.valueOf();return wge(c,l)}case $ge:case Cge:case Age:return Object.is(e.valueOf(),t.valueOf());case vge:return e.source===t.source&&e.flags===t.flags;case Oge:return e===t}n=n??new Map;const o=n.get(e),a=n.get(t);if(o!=null&&a!=null)return o===t;n.set(e,t),n.set(t,e);try{switch(s){case Sge:{if(e.size!==t.size)return!1;for(const[c,l]of e.entries())if(!t.has(c)||!zg(l,t.get(c),c,e,t,n,r))return!1;return!0}case Ige:{if(e.size!==t.size)return!1;const c=Array.from(e.values()),l=Array.from(t.values());for(let u=0;u<c.length;u++){const f=c[u],d=l.findIndex(h=>zg(f,h,void 0,e,t,n,r));if(d===-1)return!1;l.splice(d,1)}return!0}case _ge:case Bge:case kge:case Rge:case Dge:case Mge:case Uge:case Lge:case Fge:case jge:case zge:case Hge:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c<e.length;c++)if(!zg(e[c],t[c],c,e,t,n,r))return!1;return!0}case Pge:return e.byteLength!==t.byteLength?!1:Hg(new Uint8Array(e),new Uint8Array(t),n,r);case Nge:return e.byteLength!==t.byteLength||e.byteOffset!==t.byteOffset?!1:Hg(new Uint8Array(e),new Uint8Array(t),n,r);case Tge:return e.name===t.name&&e.message===t.message;case k9:{if(!(Hg(e.constructor,t.constructor,n,r)||aD(e)&&aD(t)))return!1;const c=[...Object.keys(e),...sD(e)],l=[...Object.keys(t),...sD(t)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const f=c[u],d=e[f];if(!Object.hasOwn(t,f))return!1;const h=t[f];if(!zg(d,h,f,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Zge(e,t){return qge(e,t,Vge)}var Wge=Object.defineProperty,cD=Object.getOwnPropertySymbols,Kge=Object.prototype.hasOwnProperty,Gge=Object.prototype.propertyIsEnumerable,R9=(e,t,n)=>t in e?Wge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lD=(e,t)=>{for(var n in t||(t={}))Kge.call(t,n)&&R9(e,n,t[n]);if(cD)for(var n of cD(t))Gge.call(t,n)&&R9(e,n,t[n]);return e},Ss=(e,t,n)=>R9(e,typeof t!="symbol"?t+"":t,n);class _0 extends Ufe{constructor(t,n,r,s=da,i=void 0){super(t,n,r,s),this.core=t,this.logger=n,this.name=r,Ss(this,"map",new Map),Ss(this,"version",Jhe),Ss(this,"cached",[]),Ss(this,"initialized",!1),Ss(this,"getKey"),Ss(this,"storagePrefix",da),Ss(this,"recentlyDeleted",[]),Ss(this,"recentlyDeletedLimit",200),Ss(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!bn(o)?this.map.set(this.getKey(o),o):Ide(o)?this.map.set(o.id,o):_de(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ss(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())}),Ss(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ss(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Zge(a[c],o[c]))):this.values)),Ss(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=lD(lD({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ss(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=ui(n,this.name),this.storagePrefix=s,this.getKey=i}get context(){return li(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(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){const n=this.map.get(t);if(!n){if(this.recentlyDeleted.includes(t)){const{message:s}=pe("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(s),new Error(s)}const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Yge=Object.defineProperty,Xge=(e,t,n)=>t in e?Yge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,et=(e,t,n)=>Xge(e,typeof t!="symbol"?t+"":t,n);class Jge{constructor(t,n){this.core=t,this.logger=n,et(this,"name",n1e),et(this,"version",r1e),et(this,"events",new Ot.exports),et(this,"pairings"),et(this,"initialized",!1),et(this,"storagePrefix",da),et(this,"ignoredPayloadTypes",[pl]),et(this,"registeredMethods",[]),et(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),et(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),et(this,"create",async r=>{this.isInitialized();const s=i9(),i=await this.core.crypto.setSymKey(s),o=cn(Q.FIVE_MINUTES),a={protocol:TR},c={topic:i,expiry:o,relay:a,active:!1,methods:r?.methods},l=Rk({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(C0.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:r?.transportType,internal:r?.internal}),{topic:i,uri:l}}),et(this,"pair",async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[fa.pairing_started]}});this.isValidPair(r,s);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=kk(r.uri);s.props.properties.topic=i,s.addTrace(fa.pairing_uri_validation_success),s.addTrace(fa.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(i)){if(u=this.pairings.get(i),s.addTrace(fa.existing_pairing),u.active)throw s.setError(bl.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);s.addTrace(fa.pairing_not_expired)}const f=c||cn(Q.FIVE_MINUTES),d={topic:i,relay:a,expiry:f,active:!1,methods:l};this.core.expirer.set(i,f),await this.pairings.set(i,d),s.addTrace(fa.store_new_pairing),r.activatePairing&&await this.activate({topic:i}),this.events.emit(C0.create,d),s.addTrace(fa.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),s.addTrace(fa.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(bl.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(h){throw s.setError(bl.subscribe_pairing_topic_failure),h}return s.addTrace(fa.subscribe_pairing_topic_success),d}),et(this,"activate",async({topic:r})=>{this.isInitialized();const s=cn(Q.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})}),et(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const i=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=g0();this.events.once(gt("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),et(this,"updateExpiry",async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})}),et(this,"updateMetadata",async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})}),et(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),et(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",Ut("USER_DISCONNECTED")),await this.deletePairing(s))}),et(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:s,relay:i,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return Rk({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),et(this,"sendRequest",async(r,s,i)=>{const o=rn(s,i),a=await this.core.crypto.encode(r,o),c=Mg[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),et(this,"sendResult",async(r,s,i)=>{const o=ua(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Mg[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),et(this,"sendError",async(r,s,i)=>{const o=Rh(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Mg[c]?Mg[c].res:Mg.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),et(this,"deletePairing",async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Ut("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])}),et(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(s=>ia(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))}),et(this,"onRelayEventRequest",async r=>{const{topic:s,payload:i}=r;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,i);default:return await this.onUnknownRpcMethodRequest(s,i)}}),et(this,"onRelayEventResponse",async r=>{const{topic:s,payload:i}=r,o=(await this.core.history.get(s,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,i);default:return this.onUnknownRpcMethodResponse(o)}}),et(this,"onPairingPingRequest",async(r,s)=>{const{id:i}=s;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.events.emit(C0.ping,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}}),et(this,"onPairingPingResponse",(r,s)=>{const{id:i}=s;setTimeout(()=>{wn(s)?this.events.emit(gt("pairing_ping",i),{}):Xt(s)&&this.events.emit(gt("pairing_ping",i),{error:s.error})},500)}),et(this,"onPairingDeleteRequest",async(r,s)=>{const{id:i}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(C0.delete,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}}),et(this,"onUnknownRpcMethodRequest",async(r,s)=>{const{id:i,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=Ut("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,r,a),this.logger.error(a)}catch(a){await this.sendError(i,r,a),this.logger.error(a)}}),et(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Ut("WC_METHOD_UNSUPPORTED",r))}),et(this,"isValidPair",(r,s)=>{var i;if(!As(r)){const{message:a}=pe("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(bl.malformed_pairing_uri),new Error(a)}if(!Sde(r.uri)){const{message:a}=pe("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(bl.malformed_pairing_uri),new Error(a)}const o=kk(r?.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:a}=pe("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(bl.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=pe("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(bl.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&Q.toMiliseconds(o?.expiryTimestamp)<Date.now()){s.setError(bl.pairing_expired);const{message:a}=pe("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),et(this,"isValidPing",async r=>{if(!As(r)){const{message:i}=pe("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)}),et(this,"isValidDisconnect",async r=>{if(!As(r)){const{message:i}=pe("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)}),et(this,"isValidPairingTopic",async r=>{if(!ln(r,!1)){const{message:s}=pe("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=pe("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(ia(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=pe("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}}),this.core=t,this.logger=ui(n,this.name),this.pairings=new _0(this.core,this.logger,this.name,this.storagePrefix)}get context(){return li(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(sn.message,async t=>{const{topic:n,message:r,transportType:s}=t;if(this.pairings.keys.includes(n)&&s!==Lt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const i=await this.core.crypto.decode(n,r);Dh(i)?(this.core.history.set(n,i),await this.onRelayEventRequest({topic:n,payload:i})):A0(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:n,payload:i}),this.core.history.delete(n,i.id)),await this.core.relayer.messages.ack(n,r)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(Ui.expired,async t=>{const{topic:n}=nB(t.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(C0.expire,{topic:n}))})}}var Qge=Object.defineProperty,e2e=(e,t,n)=>t in e?Qge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Jn=(e,t,n)=>e2e(e,typeof t!="symbol"?t+"":t,n);class t2e extends kfe{constructor(t,n){super(t,n),this.core=t,this.logger=n,Jn(this,"records",new Map),Jn(this,"events",new Ot.exports.EventEmitter),Jn(this,"name",s1e),Jn(this,"version",i1e),Jn(this,"cached",[]),Jn(this,"initialized",!1),Jn(this,"storagePrefix",da),Jn(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Jn(this,"set",(r,s,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:i}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:i,expiry:cn(Q.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(xo.created,o)}),Jn(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response>"u"&&(s.response=Xt(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(xo.updated,s))}),Jn(this,"get",async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s))),Jn(this,"delete",(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(i=>{if(i.topic===r){if(typeof s<"u"&&i.id!==s)return;this.records.delete(i.id),this.events.emit(xo.deleted,i)}}),this.persist()}),Jn(this,"exists",async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1)),Jn(this,"on",(r,s)=>{this.events.on(r,s)}),Jn(this,"once",(r,s)=>{this.events.once(r,s)}),Jn(this,"off",(r,s)=>{this.events.off(r,s)}),Jn(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=ui(n,this.name)}get context(){return li(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 t=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:rn(n.request.method,n.request.params,n.id),chainId:n.chainId};return t.push(r)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();const n=this.records.get(t);if(!n){const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(xo.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(xo.created,t=>{const n=xo.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(xo.updated,t=>{const n=xo.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(xo.deleted,t=>{const n=xo.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.core.heartbeat.on(ci.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(n=>{Q.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(xo.deleted,n,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var n2e=Object.defineProperty,r2e=(e,t,n)=>t in e?n2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xr=(e,t,n)=>r2e(e,typeof t!="symbol"?t+"":t,n);class s2e extends Ffe{constructor(t,n){super(t,n),this.core=t,this.logger=n,xr(this,"expirations",new Map),xr(this,"events",new Ot.exports.EventEmitter),xr(this,"name",o1e),xr(this,"version",a1e),xr(this,"cached",[]),xr(this,"initialized",!1),xr(this,"storagePrefix",da),xr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),xr(this,"has",r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}}),xr(this,"set",(r,s)=>{this.isInitialized();const i=this.formatTarget(r),o={target:i,expiry:s};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Ui.created,{target:i,expiration:o})}),xr(this,"get",r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)}),xr(this,"del",r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),i=this.getExpiration(s);this.expirations.delete(s),this.events.emit(Ui.deleted,{target:s,expiration:i})}}),xr(this,"on",(r,s)=>{this.events.on(r,s)}),xr(this,"once",(r,s)=>{this.events.once(r,s)}),xr(this,"off",(r,s)=>{this.events.off(r,s)}),xr(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=ui(n,this.name)}get context(){return li(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(t){if(typeof t=="string")return sce(t);if(typeof t=="number")return ice(t);const{message:n}=pe("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(n)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ui.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:n}=pe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){const n=this.expirations.get(t);if(!n){const{message:r}=pe("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(t,n){const{expiry:r}=n;Q.toMiliseconds(r)-Date.now()<=0&&this.expire(t,n)}expire(t,n){this.expirations.delete(t),this.events.emit(Ui.expired,{target:t,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,n)=>this.checkExpiry(n,t))}registerEventListeners(){this.core.heartbeat.on(ci.pulse,()=>this.checkExpirations()),this.events.on(Ui.created,t=>{const n=Ui.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Ui.expired,t=>{const n=Ui.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Ui.deleted,t=>{const n=Ui.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}}var i2e=Object.defineProperty,o2e=(e,t,n)=>t in e?i2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,un=(e,t,n)=>o2e(e,typeof t!="symbol"?t+"":t,n);class a2e extends jfe{constructor(t,n,r){super(t,n,r),this.core=t,this.logger=n,this.store=r,un(this,"name",c1e),un(this,"abortController"),un(this,"isDevEnv"),un(this,"verifyUrlV3",u1e),un(this,"storagePrefix",da),un(this,"version",OR),un(this,"publicKey"),un(this,"fetchPromise"),un(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&Q.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),un(this,"register",async s=>{if(!$h()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=ei(),u=this.startAbortTimer(Q.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",y),l.body.removeChild(g),h("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 y=$=>{if($.data&&typeof $.data=="string")try{const _=JSON.parse($.data);if(_.type==="verify_attestation"){if(vh(_.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),d(_.attestation===null?"":_.attestation)}}catch(_){this.logger.warn(_)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(l){this.logger.warn(l)}return""}),un(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=s;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(vh(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);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(s?.verifyUrl);return this.fetchAttestation(o,c)}),un(this,"fetchAttestation",async(s,i)=>{this.logger.debug(`resolving attestation: ${s} from url: ${i}`);const o=this.startAbortTimer(Q.ONE_SECOND*5),a=await fetch(`${i}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),un(this,"getVerifyUrl",s=>{let i=s||Ug;return d1e.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Ug}`),i=Ug),i}),un(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(Q.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await i.json()}catch(s){this.logger.warn(s)}}),un(this,"persistPublicKey",async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s}),un(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),un(this,"isValidJwtAttestation",async s=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(s,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),un(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),un(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),un(this,"validateAttestation",(s,i)=>{const o=Que(s,i.publicKey),a={hasExpired:Q.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=ui(n,this.name),this.abortController=new AbortController,this.isDevEnv=IE(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return li(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Q.toMiliseconds(t))}}var c2e=Object.defineProperty,l2e=(e,t,n)=>t in e?c2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,uD=(e,t,n)=>l2e(e,typeof t!="symbol"?t+"":t,n);class u2e extends zfe{constructor(t,n){super(t,n),this.projectId=t,this.logger=n,uD(this,"context",f1e),uD(this,"registerDeviceToken",async r=>{const{clientId:s,token:i,notificationType:o,enableEncrypted:a=!1}=r,c=`${h1e}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:i,always_raw:a})})}),this.logger=ui(n,this.context)}}var d2e=Object.defineProperty,dD=Object.getOwnPropertySymbols,f2e=Object.prototype.hasOwnProperty,h2e=Object.prototype.propertyIsEnumerable,D9=(e,t,n)=>t in e?d2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Vg=(e,t)=>{for(var n in t||(t={}))f2e.call(t,n)&&D9(e,n,t[n]);if(dD)for(var n of dD(t))h2e.call(t,n)&&D9(e,n,t[n]);return e},Un=(e,t,n)=>D9(e,typeof t!="symbol"?t+"":t,n);class p2e extends Hfe{constructor(t,n,r=!0){super(t,n,r),this.core=t,this.logger=n,Un(this,"context",g1e),Un(this,"storagePrefix",da),Un(this,"storageVersion",p1e),Un(this,"events",new Map),Un(this,"shouldPersist",!1),Un(this,"init",async()=>{if(!IE())try{const s={eventId:sB(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:eB(this.core.relayer.protocol,this.core.relayer.version,C9)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),Un(this,"createEvent",s=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=sB(),u=this.core.projectId||"",f=Date.now(),d=Vg({eventId:l,timestamp:f,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),Un(this,"getEvent",s=>{const{eventId:i,topic:o}=s;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Vg(Vg({},a),this.setMethods(a.eventId))}),Un(this,"deleteEvent",s=>{const{eventId:i}=s;this.events.delete(i),this.shouldPersist=!0}),Un(this,"setEventListeners",()=>{this.core.heartbeat.on(ci.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{Q.fromMiliseconds(Date.now())-Q.fromMiliseconds(s.timestamp)>m1e&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),Un(this,"setMethods",s=>({addTrace:i=>this.addTrace(s,i),setError:i=>this.setError(s,i)})),Un(this,"addTrace",(s,i)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(i),this.events.set(s,o),this.shouldPersist=!0)}),Un(this,"setError",(s,i)=>{const o=this.events.get(s);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),Un(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Un(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(i=>{this.events.set(i.eventId,Vg(Vg({},i),this.setMethods(i.eventId)))})}catch(s){this.logger.warn(s)}}),Un(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[i,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const i of s)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),Un(this,"sendEvent",async s=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${y1e}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${C9}${i}`,{method:"POST",body:JSON.stringify(s)})}),Un(this,"getAppDomain",()=>QN().url),this.logger=ui(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var g2e=Object.defineProperty,fD=Object.getOwnPropertySymbols,m2e=Object.prototype.hasOwnProperty,y2e=Object.prototype.propertyIsEnumerable,M9=(e,t,n)=>t in e?g2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hD=(e,t)=>{for(var n in t||(t={}))m2e.call(t,n)&&M9(e,n,t[n]);if(fD)for(var n of fD(t))y2e.call(t,n)&&M9(e,n,t[n]);return e},Rt=(e,t,n)=>M9(e,typeof t!="symbol"?t+"":t,n);class U9 extends Pfe{constructor(t){var n;super(t),Rt(this,"protocol",_R),Rt(this,"version",OR),Rt(this,"name",c6),Rt(this,"relayUrl"),Rt(this,"projectId"),Rt(this,"customStoragePrefix"),Rt(this,"events",new Ot.exports.EventEmitter),Rt(this,"logger"),Rt(this,"heartbeat"),Rt(this,"relayer"),Rt(this,"crypto"),Rt(this,"storage"),Rt(this,"history"),Rt(this,"expirer"),Rt(this,"pairing"),Rt(this,"verify"),Rt(this,"echoClient"),Rt(this,"linkModeSupportedApps"),Rt(this,"eventClient"),Rt(this,"initialized",!1),Rt(this,"logChunkController"),Rt(this,"on",(a,c)=>this.events.on(a,c)),Rt(this,"once",(a,c)=>this.events.once(a,c)),Rt(this,"off",(a,c)=>this.events.off(a,c)),Rt(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Rt(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Lt.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||NR,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const s=xfe({level:typeof t?.logger=="string"&&t.logger?t.logger:Uhe.logger,name:c6}),{logger:i,chunkLoggerController:o}=Ife({opts:s,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.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=ui(i,this.name),this.heartbeat=new Jw,this.crypto=new qpe(this,this.logger,t?.keychain),this.history=new t2e(this,this.logger),this.expirer=new s2e(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new Qk(hD(hD({},Lhe),t?.storageOptions)),this.relayer=new bge({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Jge(this,this.logger),this.verify=new a2e(this,this.logger,this.storage),this.echoClient=new u2e(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new p2e(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new U9(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(Qhe,r),n}get context(){return li(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(BR,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(BR)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${t}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(t){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=t.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const b2e=U9;var L9={exports:{}};const pD=Aw;L9.exports=wl;const qg=B2e().console||{},w2e={mapHttpRequest:d6,mapHttpResponse:d6,wrapRequestSerializer:V9,wrapResponseSerializer:V9,wrapErrorSerializer:V9,req:d6,res:d6,err:mD,errWithCause:mD};function Vu(e,t){return e==="silent"?1/0:t.levels.values[e]}const F9=Symbol("pino.logFuncs"),j9=Symbol("pino.hierarchy"),v2e={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function gD(e,t){const n={logger:t,parent:e[j9]};t[j9]=n}function E2e(e,t,n){const r={};t.forEach(s=>{r[s]=n[s]?n[s]:qg[s]||qg[v2e[s]||"log"]||Fh}),e[F9]=r}function x2e(e,t){return Array.isArray(e)?e.filter(function(r){return r!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function wl(e){e=e||{},e.browser=e.browser||{};const t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");const n=e.browser.write||qg;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},s=x2e(e.browser.serialize,r);let i=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(n);l.log||(l.log=Fh),E2e(l,a,n),gD({},l),Object.defineProperty(l,"levelVal",{get:f}),Object.defineProperty(l,"level",{get:d,set:h});const u={transmit:t,serialize:s,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:P2e(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Fh};l.levels=$2e(e),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Fh,l.serializers=r,l._serialize=s,l._stdErrSerialize=i,l.child=function(...g){return p.call(this,u,...g)},t&&(l._logEvent=H9());function f(){return Vu(this.level,this)}function d(){return this._level}function h(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,O0(this,u,l,"error"),O0(this,u,l,"fatal"),O0(this,u,l,"warn"),O0(this,u,l,"info"),O0(this,u,l,"debug"),O0(this,u,l,"trace"),o.forEach(y=>{O0(this,u,l,y)})}function p(g,y,$){if(!y)throw new Error("missing bindings for child Pino");$=$||{},s&&y.serializers&&($.serializers=y.serializers);const _=$.serializers;if(s&&_){var x=Object.assign({},r,_),E=e.browser.serialize===!0?Object.keys(x):s;delete y.serializers,z9([y],E,x,this._stdErrSerialize)}function P(k){this._childLevel=(k._childLevel|0)+1,this.bindings=y,x&&(this.serializers=x,this._serialize=E),t&&(this._logEvent=H9([].concat(k._logEvent.bindings,y)))}P.prototype=this;const N=new P(this);return gD(this,N),N.child=function(...k){return p.call(this,g,...k)},N.level=$.level||this.level,g.onChild(N),N}return l}function $2e(e){const t=e.customLevels||{},n=Object.assign({},wl.levels.values,t),r=Object.assign({},wl.levels.labels,A2e(t));return{values:n,labels:r}}function A2e(e){const t={};return Object.keys(e).forEach(function(n){t[e[n]]=n}),t}wl.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},wl.stdSerializers=w2e,wl.stdTimeFunctions=Object.assign({},{nullTime:yD,epochTime:bD,unixTime:T2e,isoTime:N2e});function C2e(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[j9];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}function O0(e,t,n,r){if(Object.defineProperty(e,r,{value:Vu(e.level,n)>Vu(r,n)?Fh:n[F9][r],writable:!0,enumerable:!0,configurable:!0}),e[r]===Fh){if(!t.transmit)return;const i=t.transmit.level||e.level,o=Vu(i,n);if(Vu(r,n)<o)return}e[r]=I2e(e,t,n,r);const s=C2e(e);s.length!==0&&(e[r]=S2e(s,e[r]))}function S2e(e,t){return function(){return t.apply(this,[...e,...arguments])}}function I2e(e,t,n,r){return function(s){return function(){const o=t.timestamp(),a=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===qg?qg:this;for(var l=0;l<a.length;l++)a[l]=arguments[l];var u=!1;if(t.serialize&&(z9(a,this._serialize,this.serializers,this._stdErrSerialize),u=!0),t.asObject||t.formatters?s.call(c,..._2e(this,r,a,o,t)):s.apply(c,a),t.transmit){const f=t.transmit.level||e._level,d=Vu(f,n),h=Vu(r,n);if(h<d)return;O2e(this,{ts:o,methodLevel:r,methodValue:h,transmitLevel:f,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Vu(e._level,n)},a,u)}}}(e[F9][r])}function _2e(e,t,n,r,s){const{level:i,log:o=f=>f}=s.formatters||{},a=n.slice();let c=a[0];const l={};let u=(e._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),i){const f=i(t,e.levels.values[t]);Object.assign(l,f)}else l.level=e.levels.values[t];if(s.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?pD(a.shift(),a):void 0}else typeof c=="string"&&(c=pD(a.shift(),a));return c!==void 0&&(l[s.messageKey]=c),[o(l)]}}function z9(e,t,n,r){for(const s in e)if(r&&e[s]instanceof Error)e[s]=wl.stdSerializers.err(e[s]);else if(typeof e[s]=="object"&&!Array.isArray(e[s])&&t)for(const i in e[s])t.indexOf(i)>-1&&i in n&&(e[s][i]=n[i](e[s][i]))}function O2e(e,t,n,r=!1){const s=t.send,i=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;r||z9(n,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=i,e._logEvent.messages=n.filter(function(u){return l.indexOf(u)===-1}),e._logEvent.level.label=o,e._logEvent.level.value=a,s(o,e._logEvent,c),e._logEvent=H9(l)}function H9(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function mD(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)t[n]===void 0&&(t[n]=e[n]);return t}function P2e(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?yD:bD}function d6(){return{}}function V9(e){return e}function Fh(){}function yD(){return!1}function bD(){return Date.now()}function T2e(){return Math.round(Date.now()/1e3)}function N2e(){return new Date(Date.now()).toISOString()}function B2e(){function e(t){return typeof t<"u"&&t}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}L9.exports.default=wl,L9.exports.pino=wl;const k2e="custom_context";function R2e(e,t=k2e){return e[t]||""}const wD="wc",vD=2,ED="client",q9=`${wD}@${vD}:${ED}:`,Z9={name:ED,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},xD="WALLETCONNECT_DEEPLINK_CHOICE",D2e="proposal",$D="Proposal expired",M2e="session",jh=Q.SEVEN_DAYS,U2e="engine",Qn={wc_sessionPropose:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Q.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Q.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1119}}},W9={min:Q.FIVE_MINUTES,max:Q.SEVEN_DAYS},pa={idle:"IDLE",active:"ACTIVE"},L2e={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:""}},F2e="request",j2e=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],z2e="wc",H2e="auth",V2e="authKeys",q2e="pairingTopics",Z2e="requests",f6=`${z2e}@${1.5}:${H2e}:`,h6=`${f6}:PUB_KEY`;var W2e=Object.defineProperty,K2e=Object.defineProperties,G2e=Object.getOwnPropertyDescriptors,AD=Object.getOwnPropertySymbols,Y2e=Object.prototype.hasOwnProperty,X2e=Object.prototype.propertyIsEnumerable,K9=(e,t,n)=>t in e?W2e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wt=(e,t)=>{for(var n in t||(t={}))Y2e.call(t,n)&&K9(e,n,t[n]);if(AD)for(var n of AD(t))X2e.call(t,n)&&K9(e,n,t[n]);return e},$r=(e,t)=>K2e(e,G2e(t)),le=(e,t,n)=>K9(e,typeof t!="symbol"?t+"":t,n);class J2e extends Wfe{constructor(t){super(t),le(this,"name",U2e),le(this,"events",new Ot.exports),le(this,"initialized",!1),le(this,"requestQueue",{state:pa.idle,queue:[]}),le(this,"sessionRequestQueue",{state:pa.idle,queue:[]}),le(this,"emittedSessionRequests",new pce({limit:500})),le(this,"requestQueueDelay",Q.ONE_SECOND),le(this,"expectedPairingMethodMap",new Map),le(this,"recentlyDeletedMap",new Map),le(this,"recentlyDeletedLimit",200),le(this,"relayMessageCache",[]),le(this,"pendingSessions",new Map),le(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(Qn)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Q.toMiliseconds(this.requestQueueDelay)))}),le(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=$r(wt({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=Ede(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=s,f,d=!1;try{if(u){const N=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),N}if(!u||!d){const{topic:N,uri:k}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=N,f=k}if(!u){const{message:N}=pe("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(N)}const h=await this.client.core.crypto.generateKeyPair(),p=Qn.wc_sessionPropose.req.ttl||Q.FIVE_MINUTES,g=cn(p),y=$r(wt(wt({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:TR}],proposer:{publicKey:h,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Dn()}),$=gt("session_connect",y.id),{reject:_,resolve:x,done:E}=g0(p,$D),P=({id:N})=>{N===y.id&&(this.client.events.off("proposal_expire",P),this.pendingSessions.delete(y.id),this.events.emit($,{error:{message:$D,code:0}}))};return this.client.events.on("proposal_expire",P),this.events.once($,({error:N,session:k})=>{this.client.events.off("proposal_expire",P),N?_(N):k&&x(k)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:f,approval:E}}),le(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),le(this,"approve",async n=>{var r,s,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[$o.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(T){throw o.setError(S0.no_internet_connection),T}try{await this.isValidProposalId(n?.id)}catch(T){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(S0.proposal_not_found),T}try{await this.isValidApprove(n)}catch(T){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(S0.session_approve_namespace_validation_failure),T}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:f,sessionConfig:d}=n,h=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:y,optionalNamespaces:$}=h;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:$o.session_approve_started,properties:{topic:p,trace:[$o.session_approve_started,$o.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),E=g.publicKey,P=await this.client.core.crypto.generateSharedKey(x,E),N=wt(wt(wt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:x,metadata:this.client.metadata},expiry:cn(jh)},u&&{sessionProperties:u}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),k=Lt.relay;_.addTrace($o.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:k,internal:{skipSubscribe:!0}})}catch(T){throw _.setError(S0.subscribe_session_topic_failure),T}_.addTrace($o.subscribe_session_topic_success);const R=$r(wt({},N),{topic:P,requiredNamespaces:y,optionalNamespaces:$,pairingTopic:p,acknowledged:!1,self:N.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:x,transportType:Lt.relay});await this.client.session.set(P,R),_.addTrace($o.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:h,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:N,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),_.addTrace($o.session_approve_publish_success)}catch(T){throw this.client.logger.error(T),this.client.session.delete(P,Ut("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),T}return this.client.core.eventClient.deleteEvent({eventId:_.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(P,cn(jh)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),le(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:s}=n;let i;try{i=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}i&&await this.sendError({id:r,topic:i,error:s,rpcOpts:Qn.wc_sessionPropose.reject}),await this.deleteProposal(r)}),le(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:s}=n,{done:i,resolve:o,reject:a}=g0(),c=Dn(),l=Wr().toString(),u=this.client.session.get(r).namespaces;return this.events.once(gt("session_update",c),({error:f})=>{f?a(f):o()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:u}),a(f)}),{acknowledged:i}}),le(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,s=Dn(),{done:i,resolve:o,reject:a}=g0();return this.events.once(gt("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,cn(jh)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),le(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:s,topic:i,expiry:o=Qn.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(i);a?.transportType===Lt.relay&&await this.confirmOnlineStateOrThrow();const c=Dn(),l=Wr().toString(),{done:u,resolve:f,reject:d}=g0(o,"Request expired. Please try again.");this.events.once(gt("session_request",c),({error:y,result:$})=>{y?d(y):f($)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:h,params:{request:$r(wt({},s),{expiryTimestamp:cn(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),await u();const g={request:$r(wt({},s),{expiryTimestamp:cn(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:h,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch($=>d($)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),y()}),new Promise(async y=>{var $;if(!(($=a.sessionConfig)!=null&&$.disableDeepLink)){const _=await lce(this.client.core.storage,xD);await oce({id:c,topic:i,wcDeepLink:_})}y()}),u()]).then(y=>y[2])}),le(this,"respond",async n=>{var r,s;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((s=(r=n?.response)==null?void 0:r.id)==null?void 0:s.toString()),trace:[$o.session_request_response_started]}});try{await this.isValidRespond(n)}catch(f){throw i.addTrace(f?.message),i.setError(S0.session_request_response_validation_failure),f}i.addTrace($o.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,l=this.client.session.get(o);l.transportType===Lt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace($o.session_request_response_publish_started),wn(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):Xt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(n)}catch(f){throw i.addTrace(f?.message),i.setError(S0.session_request_response_publish_failure),f}}),le(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=n;if(this.client.session.keys.includes(r)){const s=Dn(),i=Wr().toString(),{done:o,resolve:a,reject:c}=g0();this.events.once(gt("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),le(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:s,chainId:i}=n,o=Wr().toString(),a=Dn();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),le(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:Ut("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=pe("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}}),le(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>Ade(r,n)))),le(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),le(this,"authenticate",async(n,r)=>{var s;this.isInitialized(),this.isValidAuthenticate(n);const i=r&&this.client.core.linkModeSupportedApps.includes(r)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=i?Lt.link_mode:Lt.relay;o===Lt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:f,type:d,exp:h,nbf:p,methods:g=[],expiry:y}=n,$=[...n.resources||[]],{topic:_,uri:x}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:x}});const E=await this.client.core.crypto.generateKeyPair(),P=Ww(E);if(await Promise.all([this.client.auth.authKeys.set(h6,{responseTopic:P,publicKey:E}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:_})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${_}`),g.length>0){const{namespace:C}=cl(a[0]);let O=Ale(C,"request",g);Rw($)&&(O=Sle(O,$.pop())),$.push(O)}const N=y&&y>Qn.wc_sessionAuthenticate.req.ttl?y:Qn.wc_sessionAuthenticate.req.ttl,k={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:$},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:cn(N)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},T={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:cn(Qn.wc_sessionPropose.req.ttl),id:Dn()},{done:L,resolve:M,reject:S}=g0(N,"Request expired"),w=Dn(),v=gt("session_connect",T.id),m=gt("session_request",w),b=async({error:C,session:O})=>{this.events.off(m,A),C?S(C):O&&M({session:O})},A=async C=>{var O,B,D;if(await this.deletePendingAuthRequest(w,{message:"fulfilled",code:0}),C.error){const Z=Ut("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===Z.code?void 0:(this.events.off(v,b),S(C.error.message))}await this.deleteProposal(T.id),this.events.off(v,b);const{cacaos:z,responder:j}=C.result,U=[],V=[];for(const Z of z){await OB({cacao:Z,projectId:this.client.core.projectId})||(this.client.logger.error(Z,"Signature verification failed"),S(Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=Z,fe=Rw(Y.resources),me=[DE(Y.iss)],we=kw(Y.iss);if(fe){const Re=NB(fe),We=BB(fe);U.push(...Re),me.push(...We)}for(const Re of me)V.push(`${Re}:${we}`)}const q=await this.client.core.crypto.generateSharedKey(E,j.publicKey);let X;U.length>0&&(X={topic:q,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:j,controller:j.publicKey,expiry:cn(jh),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:Lk([...new Set(U)],[...new Set(V)]),transportType:o},await this.client.core.relayer.subscribe(q,{transportType:o}),await this.client.session.set(q,X),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:j.metadata}),X=this.client.session.get(q)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(B=j.metadata.redirect)!=null&&B.linkMode&&(D=j.metadata.redirect)!=null&&D.universal&&r&&(this.client.core.addLinkModeSupportedApp(j.metadata.redirect.universal),this.client.session.update(q,{transportType:Lt.link_mode})),M({auths:z,session:X})};this.events.once(v,b),this.events.once(m,A);let I;try{if(i){const C=rn("wc_sessionAuthenticate",k,w);this.client.core.history.set(_,C);const O=await this.client.core.crypto.encode("",C,{type:Og,encoding:ju});I=Gw(r,_,O)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:k,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:w}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:T,expiry:Qn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:T.id})])}catch(C){throw this.events.off(v,b),this.events.off(m,A),C}return await this.setProposal(T.id,T),await this.setAuthRequest(w,{request:$r(wt({},k),{verifyContext:{}}),pairingTopic:_,transportType:o}),{uri:I??x,response:L}}),le(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:s}=n,i=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[I0.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Lg.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw i.setError(Lg.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Lt.relay;a===Lt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Ww(c),f={type:pl,receiverPublicKey:c,senderPublicKey:l},d=[],h=[];for(const y of s){if(!await OB({cacao:y,projectId:this.client.core.projectId})){i.setError(Lg.invalid_cacao);const P=Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:P,encodeOpts:f}),new Error(P.message)}i.addTrace(I0.cacaos_verified);const{p:$}=y,_=Rw($.resources),x=[DE($.iss)],E=kw($.iss);if(_){const P=NB(_),N=BB(_);d.push(...P),x.push(...N)}for(const P of x)h.push(`${P}:${E}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(I0.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:cn(jh),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Lk([...new Set(d)],[...new Set(h)]),transportType:a},i.addTrace(I0.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw i.setError(Lg.subscribe_authenticated_session_topic_failure),y}i.addTrace(I0.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),i.addTrace(I0.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(I0.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw i.setError(Lg.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:g}}),le(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:s}=n,i=this.getPendingAuthRequest(r);if(!i)throw new Error(`Could not find pending auth request with id ${r}`);i.transportType===Lt.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ww(o),l={type:pl,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:l,rpcOpts:Qn.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),le(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:s}=n;return PB(r,s)}),le(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),le(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&i.topic&&i.topic!==r.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),le(this,"deleteSession",async n=>{var r;const{topic:s,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,Ut("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(xD).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===s&&this.deletePendingSessionRequest(l.id,Ut("USER_DISCONNECTED"))}),s===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=pa.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),le(this,"deleteProposal",async(n,r)=>{if(r)try{const s=this.client.proposal.get(n),i=this.client.core.eventClient.getEvent({topic:s.pairingTopic});i?.setError(S0.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Ut("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),le(this,"deletePendingSessionRequest",async(n,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==n),s&&(this.sessionRequestQueue.state=pa.idle,this.client.events.emit("session_request_expire",{id:n}))}),le(this,"deletePendingAuthRequest",async(n,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)])}),le(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),le(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,cn(Qn.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),le(this,"setAuthRequest",async(n,r)=>{const{request:s,pairingTopic:i,transportType:o=Lt.relay}=r;this.client.core.expirer.set(n,s.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:n,pairingTopic:i,verifyContext:s.verifyContext,transportType:o})}),le(this,"setPendingSessionRequest",async n=>{const{id:r,topic:s,params:i,verifyContext:o}=n,a=i.request.expiryTimestamp||cn(Qn.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:i,verifyContext:o})}),le(this,"sendRequest",async n=>{const{topic:r,method:s,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:f,publishOpts:d={}}=n,h=rn(s,i,c);let p;const g=!!u;try{const _=g?ju:$s;p=await this.client.core.crypto.encode(r,h,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),_}let y;if(j2e.includes(s)){const _=Ri(JSON.stringify(h)),x=Ri(p);y=await this.client.core.verify.register({id:x,decryptedId:_})}const $=wt(wt({},Qn[s].req),d);if($.attestation=y,o&&($.ttl=o),a&&($.id=a),this.client.core.history.set(r,h),g){const _=Gw(u,r,p);await global.Linking.openURL(_,this.client.name)}else $.tvf=$r(wt({},f),{correlationId:h.id}),l?($.internal=$r(wt({},$.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,$)):this.client.core.relayer.publish(r,p,$).catch(_=>this.client.logger.error(_));return h.id}),le(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:s}=n,i=rn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,i);const o=await this.client.core.crypto.encode(r.pairingTopic,i,{encoding:$s}),a=Ri(JSON.stringify(i)),c=Ri(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:$r(wt({},s),{publishMethod:"wc_proposeSession",attestation:l})})}),le(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:s,proposal:i,sessionSettleRequest:o,publishOpts:a}=n,c=ua(i.id,s),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:$s}),u=rn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,u,{encoding:$s});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:f},opts:$r(wt({},a),{publishMethod:"wc_approveSession"})})}),le(this,"sendResult",async n=>{const{id:r,topic:s,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=ua(r,i);let u;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?ju:$s;u=await this.client.core.crypto.encode(s,l,$r(wt({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),p}let d,h;try{d=await this.client.core.history.get(s,r);const p=d.request;try{h=this.getTVFParams(r,p.params,i)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),p}if(f){const p=Gw(c,s,u);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=Qn[p].res;g.tvf=$r(wt({},h),{correlationId:r}),o?(g.internal=$r(wt({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,g)):this.client.core.relayer.publish(s,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),le(this,"sendError",async n=>{const{id:r,topic:s,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=Rh(r,i);let u;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?ju:$s;u=await this.client.core.crypto.encode(s,l,$r(wt({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),h}let d;try{d=await this.client.core.history.get(s,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),h}if(f){const h=Gw(c,s,u);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||Qn[h].res;this.client.core.relayer.publish(s,u,p)}await this.client.core.history.resolve(l)}),le(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(s=>{let i=!1;ia(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&n.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{ia(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...n.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])}),le(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),le(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),le(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===pa.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=pa.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=pa.idle}),le(this,"processRequest",async n=>{const{topic:r,payload:s,attestation:i,transportType:o,encryptedId:a}=n,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),le(this,"onRelayEventResponse",async n=>{const{topic:r,payload:s,transportType:i}=n,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),le(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:s}=pe("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),le(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:s}=n,i=this.expectedPairingMethodMap.get(r);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),le(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o}=n,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(bl.proposal_listener_not_found)),this.isValidConnect(wt({},s.params));const u=a.expiryTimestamp||cn(Qn.wc_sessionPropose.req.ttl),f=wt({id:c,pairingTopic:r,expiryTimestamp:u,attestation:i,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:i,hash:Ri(JSON.stringify(s)),encryptedId:o,metadata:f.proposer.metadata});l?.addTrace(fa.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Qn.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),le(this,"onSessionProposeResponse",async(n,r,s)=>{const{id:i}=r;if(wn(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);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(i,{sessionTopic:u,pairingTopic:n,proposalId:i,publicKey:c});const f=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:n})}else if(Xt(r)){await this.deleteProposal(i);const o=gt("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),le(this,"onSessionSettleRequest",async(n,r)=>{const{id:s,params:i}=r;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:f,sessionConfig:d}=r.params,h=[...this.pendingSessions.values()].find(y=>y.sessionTopic===n);if(!h)return this.client.logger.error(`Pending session not found for topic ${n}`);const p=this.client.proposal.get(h.proposalId),g=$r(wt(wt(wt({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:h.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:h.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:Lt.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:h.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(gt("session_connect",h.proposalId),{session:g}),this.pendingSessions.delete(h.proposalId),this.deleteProposal(h.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),le(this,"onSessionSettleResponse",async(n,r)=>{const{id:s}=r;wn(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(gt("session_approve",s),{})):Xt(r)&&(await this.client.session.delete(n,Ut("USER_DISCONNECTED")),this.events.emit(gt("session_approve",s),{error:r.error}))}),le(this,"onSessionUpdateRequest",async(n,r)=>{const{params:s,id:i}=r;try{const o=`${n}_session_update`,a=Ng.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:n,error:Ut("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(wt({topic:n},s));try{Ng.set(o,i),await this.client.session.update(n,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:n,result:!0})}catch(c){throw Ng.delete(o),c}this.client.events.emit("session_update",{id:i,topic:n,params:s})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),le(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),le(this,"onSessionUpdateResponse",(n,r)=>{const{id:s}=r,i=gt("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);wn(r)?this.events.emit(gt("session_update",s),{}):Xt(r)&&this.events.emit(gt("session_update",s),{error:r.error})}),le(this,"onSessionExtendRequest",async(n,r)=>{const{id:s}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,cn(jh)),await this.sendResult({id:s,topic:n,result:!0}),this.client.events.emit("session_extend",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}}),le(this,"onSessionExtendResponse",(n,r)=>{const{id:s}=r,i=gt("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);wn(r)?this.events.emit(gt("session_extend",s),{}):Xt(r)&&this.events.emit(gt("session_extend",s),{error:r.error})}),le(this,"onSessionPingRequest",async(n,r)=>{const{id:s}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:s,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}}),le(this,"onSessionPingResponse",(n,r)=>{const{id:s}=r,i=gt("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);wn(r)?this.events.emit(gt("session_ping",s),{}):Xt(r)&&this.events.emit(gt("session_ping",s),{error:r.error})},500)}),le(this,"onSessionDeleteRequest",async(n,r)=>{const{id:s}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(sn.publish,async()=>{i(await this.deleteSession({topic:n,id:s}))})}),this.sendResult({id:s,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Ut("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),le(this,"onSessionRequest",async n=>{var r,s,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:f,params:d}=a;try{await this.isValidRequest(wt({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Ri(JSON.stringify(rn("wc_sessionRequest",d,f))),encryptedId:l,metadata:h.peer.metadata,transportType:u}),g={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(g),u===Lt.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((s=h.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),le(this,"onSessionRequestResponse",(n,r)=>{const{id:s}=r,i=gt("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);wn(r)?this.events.emit(gt("session_request",s),{result:r.result}):Xt(r)&&this.events.emit(gt("session_request",s),{error:r.error})}),le(this,"onSessionEventRequest",async(n,r)=>{const{id:s,params:i}=r;try{const o=`${n}_session_event_${i.event.name}`,a=Ng.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(wt({topic:n},i)),this.client.events.emit("session_event",{id:s,topic:n,params:i}),Ng.set(o,s)}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),le(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),wn(r)?this.events.emit(gt("session_request",s),{result:r.result}):Xt(r)&&this.events.emit(gt("session_request",s),{error:r.error})}),le(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:s,payload:i,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:f}=i.params,d=await this.getVerifyContext({attestationId:o,hash:Ri(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),h={requester:l,pairingTopic:s,id:i.id,authPayload:u,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(i.id,{request:h,pairingTopic:s,transportType:c}),c===Lt.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:d})}catch(l){this.client.logger.error(l);const u=i.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(i.params.requester.metadata,c),h={type:pl,receiverPublicKey:u,senderPublicKey:f};await this.sendError({id:i.id,topic:s,error:l,encodeOpts:h,rpcOpts:Qn.wc_sessionAuthenticate.autoReject,appLink:d})}}),le(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),le(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=pa.idle,this.processSessionRequestQueue()},Q.toMiliseconds(this.requestQueueDelay))}),le(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===n&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=gt("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(gt("session_request",i.request.id),{error:r})})}),le(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===pa.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),le(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=pa.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),le(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:rn("wc_sessionPropose",$r(wt({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),le(this,"isValidConnect",async n=>{if(!As(n)){const{message:l}=pe("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=n;if(bn(r)||await this.isValidPairingTopic(r),!Dde(c,!0)){const{message:l}=pe("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!bn(s)&&ca(s)!==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(s,"requiredNamespaces")}if(i&&!bn(i)&&ca(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!bn(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!bn(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(i||{}));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)}`)}}),le(this,"validateNamespaces",(n,r)=>{const s=Rde(n,"connect()",r);if(s)throw new Error(s.message)}),le(this,"isValidApprove",async n=>{if(!As(n))throw new Error(pe("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:s,relayProtocol:i,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=c9(s,"approve()");if(l)throw new Error(l.message);const u=Vk(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!ln(i,!0)){const{message:f}=pe("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(f)}if(o&&!bn(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!bn(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(s));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),le(this,"isValidReject",async n=>{if(!As(n)){const{message:i}=pe("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(i)}const{id:r,reason:s}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!Ude(s)){const{message:i}=pe("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}}),le(this,"isValidSessionSettleRequest",n=>{if(!As(n)){const{message:l}=pe("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:s,namespaces:i,expiry:o}=n;if(!zk(r)){const{message:l}=pe("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Ode(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=c9(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ia(o)){const{message:l}=pe("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),le(this,"isValidUpdate",async n=>{if(!As(n)){const{message:c}=pe("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:s}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const i=this.client.session.get(r),o=c9(s,"update()");if(o)throw new Error(o.message);const a=Vk(i.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),le(this,"isValidExtend",async n=>{if(!As(n)){const{message:s}=pe("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(s)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),le(this,"isValidRequest",async n=>{if(!As(n)){const{message:c}=pe("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:s,chainId:i,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Hk(a,i)){const{message:c}=pe("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!Lde(s)){const{message:c}=pe("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!zde(a,i,s.method)){const{message:c}=pe("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!Zde(o,W9)){const{message:c}=pe("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${W9.min} and ${W9.max}`);throw new Error(c)}}),le(this,"isValidRespond",async n=>{var r;if(!As(n)){const{message:a}=pe("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:s,response:i}=n;try{await this.isValidSessionTopic(s)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!Fde(i)){const{message:a}=pe("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(a)}const o=this.client.pendingRequest.get(i.id);if(o.topic!==s){const{message:a}=pe("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${s}`);throw new Error(a)}}),le(this,"isValidPing",async n=>{if(!As(n)){const{message:s}=pe("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),le(this,"isValidEmit",async n=>{if(!As(n)){const{message:a}=pe("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:s,chainId:i}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Hk(o,i)){const{message:a}=pe("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!jde(s)){const{message:a}=pe("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!Hde(o,i,s.name)){const{message:a}=pe("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),le(this,"isValidDisconnect",async n=>{if(!As(n)){const{message:s}=pe("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),le(this,"isValidAuthenticate",n=>{const{chains:r,uri:s,domain:i,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!ln(s,!1))throw new Error("uri is required parameter");if(!ln(i,!1))throw new Error("domain is required parameter");if(!ln(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>cl(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=cl(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),le(this,"getVerifyContext",async n=>{const{attestationId:r,hash:s,encryptedId:i,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Ug,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Lt.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:r,hash:s,encryptedId:i,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}),le(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((s,i)=>{if(s==null){const{message:o}=pe("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(n)[i]}`);throw new Error(o)}})}),le(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),le(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(o)}}}),le(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:s}=pe("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(s)}}),le(this,"isLinkModeEnabled",(n,r)=>{var s,i,o,a,c,l,u,f,d;return!n||r!==Lt.link_mode?!1:((i=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:i.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=n?.redirect)==null?void 0:u.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),le(this,"getAppLinkIfEnabled",(n,r)=>{var s;return this.isLinkModeEnabled(n,r)?(s=n?.redirect)==null?void 0:s.universal:void 0}),le(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=rB(n,"topic")||"",s=decodeURIComponent(rB(n,"wc_ev")||""),i=this.client.session.keys.includes(r);i&&this.client.session.update(r,{transportType:Lt.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:i})}),le(this,"registerLinkModeListeners",async()=>{var n;if(IE()||Iu()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await r.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),le(this,"getTVFParams",(n,r,s)=>{var i,o,a;if(!((i=r.request)!=null&&i.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,s);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),le(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const s=n?.data||((r=n?.[0])==null?void 0:r.data);if(!s.startsWith("0x"))return!1;const i=s.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),le(this,"extractTxHashesFromResult",(n,r)=>{var s;try{if(!r)return[];const i=n.method,o=L2e[i];if(i==="sui_signTransaction")return[ale(r.transactionBytes)];if(i==="near_signTransaction")return[CB(r)];if(i==="near_signTransactions")return r.map(c=>CB(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(s=r.tx_json)==null?void 0:s.hash];if(i==="polkadot_signTransaction")return[a0e({transaction:n.params.transactionPayload,signature:r.signature})];if(i==="algo_signTxn")return Di(r)?r.map(c=>SB(c)):[SB(r)];if(i==="cosmos_signDirect")return[lle(r)];if(i==="wallet_sendCalls")return ule(r);if(typeof r=="string")return[r];const a=r[o.key];if(Di(a))return i==="solana_signAllTransactions"?a.map(c=>ole(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn(i,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const t=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(t);for(const[r,s]of Object.entries(n))for(const i of s)try{await this.onProviderMessageEvent({topic:r,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${i}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:t}=pe("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(sn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){const{topic:n,message:r,attestation:s,transportType:i}=t,{publicKey:o}=this.client.auth.authKeys.keys.includes(h6)?this.client.auth.authKeys.get(h6):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:i===Lt.link_mode?ju:$s});Dh(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:s,transportType:i,encryptedId:Ri(r)})):A0(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:i}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ui.expired,async t=>{const{topic:n,id:r}=nB(t.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,pe("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,pe("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(C0.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(C0.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!ln(t,!1)){const{message:n}=pe("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:n}=pe("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(n)}if(ia(this.client.core.pairing.pairings.get(t).expiry)){const{message:n}=pe("EXPIRED",`pairing topic: ${t}`);throw new Error(n)}}async isValidSessionTopic(t){if(!ln(t,!1)){const{message:n}=pe("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(n)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){const{message:n}=pe("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(n)}if(ia(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});const{message:n}=pe("EXPIRED",`session topic: ${t}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(t)){const{message:n}=pe("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(n)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(ln(t,!1)){const{message:n}=pe("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(n)}else{const{message:n}=pe("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(n)}}async isValidProposalId(t){if(!Mde(t)){const{message:n}=pe("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(n)}if(!this.client.proposal.keys.includes(t)){const{message:n}=pe("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(n)}if(ia(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);const{message:n}=pe("EXPIRED",`proposal id: ${t}`);throw new Error(n)}}}class Q2e extends _0{constructor(t,n){super(t,n,D2e,q9),this.core=t,this.logger=n}}class eme extends _0{constructor(t,n){super(t,n,M2e,q9),this.core=t,this.logger=n}}class tme extends _0{constructor(t,n){super(t,n,F2e,q9,r=>r.id),this.core=t,this.logger=n}}class nme extends _0{constructor(t,n){super(t,n,V2e,f6,()=>h6),this.core=t,this.logger=n}}class rme extends _0{constructor(t,n){super(t,n,q2e,f6),this.core=t,this.logger=n}}class sme extends _0{constructor(t,n){super(t,n,Z2e,f6,r=>r.id),this.core=t,this.logger=n}}var ime=Object.defineProperty,ome=(e,t,n)=>t in e?ime(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G9=(e,t,n)=>ome(e,typeof t!="symbol"?t+"":t,n);class ame{constructor(t,n){this.core=t,this.logger=n,G9(this,"authKeys"),G9(this,"pairingTopics"),G9(this,"requests"),this.authKeys=new nme(this.core,this.logger),this.pairingTopics=new rme(this.core,this.logger),this.requests=new sme(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var cme=Object.defineProperty,lme=(e,t,n)=>t in e?cme(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,tt=(e,t,n)=>lme(e,typeof t!="symbol"?t+"":t,n);class Y9 extends Zfe{constructor(t){super(t),tt(this,"protocol",wD),tt(this,"version",vD),tt(this,"name",Z9.name),tt(this,"metadata"),tt(this,"core"),tt(this,"logger"),tt(this,"events",new Ot.exports.EventEmitter),tt(this,"engine"),tt(this,"session"),tt(this,"proposal"),tt(this,"pendingRequest"),tt(this,"auth"),tt(this,"signConfig"),tt(this,"on",(r,s)=>this.events.on(r,s)),tt(this,"once",(r,s)=>this.events.once(r,s)),tt(this,"off",(r,s)=>this.events.off(r,s)),tt(this,"removeListener",(r,s)=>this.events.removeListener(r,s)),tt(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),tt(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"update",async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"request",async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"find",r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),tt(this,"authenticate",async(r,s)=>{try{return await this.engine.authenticate(r,s)}catch(i){throw this.logger.error(i.message),i}}),tt(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),tt(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),this.name=t?.name||Z9.name,this.metadata=ece(t?.metadata),this.signConfig=t?.signConfig;const n=d9({logger:t?.logger||Z9.logger,name:this.name});this.logger=n,this.core=t?.core||new b2e(t),this.session=new eme(this.core,this.logger),this.proposal=new Q2e(this.core,this.logger),this.pendingRequest=new tme(this.core,this.logger),this.engine=new J2e(this),this.auth=new ame(this.core,this.logger)}static async init(t){const n=new Y9(t);return await n.initialize(),n}get context(){return R2e(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(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}}const ume=Y9;var X9={exports:{}};(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Tn<"u"&&Tn,r=function(){function i(){this.fetch=!1,this.DOMException=n.DOMException}return i.prototype=n,new i}();(function(i){(function(o){var a=typeof i<"u"&&i||typeof self<"u"&&self||typeof Tn<"u"&&Tn||{},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(m){return m&&DataView.prototype.isPrototypeOf(m)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(m){return m&&u.indexOf(Object.prototype.toString.call(m))>-1};function d(m){if(typeof m!="string"&&(m=String(m)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(m)||m==="")throw new TypeError('Invalid character in header field name: "'+m+'"');return m.toLowerCase()}function h(m){return typeof m!="string"&&(m=String(m)),m}function p(m){var b={next:function(){var A=m.shift();return{done:A===void 0,value:A}}};return c.iterable&&(b[Symbol.iterator]=function(){return b}),b}function g(m){this.map={},m instanceof g?m.forEach(function(b,A){this.append(A,b)},this):Array.isArray(m)?m.forEach(function(b){if(b.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+b.length);this.append(b[0],b[1])},this):m&&Object.getOwnPropertyNames(m).forEach(function(b){this.append(b,m[b])},this)}g.prototype.append=function(m,b){m=d(m),b=h(b);var A=this.map[m];this.map[m]=A?A+", "+b:b},g.prototype.delete=function(m){delete this.map[d(m)]},g.prototype.get=function(m){return m=d(m),this.has(m)?this.map[m]:null},g.prototype.has=function(m){return this.map.hasOwnProperty(d(m))},g.prototype.set=function(m,b){this.map[d(m)]=h(b)},g.prototype.forEach=function(m,b){for(var A in this.map)this.map.hasOwnProperty(A)&&m.call(b,this.map[A],A,this)},g.prototype.keys=function(){var m=[];return this.forEach(function(b,A){m.push(A)}),p(m)},g.prototype.values=function(){var m=[];return this.forEach(function(b){m.push(b)}),p(m)},g.prototype.entries=function(){var m=[];return this.forEach(function(b,A){m.push([A,b])}),p(m)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function y(m){if(!m._noBody){if(m.bodyUsed)return Promise.reject(new TypeError("Already read"));m.bodyUsed=!0}}function $(m){return new Promise(function(b,A){m.onload=function(){b(m.result)},m.onerror=function(){A(m.error)}})}function _(m){var b=new FileReader,A=$(b);return b.readAsArrayBuffer(m),A}function x(m){var b=new FileReader,A=$(b),I=/charset=([A-Za-z0-9_-]+)/.exec(m.type),C=I?I[1]:"utf-8";return b.readAsText(m,C),A}function E(m){for(var b=new Uint8Array(m),A=new Array(b.length),I=0;I<b.length;I++)A[I]=String.fromCharCode(b[I]);return A.join("")}function P(m){if(m.slice)return m.slice(0);var b=new Uint8Array(m.byteLength);return b.set(new Uint8Array(m)),b.buffer}function N(){return this.bodyUsed=!1,this._initBody=function(m){this.bodyUsed=this.bodyUsed,this._bodyInit=m,m?typeof m=="string"?this._bodyText=m:c.blob&&Blob.prototype.isPrototypeOf(m)?this._bodyBlob=m:c.formData&&FormData.prototype.isPrototypeOf(m)?this._bodyFormData=m:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)?this._bodyText=m.toString():c.arrayBuffer&&c.blob&&l(m)?(this._bodyArrayBuffer=P(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||f(m))?this._bodyArrayBuffer=P(m):this._bodyText=m=Object.prototype.toString.call(m):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof m=="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(m)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var m=y(this);if(m)return m;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 m=y(this);return m||(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(_);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var m=y(this);if(m)return m;if(this._bodyBlob)return x(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(E(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(L)}),this.json=function(){return this.text().then(JSON.parse)},this}var k=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(m){var b=m.toUpperCase();return k.indexOf(b)>-1?b:m}function T(m,b){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var A=b.body;if(m instanceof T){if(m.bodyUsed)throw new TypeError("Already read");this.url=m.url,this.credentials=m.credentials,b.headers||(this.headers=new g(m.headers)),this.method=m.method,this.mode=m.mode,this.signal=m.signal,!A&&m._bodyInit!=null&&(A=m._bodyInit,m.bodyUsed=!0)}else this.url=String(m);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new g(b.headers)),this.method=R(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||function(){if("AbortController"in a){var O=new AbortController;return O.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")&&(b.cache==="no-store"||b.cache==="no-cache")){var I=/([?&])_=[^&]*/;if(I.test(this.url))this.url=this.url.replace(I,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function L(m){var b=new FormData;return m.trim().split("&").forEach(function(A){if(A){var I=A.split("="),C=I.shift().replace(/\+/g," "),O=I.join("=").replace(/\+/g," ");b.append(decodeURIComponent(C),decodeURIComponent(O))}}),b}function M(m){var b=new g,A=m.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(I){return I.indexOf(`
|
|
41
41
|
`)===0?I.substr(1,I.length):I}).forEach(function(I){var C=I.split(":"),O=C.shift().trim();if(O){var B=C.join(":").trim();try{b.append(O,B)}catch(D){console.warn("Response "+D.message)}}}),b}N.call(T.prototype);function S(m,b){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(b||(b={}),this.type="default",this.status=b.status===void 0?200:b.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=b.statusText===void 0?"":""+b.statusText,this.headers=new g(b.headers),this.url=b.url||"",this._initBody(m)}N.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},S.error=function(){var m=new S(null,{status:200,statusText:""});return m.ok=!1,m.status=0,m.type="error",m};var w=[301,302,303,307,308];S.redirect=function(m,b){if(w.indexOf(b)===-1)throw new RangeError("Invalid status code");return new S(null,{status:b,headers:{location:m}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(b,A){this.message=b,this.name=A;var I=Error(b);this.stack=I.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function v(m,b){return new Promise(function(A,I){var C=new T(m,b);if(C.signal&&C.signal.aborted)return I(new o.DOMException("Aborted","AbortError"));var O=new XMLHttpRequest;function B(){O.abort()}O.onload=function(){var j={statusText:O.statusText,headers:M(O.getAllResponseHeaders()||"")};C.url.indexOf("file://")===0&&(O.status<200||O.status>599)?j.status=200:j.status=O.status,j.url="responseURL"in O?O.responseURL:j.headers.get("X-Request-URL");var U="response"in O?O.response:O.responseText;setTimeout(function(){A(new S(U,j))},0)},O.onerror=function(){setTimeout(function(){I(new TypeError("Network request failed"))},0)},O.ontimeout=function(){setTimeout(function(){I(new TypeError("Network request timed out"))},0)},O.onabort=function(){setTimeout(function(){I(new o.DOMException("Aborted","AbortError"))},0)};function D(j){try{return j===""&&a.location.href?a.location.href:j}catch{return j}}if(O.open(C.method,D(C.url),!0),C.credentials==="include"?O.withCredentials=!0:C.credentials==="omit"&&(O.withCredentials=!1),"responseType"in O&&(c.blob?O.responseType="blob":c.arrayBuffer&&(O.responseType="arraybuffer")),b&&typeof b.headers=="object"&&!(b.headers instanceof g||a.Headers&&b.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(b.headers).forEach(function(j){z.push(d(j)),O.setRequestHeader(j,h(b.headers[j]))}),C.headers.forEach(function(j,U){z.indexOf(U)===-1&&O.setRequestHeader(U,j)})}else C.headers.forEach(function(j,U){O.setRequestHeader(U,j)});C.signal&&(C.signal.addEventListener("abort",B),O.onreadystatechange=function(){O.readyState===4&&C.signal.removeEventListener("abort",B)}),O.send(typeof C._bodyInit>"u"?null:C._bodyInit)})}return v.polyfill=!0,a.fetch||(a.fetch=v,a.Headers=g,a.Request=T,a.Response=S),o.Headers=g,o.Request=T,o.Response=S,o.fetch=v,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var s=n.fetch?n:r;t=s.fetch,t.default=s.fetch,t.fetch=s.fetch,t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response,e.exports=t})(X9,X9.exports);var CD=CX(X9.exports),dme=Object.defineProperty,fme=Object.defineProperties,hme=Object.getOwnPropertyDescriptors,SD=Object.getOwnPropertySymbols,pme=Object.prototype.hasOwnProperty,gme=Object.prototype.propertyIsEnumerable,ID=(e,t,n)=>t in e?dme(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_D=(e,t)=>{for(var n in t||(t={}))pme.call(t,n)&&ID(e,n,t[n]);if(SD)for(var n of SD(t))gme.call(t,n)&&ID(e,n,t[n]);return e},OD=(e,t)=>fme(e,hme(t));const mme={Accept:"application/json","Content-Type":"application/json"},yme="POST",PD={headers:mme,method:yme},TD=10;class p6{constructor(t,n=!1){if(this.url=t,this.disableProviderPing=n,this.events=new Ot.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!vR(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=n}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{const n=ws(t),r=await(await CD(this.url,OD(_D({},PD),{body:n}))).json();this.onPayload({data:r})}catch(n){this.onError(t.id,n)}}async register(t=this.url){if(!vR(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));r()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){const n=ws({id:1,jsonrpc:"2.0",method:"test",params:[]});await CD(t,OD(_D({},PD),{body:n}))}this.onOpen()}catch(n){const r=this.parseError(n);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;const n=typeof t.data=="string"?sl(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),s=r.message||r.toString(),i=Rh(t,s);this.events.emit("payload",i)}parseError(t,n=this.url){return pR(t,n,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>TD&&this.events.setMaxListeners(TD)}}var bme=Object.defineProperty,ND=Object.getOwnPropertySymbols,wme=Object.prototype.hasOwnProperty,vme=Object.prototype.propertyIsEnumerable,BD=(e,t,n)=>t in e?bme(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kD=(e,t)=>{for(var n in t||(t={}))wme.call(t,n)&&BD(e,n,t[n]);if(ND)for(var n of ND(t))vme.call(t,n)&&BD(e,n,t[n]);return e};function J9(e){return e==null||typeof e!="object"&&typeof e!="function"}function RD(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function DD(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Eme="[object RegExp]",MD="[object String]",UD="[object Number]",LD="[object Boolean]",FD="[object Arguments]",xme="[object Symbol]",$me="[object Date]",Ame="[object Map]",Cme="[object Set]",Sme="[object Array]",Ime="[object ArrayBuffer]",_me="[object Object]",Ome="[object DataView]",Pme="[object Uint8Array]",Tme="[object Uint8ClampedArray]",Nme="[object Uint16Array]",Bme="[object Uint32Array]",kme="[object Int8Array]",Rme="[object Int16Array]",Dme="[object Int32Array]",Mme="[object Float32Array]",Ume="[object Float64Array]";function Q9(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Lme(e,t){return zh(e,void 0,e,new Map,t)}function zh(e,t,n,r=new Map,s=void 0){const i=s?.(e,t,n,r);if(i!=null)return i;if(J9(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){const o=new Array(e.length);r.set(e,o);for(let a=0;a<e.length;a++)o[a]=zh(e[a],a,n,r,s);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){const o=new Map;r.set(e,o);for(const[a,c]of e)o.set(a,zh(c,a,n,r,s));return o}if(e instanceof Set){const o=new Set;r.set(e,o);for(const a of e)o.add(zh(a,void 0,n,r,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(Q9(e)){const o=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,o);for(let a=0;a<e.length;a++)o[a]=zh(e[a],a,n,r,s);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,o),P0(o,e,n,r,s),o}if(typeof File<"u"&&e instanceof File){const o=new File([e],e.name,{type:e.type});return r.set(e,o),P0(o,e,n,r,s),o}if(e instanceof Blob){const o=new Blob([e],{type:e.type});return r.set(e,o),P0(o,e,n,r,s),o}if(e instanceof Error){const o=new e.constructor;return r.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,P0(o,e,n,r,s),o}if(typeof e=="object"&&Fme(e)){const o=Object.create(Object.getPrototypeOf(e));return r.set(e,o),P0(o,e,n,r,s),o}return e}function P0(e,t,n=e,r,s){const i=[...Object.keys(t),...RD(t)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(e,a);(c==null||c.writable)&&(e[a]=zh(t[a],a,n,r,s))}}function Fme(e){switch(DD(e)){case FD:case Sme:case Ime:case Ome:case LD:case $me:case Mme:case Ume:case kme:case Rme:case Dme:case Ame:case UD:case _me:case Eme:case Cme:case MD:case xme:case Pme:case Tme:case Nme:case Bme:return!0;default:return!1}}function jme(e,t){return Lme(e,(n,r,s,i)=>{const o=t?.(n,r,s,i);if(o!=null)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case UD:case MD:case LD:{const a=new e.constructor(e?.valueOf());return P0(a,e),a}case FD:{const a={};return P0(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}})}function jD(e){return jme(e)}function zD(e){return e!==null&&typeof e=="object"&&DD(e)==="[object Arguments]"}function HD(e){return typeof e=="object"&&e!==null}function zme(){}function Hme(e){return Q9(e)}function Vme(e){var t;if(typeof e!="object"||e==null)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!=="[object Object]"){const r=e[Symbol.toStringTag];return r==null||!((t=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))!=null&&t.writable)?!1:e.toString()===`[object ${r}]`}let n=e;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}function qme(e){if(J9(e))return e;if(Array.isArray(e)||Q9(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e),n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){const r=new n(e);return r.lastIndex=e.lastIndex,r}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){const r=new n(e.message);return r.stack=e.stack,r.name=e.name,r.cause=e.cause,r}if(typeof File<"u"&&e instanceof File)return new n([e],e.name,{type:e.type,lastModified:e.lastModified});if(typeof e=="object"){const r=Object.create(t);return Object.assign(r,e)}return e}function Zme(e,...t){const n=t.slice(0,-1),r=t[t.length-1];let s=e;for(let i=0;i<n.length;i++){const o=n[i];s=ex(s,o,r,new Map)}return s}function ex(e,t,n,r){var s;if(J9(e)&&(e=Object(e)),t==null||typeof t!="object")return e;if(r.has(t))return qme(r.get(t));if(r.set(t,e),Array.isArray(t)){t=t.slice();for(let o=0;o<t.length;o++)t[o]=(s=t[o])!=null?s:void 0}const i=[...Object.keys(t),...RD(t)];for(let o=0;o<i.length;o++){const a=i[o];let c=t[a],l=e[a];if(zD(c)&&(c=kD({},c)),zD(l)&&(l=kD({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=jD(c)),Array.isArray(c))if(typeof l=="object"&&l!=null){const f=[],d=Reflect.ownKeys(l);for(let h=0;h<d.length;h++){const p=d[h];f[p]=l[p]}l=f}else l=[];const u=n(l,c,a,e,t,r);u!=null?e[a]=u:Array.isArray(c)||HD(l)&&HD(c)?e[a]=ex(l,c,n,r):l==null&&Vme(c)?e[a]=ex({},c,n,r):l==null&&Hme(c)?e[a]=jD(c):(l===void 0||c!==void 0)&&(e[a]=c)}return e}function Wme(e,...t){return Zme(e,...t,zme)}const VD="error",Kme="wss://relay.walletconnect.org",Gme="wc",qD="universal_provider",g6=`${Gme}@2:${qD}:`,ZD="https://rpc.walletconnect.org/v1/",WD="generic",Yme=`${ZD}bundler`,Hh="call_status",Xme=86400,tx={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Jme=Object.defineProperty,Qme=Object.defineProperties,eye=Object.getOwnPropertyDescriptors,KD=Object.getOwnPropertySymbols,tye=Object.prototype.hasOwnProperty,nye=Object.prototype.propertyIsEnumerable,GD=(e,t,n)=>t in e?Jme(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,m6=(e,t)=>{for(var n in t||(t={}))tye.call(t,n)&&GD(e,n,t[n]);if(KD)for(var n of KD(t))nye.call(t,n)&&GD(e,n,t[n]);return e},rye=(e,t)=>Qme(e,eye(t));function YD(e,t,n){var r;const s=cl(e);return((r=t.rpcMap)==null?void 0:r[s.reference])||`${ZD}?chainId=${s.namespace}:${s.reference}&projectId=${n}`}function sye(e){return e.includes(":")?e.split(":")[1]:e}function XD(e){return e.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function iye(e,t){const n=Object.keys(t.namespaces).filter(s=>s.includes(e));if(!n.length)return[];const r=[];return n.forEach(s=>{const i=t.namespaces[s].accounts;r.push(...i)}),r}function JD(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>{var r,s;return((r=n?.chains)==null?void 0:r.length)&&((s=n?.chains)==null?void 0:s.length)>0}))}function y6(e={},t={}){const n=JD(QD(e)),r=JD(QD(t));return Wme(n,r)}function QD(e){var t,n,r,s,i;const o={};if(!ca(e))return o;for(const[a,c]of Object.entries(e)){const l=Yw(a)?[a]:c.chains,u=c.methods||[],f=c.events||[],d=c.rpcMap||{},h=Bh(a);o[h]=rye(m6(m6({},o[h]),c),{chains:oa(l,(t=o[h])==null?void 0:t.chains),methods:oa(u,(n=o[h])==null?void 0:n.methods),events:oa(f,(r=o[h])==null?void 0:r.events)}),(ca(d)||ca(((s=o[h])==null?void 0:s.rpcMap)||{}))&&(o[h].rpcMap=m6(m6({},d),(i=o[h])==null?void 0:i.rpcMap))}return o}function eM(e){return e.includes(":")?e.split(":")[2]:e}function tM(e){const t={};for(const[n,r]of Object.entries(e)){const s=r.methods||[],i=r.events||[],o=r.accounts||[],a=Yw(n)?[n]:r.chains?r.chains:XD(r.accounts);t[n]={chains:a,methods:s,events:i,accounts:o}}return t}function nx(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function oye(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}const nM={},Vh=e=>nM[e],rx=(e,t)=>{nM[e]=t};var aye=Object.defineProperty,rM=Object.getOwnPropertySymbols,cye=Object.prototype.hasOwnProperty,lye=Object.prototype.propertyIsEnumerable,sM=(e,t,n)=>t in e?aye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,iM=(e,t)=>{for(var n in t||(t={}))cye.call(t,n)&&sM(e,n,t[n]);if(rM)for(var n of rM(t))lye.call(t,n)&&sM(e,n,t[n]);return e};const oM="eip155",uye=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],dye=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,sx=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,aM=e=>Object.keys(e).filter(t=>uye.includes(t)).reduce((t,n)=>(t[n]=fye(e[n]),t),{}),fye=e=>typeof e=="string"&&oye(e)?JSON.parse(e):e,hye=(e,t,n)=>{const{sessionProperties:r={},scopedProperties:s={}}=e,i={};if(!ca(s)&&!ca(r))return;const o=aM(r);for(const a of n){const c=dye(a);if(!c)continue;i[sx(c)]=o;const l=s?.[`${oM}:${c}`];if(l){const u=l?.[`${oM}:${c}:${t}`];i[sx(c)]=iM(iM({},i[sx(c)]),aM(u||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var pye=Object.defineProperty,gye=(e,t,n)=>t in e?pye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mye=(e,t,n)=>gye(e,typeof t!="symbol"?t+"":t,n);let ix;class ox{constructor(t){mye(this,"storage"),this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,n){return await this.storage.setItem(t,n)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return ix||(ix=new ox(t)),ix}}var yye=Object.defineProperty,bye=Object.defineProperties,wye=Object.getOwnPropertyDescriptors,cM=Object.getOwnPropertySymbols,vye=Object.prototype.hasOwnProperty,Eye=Object.prototype.propertyIsEnumerable,lM=(e,t,n)=>t in e?yye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xye=(e,t)=>{for(var n in t||(t={}))vye.call(t,n)&&lM(e,n,t[n]);if(cM)for(var n of cM(t))Eye.call(t,n)&&lM(e,n,t[n]);return e},$ye=(e,t)=>bye(e,wye(t));async function Aye(e,t){const n=cl(e.result.capabilities.caip345.caip2),r=e.result.capabilities.caip345.transactionHashes,s=await Promise.allSettled(r.map(f=>Cye(n.reference,f,t))),i=s.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);s.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));const o=!i.length||i.some(f=>!f),a=i.every(f=>f?.status==="0x1"),c=i.every(f=>f?.status==="0x0"),l=i.some(f=>f?.status==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:i,status:u}}async function Cye(e,t,n){return await n(parseInt(e)).request(rn("eth_getTransactionReceipt",[t]))}async function Sye({sendCalls:e,storage:t}){const n=await t.getItem(Hh);await t.setItem(Hh,$ye(xye({},n),{[e.result.id]:{request:e.request,result:e.result,expiry:cn(Xme)}}))}async function Iye({resultId:e,storage:t}){const n=await t.getItem(Hh);if(n){delete n[e],await t.setItem(Hh,n);for(const r in n)ia(n[r].expiry)&&delete n[r];await t.setItem(Hh,n)}}async function _ye({resultId:e,storage:t}){const n=await t.getItem(Hh),r=n?.[e];if(r&&!ia(r.expiry))return r;await Iye({resultId:e,storage:t})}var Oye=Object.defineProperty,Pye=Object.defineProperties,Tye=Object.getOwnPropertyDescriptors,uM=Object.getOwnPropertySymbols,Nye=Object.prototype.hasOwnProperty,Bye=Object.prototype.propertyIsEnumerable,ax=(e,t,n)=>t in e?Oye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,cx=(e,t)=>{for(var n in t||(t={}))Nye.call(t,n)&&ax(e,n,t[n]);if(uM)for(var n of uM(t))Bye.call(t,n)&&ax(e,n,t[n]);return e},lx=(e,t)=>Pye(e,Tye(t)),T0=(e,t,n)=>ax(e,typeof t!="symbol"?t+"":t,n);class kye{constructor(t){T0(this,"name","eip155"),T0(this,"client"),T0(this,"chainId"),T0(this,"namespace"),T0(this,"httpProviders"),T0(this,"events"),T0(this,"storage"),this.namespace=t.namespace,this.events=Vh("events"),this.client=Vh("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=ox.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,n){this.httpProviders[t]||this.setHttpProvider(parseInt(t),n);const r=this.chainId;this.chainId=parseInt(t),this.events.emit(tx.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${r}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,n){const r=n||YD(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${t}`);return new Mh(new p6(r,Vh("disableProviderPing")))}setHttpProvider(t,n){const r=this.createHttpProvider(t,n);r&&(this.httpProviders[t]=r)}createHttpProviders(){const t={};return this.namespace.chains.forEach(n=>{var r;const s=parseInt(sye(n));t[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),t}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}getHttpProvider(t){const n=t||this.chainId;return this.httpProviders[n]||(this.httpProviders=lx(cx({},this.httpProviders),{[n]:this.createHttpProvider(n)}),this.httpProviders[n])}async handleSwitchChain(t){var n,r;let s=t.request.params?(n=t.request.params[0])==null?void 0:n.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const i=parseInt(s,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:s}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var n,r,s,i,o;const a=(r=(n=t.request)==null?void 0:n.params)==null?void 0:r[0],c=((i=(s=t.request)==null?void 0:s.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(t.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},f=`${a}${c.join(",")}`,d=u?.[f];if(d)return d;let h;try{h=hye(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(h)return h;const p=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:lx(cx({},l.sessionProperties||{}),{capabilities:lx(cx({},u||{}),{[f]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(t){var n,r,s;const i=this.client.session.get(t.topic),o=(n=i.sessionProperties)==null?void 0:n.bundler_name;if(o){const l=this.getBundlerUrl(t.chainId,o);try{return await this.getUserOperationReceipt(l,t)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(r=i.sessionProperties)==null?void 0:r.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await _ye({resultId:(s=t.request.params)==null?void 0:s[0],storage:this.storage});if(c)try{return await Aye(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,n){var r;const s=new URL(t),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(rn("eth_getUserOperationReceipt",[(r=n.request.params)==null?void 0:r[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(t,n){return`${Yme}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${n}`}async sendCalls(t){var n,r,s;const i=await this.client.request(t),o=(n=t.request.params)==null?void 0:n[0],a=i?.id,c=i?.capabilities||{},l=(r=c?.caip345)==null?void 0:r.caip2,u=(s=c?.caip345)==null?void 0:s.transactionHashes;return!a||!l||!(u!=null&&u.length)||await Sye({sendCalls:{request:o,result:i},storage:this.storage}),i}}var Rye=Object.defineProperty,Dye=(e,t,n)=>t in e?Rye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,qh=(e,t,n)=>Dye(e,typeof t!="symbol"?t+"":t,n);class Mye{constructor(t){qh(this,"name",WD),qh(this,"client"),qh(this,"httpProviders"),qh(this,"events"),qh(this,"namespace"),qh(this,"chainId"),this.namespace=t.namespace,this.events=Vh("events"),this.client=Vh("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,n){this.httpProviders[t]||this.setHttpProvider(t,n);const r=this.chainId;this.chainId=t,this.events.emit(tx.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${r}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return cl(t).namespace}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){var t,n;const r={};return(n=(t=this.namespace)==null?void 0:t.accounts)==null||n.forEach(s=>{var i,o;const a=cl(s),c=(o=(i=this.namespace)==null?void 0:i.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];r[a.reference]=this.createHttpProvider(s,c)}),r}getHttpProvider(t){const n=cl(t).reference,r=this.httpProviders[n];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,n){const r=this.createHttpProvider(t,n);r&&(this.httpProviders[t]=r)}createHttpProvider(t,n){const r=n||YD(t,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${t}`);return new Mh(new p6(r,Vh("disableProviderPing")))}}var Uye=Object.defineProperty,Lye=Object.defineProperties,Fye=Object.getOwnPropertyDescriptors,dM=Object.getOwnPropertySymbols,jye=Object.prototype.hasOwnProperty,zye=Object.prototype.propertyIsEnumerable,ux=(e,t,n)=>t in e?Uye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Zg=(e,t)=>{for(var n in t||(t={}))jye.call(t,n)&&ux(e,n,t[n]);if(dM)for(var n of dM(t))zye.call(t,n)&&ux(e,n,t[n]);return e},b6=(e,t)=>Lye(e,Fye(t)),Fi=(e,t,n)=>ux(e,typeof t!="symbol"?t+"":t,n);class dx{constructor(t){Fi(this,"client"),Fi(this,"namespaces"),Fi(this,"optionalNamespaces"),Fi(this,"sessionProperties"),Fi(this,"scopedProperties"),Fi(this,"events",new Ot.exports),Fi(this,"rpcProviders",{}),Fi(this,"session"),Fi(this,"providerOpts"),Fi(this,"logger"),Fi(this,"uri"),Fi(this,"disableProviderPing",!1);var n,r;this.providerOpts=t,this.logger=d9({logger:(n=t.logger)!=null?n:VD,name:(r=this.providerOpts.name)!=null?r:qD}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){const n=new dx(t);return await n.initialize(),n}async request(t,n,r){const[s,i]=this.validateChain(n);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:Zg({},t),chainId:`${s}:${i}`,topic:this.session.topic,expiry:r})}sendAsync(t,n,r,s){const i=new Date().getTime();this.request(t,r,s).then(o=>n(null,ua(i,o))).catch(o=>n(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 t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:Ut("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,n){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();const{uri:r,response:s}=await this.client.authenticate(t,n);r&&(this.uri=r,this.events.emit("display_uri",r));const i=await s();if(this.session=i.session,this.session){const o=tM(this.session.namespaces);this.namespaces=y6(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}removeListener(t,n){this.events.removeListener(t,n)}off(t,n){this.events.off(t,n)}get isWalletConnect(){return!0}async pair(t){const{uri:n,approval:r}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});n&&(this.uri=n,this.events.emit("display_uri",n));const s=await r();this.session=s;const i=tM(s.namespaces);return this.namespaces=y6(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,n){try{if(!this.session)return;const[r,s]=this.validateChain(t);this.getProvider(r).setDefaultChain(s,n)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");const n=this.client.pairing.getAll();if(!Di(n))return;for(const r of n)t.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${n.length}`)}catch(n){this.logger.warn(n,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var t,n;if(this.client=this.providerOpts.client||await ume.init({core:this.providerOpts.core,logger:this.providerOpts.logger||VD,relayUrl:this.providerOpts.relayUrl||Kme,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(r){throw this.logger.error(r,"Failed to get session"),new Error(`The provided session: ${(n=(t=this.providerOpts)==null?void 0:t.session)==null?void 0:n.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[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 t=[...new Set(Object.keys(this.session.namespaces).map(n=>Bh(n)))];rx("client",this.client),rx("events",this.events),rx("disableProviderPing",this.disableProviderPing),t.forEach(n=>{if(!this.session)return;const r=iye(n,this.session);if(r?.length===0)return;const s=XD(r),i=y6(this.namespaces,this.optionalNamespaces),o=b6(Zg({},i[n]),{accounts:r,chains:s});switch(n){case"eip155":this.rpcProviders[n]=new kye({namespace:o});break;default:this.rpcProviders[n]=new Mye({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{var n;const{topic:r}=t;r===((n=this.session)==null?void 0:n.topic)&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{var n;const{params:r,topic:s}=t;if(s!==((n=this.session)==null?void 0:n.topic))return;const{event:i}=r;if(i.name==="accountsChanged"){const o=i.data;o&&Di(o)&&this.events.emit("accountsChanged",o.map(eM))}else if(i.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Bh(o),l=nx(o)!==nx(a)?`${c}:${nx(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(i.name,i.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:n})=>{var r,s;if(t!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:i}=n,o=(s=this.client)==null?void 0:s.session.get(t);this.session=b6(Zg({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:n})}),this.client.on("session_delete",async t=>{var n;t.topic===((n=this.session)==null?void 0:n.topic)&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",b6(Zg({},Ut("USER_DISCONNECTED")),{data:t.topic})))}),this.on(tx.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(b6(Zg({},t),{internal:!0}))})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[WD]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var n;this.getProvider(t).updateNamespace((n=this.session)==null?void 0:n.namespaces[t])})}setNamespaces(t){const{namespaces:n={},optionalNamespaces:r={},sessionProperties:s,scopedProperties:i}=t;this.optionalNamespaces=y6(n,r),this.sessionProperties=s,this.scopedProperties=i}validateChain(t){const[n,r]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[n,r];if(n&&!Object.keys(this.namespaces||{}).map(o=>Bh(o)).includes(n))throw new Error(`Namespace '${n}' is not configured. Please call connect() first with namespace config.`);if(n&&r)return[n,r];const s=Bh(Object.keys(this.namespaces)[0]),i=this.rpcProviders[s].getDefaultChain();return[s,i]}async requestAccounts(){const[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:n,internal:r=!1}){if(!this.namespaces)return;const[s,i]=this.validateChain(t);i&&(this.updateNamespaceChain(s,i),r?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:t,previousCaipChainId:n})):this.getProvider(s).setDefaultChain(i),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:n,previousCaipChainId:r}){var s,i;try{if(r===n)return;const o=(i=(s=this.session)==null?void 0:s.namespaces[t])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${n}:`)).map(eM);if(!Di(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,n){if(!this.namespaces)return;const r=this.namespaces[t]?t:`${t}:${n}`,s={chains:[],methods:[],events:[],defaultChain:n};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=n):this.namespaces[r]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,n){var r;const s=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${g6}/${t}${s}`,n)}async getFromStore(t){var n;const r=((n=this.session)==null?void 0:n.topic)||"";return await this.client.core.storage.getItem(`${g6}/${t}${r}`)}async deleteFromStore(t){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.removeItem(`${g6}/${t}${r}`)}async cleanupStorage(){var t;try{if(((t=this.client)==null?void 0:t.session.length)>0)return;const n=await this.client.core.storage.getKeys();for(const r of n)r.startsWith(g6)&&await this.client.core.storage.removeItem(r)}catch(n){this.logger.warn(n,"Failed to cleanup storage")}}}const Hye=dx,Vye="wc",qye="ethereum_provider",Zye=`${Vye}@2:${qye}:`,Wye="https://rpc.walletconnect.org/v1/",w6=["eth_sendTransaction","personal_sign"],fM=["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"],v6=["chainChanged","accountsChanged"],hM=["chainChanged","accountsChanged","message","disconnect","connect"],Kye=async()=>{const{createAppKit:e}=await Promise.resolve().then(function(){return HLe});return e};var Gye=Object.defineProperty,Yye=Object.defineProperties,Xye=Object.getOwnPropertyDescriptors,pM=Object.getOwnPropertySymbols,Jye=Object.prototype.hasOwnProperty,Qye=Object.prototype.propertyIsEnumerable,fx=(e,t,n)=>t in e?Gye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,N0=(e,t)=>{for(var n in t||(t={}))Jye.call(t,n)&&fx(e,n,t[n]);if(pM)for(var n of pM(t))Qye.call(t,n)&&fx(e,n,t[n]);return e},Wg=(e,t)=>Yye(e,Xye(t)),hi=(e,t,n)=>fx(e,typeof t!="symbol"?t+"":t,n);function E6(e){return Number(e[0].split(":")[1])}function x6(e){return`0x${e.toString(16)}`}function ebe(e){const{chains:t,optionalChains:n,methods:r,optionalMethods:s,events:i,optionalEvents:o,rpcMap:a}=e;if(!Di(t))throw new Error("Invalid chains");const c={chains:t,methods:r||w6,events:i||v6,rpcMap:N0({},t.length?{[E6(t)]:a[E6(t)]}:{})},l=i?.filter(h=>!v6.includes(h)),u=r?.filter(h=>!w6.includes(h));if(!n&&!o&&!s&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:t.length?c:void 0};const f=l?.length&&u?.length||!n,d={chains:[...new Set(f?c.chains.concat(n||[]):n)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:fM))],events:[...new Set(c.events.concat(o!=null&&o.length?o:hM))],rpcMap:a};return{required:t.length?c:void 0,optional:n.length?d:void 0}}class $6{constructor(){hi(this,"events",new Ot.exports.EventEmitter),hi(this,"namespace","eip155"),hi(this,"accounts",[]),hi(this,"signer"),hi(this,"chainId",1),hi(this,"modal"),hi(this,"rpc"),hi(this,"STORAGE_KEY",Zye),hi(this,"on",(t,n)=>(this.events.on(t,n),this)),hi(this,"once",(t,n)=>(this.events.once(t,n),this)),hi(this,"removeListener",(t,n)=>(this.events.removeListener(t,n),this)),hi(this,"off",(t,n)=>(this.events.off(t,n),this)),hi(this,"parseAccount",t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t),this.signer={},this.rpc={}}static async init(t){const n=new $6;return await n.initialize(t),n}async request(t,n){return await this.signer.request(t,this.formatChainId(this.chainId),n)}sendAsync(t,n,r){this.signer.sendAsync(t,n,this.formatChainId(this.chainId),r)}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(t){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:r,optional:s}=ebe(this.rpc);try{const i=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const f=t!=null&&t.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect(Wg(N0({namespaces:N0({},r&&{[this.namespace]:r})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic,scopedProperties:f})).then(d=>{a(d)}).catch(d=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!i)return;const o=WN(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:x6(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{(n=this.modal)==null||n.close()}}async authenticate(t,n){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const s=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(Wg(N0({},t),{chains:this.rpc.chains}),n).then(u=>{o(u)}).catch(u=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),i=s.session;if(i){const o=WN(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:x6(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.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",t=>{const{params:n}=t,{event:r}=n;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.data),this.events.emit("session_event",t)}),this.signer.on("accountsChanged",t=>{this.accounts=this.parseAccounts(t),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",t=>{const n=parseInt(t);this.chainId=n,this.events.emit("chainChanged",x6(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",Wg(N0({},Ut("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const n=t.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));n.length&&(this.chainId=n[0],this.events.emit("chainChanged",x6(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const n=this.parseChainId(t);this.chainId=n,this.switchEthereumChain(n)}}parseAccountId(t){const[n,r,s]=t.split(":");return{chainId:`${n}:${r}`,address:s}}setAccounts(t){this.accounts=t.filter(n=>this.parseChainId(this.parseAccountId(n).chainId)===this.chainId).map(n=>this.parseAccountId(n).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var n,r;const s=(n=t?.chains)!=null?n:[],i=(r=t?.optionalChains)!=null?r:[],o=s.concat(i);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?t?.methods||w6:[],c=s.length?t?.events||v6:[],l=t?.optionalMethods||[],u=t?.optionalEvents||[],f=t?.rpcMap||this.buildRpcMap(o,t.projectId),d=t?.qrModalOptions||void 0;return{chains:s?.map(h=>this.formatChainId(h)),optionalChains:i.map(h=>this.formatChainId(h)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:f,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:d,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,n){const r={};return t.forEach(s=>{r[s]=this.getRpcUrl(s,n)}),r}async initialize(t){var n;if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?E6(this.rpc.chains):E6(this.rpc.optionalChains),this.signer=await Hye.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storage:t.storage,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const s=await Kye(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return QLe}),o=i(Wg(N0({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect\xB7");r=s(Wg(N0({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((n=this.rpc.qrModalOptions)==null?void 0:n.enableMobileFullScreen)===!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:n,optionalChains:r,rpcMap:s}=t;n&&Di(n)&&(this.rpc.chains=n.map(i=>this.formatChainId(i)),n.forEach(i=>{this.rpc.rpcMap[i]=s?.[i]||this.getRpcUrl(i)})),r&&Di(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r?.map(i=>this.formatChainId(i)),r.forEach(i=>{this.rpc.rpcMap[i]=s?.[i]||this.getRpcUrl(i)}))}getRpcUrl(t,n){var r;return((r=this.rpc.rpcMap)==null?void 0:r[t])||`${Wye}?chainId=eip155:${t}&projectId=${n||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),n=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:n?.accounts),this.setAccounts(n?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(n=>this.signer.logger.warn(n))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(n=>this.parseAccount(n))}}const tbe=$6;var gM={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Tn,function(){var n=1e3,r=6e4,s=36e5,i="millisecond",o="second",a="minute",c="hour",l="day",u="week",f="month",d="quarter",h="year",p="date",g="Invalid Date",y=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,$=/\[([^\]]+)]|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,_={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(v){var m=["th","st","nd","rd"],b=v%100;return"["+v+(m[(b-20)%10]||m[b]||m[0])+"]"}},x=function(v,m,b){var A=String(v);return!A||A.length>=m?v:""+Array(m+1-A.length).join(b)+v},E={s:x,z:function(v){var m=-v.utcOffset(),b=Math.abs(m),A=Math.floor(b/60),I=b%60;return(m<=0?"+":"-")+x(A,2,"0")+":"+x(I,2,"0")},m:function v(m,b){if(m.date()<b.date())return-v(b,m);var A=12*(b.year()-m.year())+(b.month()-m.month()),I=m.clone().add(A,f),C=b-I<0,O=m.clone().add(A+(C?-1:1),f);return+(-(A+(b-I)/(C?I-O:O-I))||0)},a:function(v){return v<0?Math.ceil(v)||0:Math.floor(v)},p:function(v){return{M:f,y:h,w:u,d:l,D:p,h:c,m:a,s:o,ms:i,Q:d}[v]||String(v||"").toLowerCase().replace(/s$/,"")},u:function(v){return v===void 0}},P="en",N={};N[P]=_;var k="$isDayjsObject",R=function(v){return v instanceof S||!(!v||!v[k])},T=function v(m,b,A){var I;if(!m)return P;if(typeof m=="string"){var C=m.toLowerCase();N[C]&&(I=C),b&&(N[C]=b,I=C);var O=m.split("-");if(!I&&O.length>1)return v(O[0])}else{var B=m.name;N[B]=m,I=B}return!A&&I&&(P=I),I||!A&&P},L=function(v,m){if(R(v))return v.clone();var b=typeof m=="object"?m:{};return b.date=v,b.args=arguments,new S(b)},M=E;M.l=T,M.i=R,M.w=function(v,m){return L(v,{locale:m.$L,utc:m.$u,x:m.$x,$offset:m.$offset})};var S=function(){function v(b){this.$L=T(b.locale,null,!0),this.parse(b),this.$x=this.$x||b.x||{},this[k]=!0}var m=v.prototype;return m.parse=function(b){this.$d=function(A){var I=A.date,C=A.utc;if(I===null)return new Date(NaN);if(M.u(I))return new Date;if(I instanceof Date)return new Date(I);if(typeof I=="string"&&!/Z$/i.test(I)){var O=I.match(y);if(O){var B=O[2]-1||0,D=(O[7]||"0").substring(0,3);return C?new Date(Date.UTC(O[1],B,O[3]||1,O[4]||0,O[5]||0,O[6]||0,D)):new Date(O[1],B,O[3]||1,O[4]||0,O[5]||0,O[6]||0,D)}}return new Date(I)}(b),this.init()},m.init=function(){var b=this.$d;this.$y=b.getFullYear(),this.$M=b.getMonth(),this.$D=b.getDate(),this.$W=b.getDay(),this.$H=b.getHours(),this.$m=b.getMinutes(),this.$s=b.getSeconds(),this.$ms=b.getMilliseconds()},m.$utils=function(){return M},m.isValid=function(){return this.$d.toString()!==g},m.isSame=function(b,A){var I=L(b);return this.startOf(A)<=I&&I<=this.endOf(A)},m.isAfter=function(b,A){return L(b)<this.startOf(A)},m.isBefore=function(b,A){return this.endOf(A)<L(b)},m.$g=function(b,A,I){return M.u(b)?this[A]:this.set(I,b)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(b,A){var I=this,C=!!M.u(A)||A,O=M.p(b),B=function(Z,Y){var fe=M.w(I.$u?Date.UTC(I.$y,Y,Z):new Date(I.$y,Y,Z),I);return C?fe:fe.endOf(l)},D=function(Z,Y){return M.w(I.toDate()[Z].apply(I.toDate("s"),(C?[0,0,0,0]:[23,59,59,999]).slice(Y)),I)},z=this.$W,j=this.$M,U=this.$D,V="set"+(this.$u?"UTC":"");switch(O){case h:return C?B(1,0):B(31,11);case f:return C?B(1,j):B(0,j+1);case u:var q=this.$locale().weekStart||0,X=(z<q?z+7:z)-q;return B(C?U-X:U+(6-X),j);case l:case p:return D(V+"Hours",0);case c:return D(V+"Minutes",1);case a:return D(V+"Seconds",2);case o:return D(V+"Milliseconds",3);default:return this.clone()}},m.endOf=function(b){return this.startOf(b,!1)},m.$set=function(b,A){var I,C=M.p(b),O="set"+(this.$u?"UTC":""),B=(I={},I[l]=O+"Date",I[p]=O+"Date",I[f]=O+"Month",I[h]=O+"FullYear",I[c]=O+"Hours",I[a]=O+"Minutes",I[o]=O+"Seconds",I[i]=O+"Milliseconds",I)[C],D=C===l?this.$D+(A-this.$W):A;if(C===f||C===h){var z=this.clone().set(p,1);z.$d[B](D),z.init(),this.$d=z.set(p,Math.min(this.$D,z.daysInMonth())).$d}else B&&this.$d[B](D);return this.init(),this},m.set=function(b,A){return this.clone().$set(b,A)},m.get=function(b){return this[M.p(b)]()},m.add=function(b,A){var I,C=this;b=Number(b);var O=M.p(A),B=function(j){var U=L(C);return M.w(U.date(U.date()+Math.round(j*b)),C)};if(O===f)return this.set(f,this.$M+b);if(O===h)return this.set(h,this.$y+b);if(O===l)return B(1);if(O===u)return B(7);var D=(I={},I[a]=r,I[c]=s,I[o]=n,I)[O]||1,z=this.$d.getTime()+b*D;return M.w(z,this)},m.subtract=function(b,A){return this.add(-1*b,A)},m.format=function(b){var A=this,I=this.$locale();if(!this.isValid())return I.invalidDate||g;var C=b||"YYYY-MM-DDTHH:mm:ssZ",O=M.z(this),B=this.$H,D=this.$m,z=this.$M,j=I.weekdays,U=I.months,V=I.meridiem,q=function(Y,fe,me,we){return Y&&(Y[fe]||Y(A,C))||me[fe].slice(0,we)},X=function(Y){return M.s(B%12||12,Y,"0")},Z=V||function(Y,fe,me){var we=Y<12?"AM":"PM";return me?we.toLowerCase():we};return C.replace($,function(Y,fe){return fe||function(me){switch(me){case"YY":return String(A.$y).slice(-2);case"YYYY":return M.s(A.$y,4,"0");case"M":return z+1;case"MM":return M.s(z+1,2,"0");case"MMM":return q(I.monthsShort,z,U,3);case"MMMM":return q(U,z);case"D":return A.$D;case"DD":return M.s(A.$D,2,"0");case"d":return String(A.$W);case"dd":return q(I.weekdaysMin,A.$W,j,2);case"ddd":return q(I.weekdaysShort,A.$W,j,3);case"dddd":return j[A.$W];case"H":return String(B);case"HH":return M.s(B,2,"0");case"h":return X(1);case"hh":return X(2);case"a":return Z(B,D,!0);case"A":return Z(B,D,!1);case"m":return String(D);case"mm":return M.s(D,2,"0");case"s":return String(A.$s);case"ss":return M.s(A.$s,2,"0");case"SSS":return M.s(A.$ms,3,"0");case"Z":return O}return null}(Y)||O.replace(":","")})},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(b,A,I){var C,O=this,B=M.p(A),D=L(b),z=(D.utcOffset()-this.utcOffset())*r,j=this-D,U=function(){return M.m(O,D)};switch(B){case h:C=U()/12;break;case f:C=U();break;case d:C=U()/3;break;case u:C=(j-z)/6048e5;break;case l:C=(j-z)/864e5;break;case c:C=j/s;break;case a:C=j/r;break;case o:C=j/n;break;default:C=j}return I?C:M.a(C)},m.daysInMonth=function(){return this.endOf(f).$D},m.$locale=function(){return N[this.$L]},m.locale=function(b,A){if(!b)return this.$L;var I=this.clone(),C=T(b,A,!0);return C&&(I.$L=C),I},m.clone=function(){return M.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},v}(),w=S.prototype;return L.prototype=w,[["$ms",i],["$s",o],["$m",a],["$H",c],["$W",l],["$M",f],["$y",h],["$D",p]].forEach(function(v){w[v[1]]=function(m){return this.$g(m,v[0],v[1])}}),L.extend=function(v,m){return v.$i||(v(m,S,L),v.$i=!0),L},L.locale=T,L.isDayjs=R,L.unix=function(v){return L(1e3*v)},L.en=N[P],L.Ls=N,L.p={},L})})(gM);var hx=gM.exports,mM={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Tn,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(n){var r=["th","st","nd","rd"],s=n%100;return"["+n+(r[(s-20)%10]||r[s]||r[0])+"]"}}})})(mM);var nbe=mM.exports,yM={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Tn,function(){return function(n,r,s){n=n||{};var i=r.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,f,d){return i.fromToBase(l,u,f,d)}s.en.relativeTime=o,i.fromToBase=function(l,u,f,d,h){for(var p,g,y,$=f.$locale().relativeTime||o,_=n.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"}],x=_.length,E=0;E<x;E+=1){var P=_[E];P.d&&(p=d?s(l).diff(f,P.d,!0):f.diff(l,P.d,!0));var N=(n.rounding||Math.round)(Math.abs(p));if(y=p>0,N<=P.r||!P.r){N<=1&&E>0&&(P=_[E-1]);var k=$[P.l];h&&(N=h(""+N)),g=typeof k=="string"?k.replace("%d",N):k(N,u,P.l,y);break}}if(u)return g;var R=y?$.future:$.past;return typeof R=="function"?R(g):R.replace("%s",g)},i.to=function(l,u){return a(l,u,this,!0)},i.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?s.utc():s()};i.toNow=function(l){return this.to(c(this),l)},i.fromNow=function(l){return this.from(c(this),l)}}})})(yM);var rbe=yM.exports,bM={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Tn,function(){return function(n,r,s){s.updateLocale=function(i,o){var a=s.Ls[i];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(bM);var sbe=bM.exports;hx.extend(rbe),hx.extend(sbe);const ibe={...nbe,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"}};hx.locale("en-web3-modal",ibe);const te={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",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,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",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof process<"u"&&process.env.NODE_ENV==="development"},px={caipNetworkIdToNumber(e){return e?Number(e.split(":")[1]):void 0},parseEvmChainId(e){return typeof e=="string"?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace(e,t){return e?.filter(n=>n.chainNamespace===t)||[]},getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const n=e.find(s=>s.caipNetworkId===t);if(n)return n.name;const[r]=t.split(":");return te.CHAIN_NAME_MAP?.[r]||void 0}},wM=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var obe=20,abe=1,B0=1e6,vM=1e6,cbe=-7,lbe=21,ube=!1,Kg="[big.js] ",k0=Kg+"Invalid ",A6=k0+"decimal places",dbe=k0+"rounding mode",EM=Kg+"Division by zero",vt={},ga=void 0,fbe=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function xM(){function e(t){var n=this;if(!(n instanceof e))return t===ga?xM():new e(t);if(t instanceof e)n.s=t.s,n.e=t.e,n.c=t.c.slice();else{if(typeof t!="string"){if(e.strict===!0&&typeof t!="bigint")throw TypeError(k0+"value");t=t===0&&1/t<0?"-0":String(t)}hbe(n,t)}n.constructor=e}return e.prototype=vt,e.DP=obe,e.RM=abe,e.NE=cbe,e.PE=lbe,e.strict=ube,e.roundDown=0,e.roundHalfUp=1,e.roundHalfEven=2,e.roundUp=3,e}function hbe(e,t){var n,r,s;if(!fbe.test(t))throw Error(k0+"number");for(e.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),s=t.length,r=0;r<s&&t.charAt(r)=="0";)++r;if(r==s)e.c=[e.e=0];else{for(;s>0&&t.charAt(--s)=="0";);for(e.e=n-r-1,e.c=[],n=0;r<=s;)e.c[n++]=+t.charAt(r++)}return e}function R0(e,t,n,r){var s=e.c;if(n===ga&&(n=e.constructor.RM),n!==0&&n!==1&&n!==2&&n!==3)throw Error(dbe);if(t<1)r=n===3&&(r||!!s[0])||t===0&&(n===1&&s[0]>=5||n===2&&(s[0]>5||s[0]===5&&(r||s[1]!==ga))),s.length=1,r?(e.e=e.e-t+1,s[0]=1):s[0]=e.e=0;else if(t<s.length){if(r=n===1&&s[t]>=5||n===2&&(s[t]>5||s[t]===5&&(r||s[t+1]!==ga||s[t-1]&1))||n===3&&(r||!!s[0]),s.length=t,r){for(;++s[--t]>9;)if(s[t]=0,t===0){++e.e,s.unshift(1);break}}for(t=s.length;!s[--t];)s.pop()}return e}function D0(e,t,n){var r=e.e,s=e.c.join(""),i=s.length;if(t)s=s.charAt(0)+(i>1?"."+s.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)s="0"+s;s="0."+s}else if(r>0)if(++r>i)for(r-=i;r--;)s+="0";else r<i&&(s=s.slice(0,r)+"."+s.slice(r));else i>1&&(s=s.charAt(0)+"."+s.slice(1));return e.s<0&&n?"-"+s:s}vt.abs=function(){var e=new this.constructor(this);return e.s=1,e},vt.cmp=function(e){var t,n=this,r=n.c,s=(e=new n.constructor(e)).c,i=n.s,o=e.s,a=n.e,c=e.e;if(!r[0]||!s[0])return r[0]?i:s[0]?-o:0;if(i!=o)return i;if(t=i<0,a!=c)return a>c^t?1:-1;for(o=(a=r.length)<(c=s.length)?a:c,i=-1;++i<o;)if(r[i]!=s[i])return r[i]>s[i]^t?1:-1;return a==c?0:a>c^t?1:-1},vt.div=function(e){var t=this,n=t.constructor,r=t.c,s=(e=new n(e)).c,i=t.s==e.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>B0)throw Error(A6);if(!s[0])throw Error(EM);if(!r[0])return e.s=i,e.c=[e.e=0],e;var a,c,l,u,f,d=s.slice(),h=a=s.length,p=r.length,g=r.slice(0,a),y=g.length,$=e,_=$.c=[],x=0,E=o+($.e=t.e-e.e)+1;for($.s=i,i=E<0?0:E,d.unshift(0);y++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(y=g.length))u=a>y?1:-1;else for(f=-1,u=0;++f<a;)if(s[f]!=g[f]){u=s[f]>g[f]?1:-1;break}if(u<0){for(c=y==a?s:d;y;){if(g[--y]<c[y]){for(f=y;f&&!g[--f];)g[f]=9;--g[f],g[y]+=10}g[y]-=c[y]}for(;!g[0];)g.shift()}else break}_[x++]=u?l:++l,g[0]&&u?g[y]=r[h]||0:g=[r[h]]}while((h++<p||g[0]!==ga)&&i--);return!_[0]&&x!=1&&(_.shift(),$.e--,E--),x>E&&R0($,E,n.RM,g[0]!==ga),$},vt.eq=function(e){return this.cmp(e)===0},vt.gt=function(e){return this.cmp(e)>0},vt.gte=function(e){return this.cmp(e)>-1},vt.lt=function(e){return this.cmp(e)<0},vt.lte=function(e){return this.cmp(e)<1},vt.minus=vt.sub=function(e){var t,n,r,s,i=this,o=i.constructor,a=i.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,i.plus(e);var l=i.c.slice(),u=i.e,f=e.c,d=e.e;if(!l[0]||!f[0])return f[0]?e.s=-c:l[0]?e=new o(i):e.s=1,e;if(a=u-d){for((s=a<0)?(a=-a,r=l):(d=u,r=f),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((s=l.length<f.length)?l:f).length,a=c=0;c<n;c++)if(l[c]!=f[c]){s=l[c]<f[c];break}if(s&&(r=l,l=f,f=r,e.s=-e.s),(c=(n=f.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;n>a;){if(l[--n]<f[n]){for(t=n;t&&!l[--t];)l[t]=9;--l[t],l[n]+=10}l[n]-=f[n]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--d;return l[0]||(e.s=1,l=[d=0]),e.c=l,e.e=d,e},vt.mod=function(e){var t,n=this,r=n.constructor,s=n.s,i=(e=new r(e)).s;if(!e.c[0])throw Error(EM);return n.s=e.s=1,t=e.cmp(n)==1,n.s=s,e.s=i,t?new r(n):(s=r.DP,i=r.RM,r.DP=r.RM=0,n=n.div(e),r.DP=s,r.RM=i,this.minus(n.times(e)))},vt.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},vt.plus=vt.add=function(e){var t,n,r,s=this,i=s.constructor;if(e=new i(e),s.s!=e.s)return e.s=-e.s,s.minus(e);var o=s.e,a=s.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new i(s):e.s=s.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,r=l):(t=-t,r=a),r.reverse();t--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),t=l.length,n=0;t;a[t]%=10)n=(a[--t]=a[t]+l[t]+n)/10|0;for(n&&(a.unshift(n),++c),t=a.length;a[--t]===0;)a.pop();return e.c=a,e.e=c,e},vt.pow=function(e){var t=this,n=new t.constructor("1"),r=n,s=e<0;if(e!==~~e||e<-vM||e>vM)throw Error(k0+"exponent");for(s&&(e=-e);e&1&&(r=r.times(t)),e>>=1,!!e;)t=t.times(t);return s?n.div(r):r},vt.prec=function(e,t){if(e!==~~e||e<1||e>B0)throw Error(k0+"precision");return R0(new this.constructor(this),e,t)},vt.round=function(e,t){if(e===ga)e=0;else if(e!==~~e||e<-B0||e>B0)throw Error(A6);return R0(new this.constructor(this),e+this.e+1,t)},vt.sqrt=function(){var e,t,n,r=this,s=r.constructor,i=r.s,o=r.e,a=new s("0.5");if(!r.c[0])return new s(r);if(i<0)throw Error(Kg+"No square root");i=Math.sqrt(+D0(r,!0,!0)),i===0||i===1/0?(t=r.c.join(""),t.length+o&1||(t+="0"),i=Math.sqrt(t),o=((o+1)/2|0)-(o<0||o&1),e=new s((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):e=new s(i+""),o=e.e+(s.DP+=4);do n=e,e=a.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return R0(e,(s.DP-=4)+e.e+1,s.RM)},vt.times=vt.mul=function(e){var t,n=this,r=n.constructor,s=n.c,i=(e=new r(e)).c,o=s.length,a=i.length,c=n.e,l=e.e;if(e.s=n.s==e.s?1:-1,!s[0]||!i[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=s,s=i,i=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+i[c]*s[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},vt.toExponential=function(e,t){var n=this,r=n.c[0];if(e!==ga){if(e!==~~e||e<0||e>B0)throw Error(A6);for(n=R0(new n.constructor(n),++e,t);n.c.length<e;)n.c.push(0)}return D0(n,!0,!!r)},vt.toFixed=function(e,t){var n=this,r=n.c[0];if(e!==ga){if(e!==~~e||e<0||e>B0)throw Error(A6);for(n=R0(new n.constructor(n),e+n.e+1,t),e=e+n.e+1;n.c.length<e;)n.c.push(0)}return D0(n,!1,!!r)},vt[Symbol.for("nodejs.util.inspect.custom")]=vt.toJSON=vt.toString=function(){var e=this,t=e.constructor;return D0(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},vt.toNumber=function(){var e=+D0(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(e.toString()))throw Error(Kg+"Imprecise conversion");return e},vt.toPrecision=function(e,t){var n=this,r=n.constructor,s=n.c[0];if(e!==ga){if(e!==~~e||e<1||e>B0)throw Error(k0+"precision");for(n=R0(new r(n),e,t);n.c.length<e;)n.c.push(0)}return D0(n,e<=n.e||n.e<=r.NE||n.e>=r.PE,!!s)},vt.valueOf=function(){var e=this,t=e.constructor;if(t.strict===!0)throw Error(Kg+"valueOf disallowed");return D0(e,e.e<=t.NE||e.e>=t.PE,!0)};var qu=xM();const dn={bigNumber(e){return e?new qu(e):new qu(0)},multiply(e,t){if(e===void 0||t===void 0)return new qu(0);const n=new qu(e),r=new qu(t);return n.times(r)},toFixed(e,t=2){return e===void 0||e===""?new qu(0).toFixed(t):new qu(e).toFixed(t)},formatNumberToLocalString(e,t=2){return e===void 0||e===""?"0.00":typeof e=="number"?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"})},parseLocalStringToNumber(e){if(e===void 0||e==="")return 0;const t=e.replace(/,/gu,"");return new qu(t).toNumber()}},pbe=[{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"}]}],gbe=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],mbe=[{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"}]}],ybe={getERC20Abi:e=>te.USDT_CONTRACT_ADDRESSES.includes(e)?mbe:pbe,getSwapAbi:()=>gbe},er={validateCaipAddress(e){if(e.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(t.length!==3)throw new Error(`Invalid CAIP-10 address: ${e}`);const[n,r,s]=t;if(!n||!r||!s)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:n,chainId:r,address:s}},parseCaipNetworkId(e){const t=e.split(":");if(t.length!==2)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[n,r]=t;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:n,chainId:r}}},ma={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(e){try{if(typeof e=="object"&&e!==null){const t=e,n=typeof t.message=="string",r=typeof t.code=="number";return n&&r}return!1}catch{return!1}},isUserRejectedMessage(e){return e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled")},isUserRejectedRequestError(e){return ma.isRpcProviderError(e)?e.code===ma.RPC_ERROR_CODE.USER_REJECTED_REQUEST||ma.isUserRejectedMessage(e.message):e instanceof Error?ma.isUserRejectedMessage(e.message):!1}};class bbe extends Error{constructor(t,n){super(n.message,{cause:t}),this.name=ma.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=n.code}}class $M extends bbe{constructor(t){super(t,{code:ma.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=ma.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const _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",RECENT_WALLET:"@appkit/recent_wallet",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",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function gx(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const Ae={setItem(e,t){Gg()&&t!==void 0&&localStorage.setItem(e,t)},getItem(e){if(Gg())return localStorage.getItem(e)||void 0},removeItem(e){Gg()&&localStorage.removeItem(e)},clear(){Gg()&&localStorage.clear()}};function Gg(){return typeof window<"u"&&typeof localStorage<"u"}function C6(e,t){return t==="light"?{"--w3m-accent":e?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":e?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const wbe=Symbol(),AM=Object.getPrototypeOf,mx=new WeakMap,vbe=e=>e&&(mx.has(e)?mx.get(e):AM(e)===Object.prototype||AM(e)===Array.prototype),Ebe=e=>vbe(e)&&e[wbe]||null,CM=(e,t=!0)=>{mx.set(e,t)},yx=e=>typeof e=="object"&&e!==null,xbe=e=>yx(e)&&!Yg.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),SM=(e,t)=>{const n=bx.get(e);if(n?.[0]===t)return n[1];const r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return CM(r,!0),bx.set(e,[t,r]),Reflect.ownKeys(e).forEach(s=>{if(Object.getOwnPropertyDescriptor(r,s))return;const i=Reflect.get(e,s),{enumerable:o}=Reflect.getOwnPropertyDescriptor(e,s),a={value:i,enumerable:o,configurable:!0};if(Yg.has(i))CM(i,!1);else if(Zu.has(i)){const[c,l]=Zu.get(i);a.value=SM(c,l())}Object.defineProperty(r,s,a)}),Object.preventExtensions(r)},$be=(e,t,n,r)=>({deleteProperty(s,i){const o=Reflect.get(s,i);n(i);const a=Reflect.deleteProperty(s,i);return a&&r(["delete",[i],o]),a},set(s,i,o,a){const c=!e()&&Reflect.has(s,i),l=Reflect.get(s,i,a);if(c&&(IM(l,o)||Xg.has(o)&&IM(l,Xg.get(o))))return!0;n(i),yx(o)&&(o=Ebe(o)||o);const u=!Zu.has(o)&&Cbe(o)?Et(o):o;return t(i,u),Reflect.set(s,i,u,a),r(["set",[i],o,l]),!0}}),Zu=new WeakMap,Yg=new WeakSet,bx=new WeakMap,S6=[1],Xg=new WeakMap;let IM=Object.is,Abe=(e,t)=>new Proxy(e,t),Cbe=xbe,Sbe=SM,Ibe=$be;function Et(e={}){if(!yx(e))throw new Error("object required");const t=Xg.get(e);if(t)return t;let n=S6[0];const r=new Set,s=(y,$=++S6[0])=>{n!==$&&(i=n=$,r.forEach(_=>_(y,$)))};let i=n;const o=(y=S6[0])=>(i!==y&&(i=y,c.forEach(([$])=>{const _=$[1](y);_>n&&(n=_)})),n),a=y=>($,_)=>{const x=[...$];x[1]=[y,...x[1]],s(x,_)},c=new Map,l=(y,$)=>{const _=!Yg.has($)&&Zu.get($);if(_){if(c.has(y))throw new Error("prop listener already exists");if(r.size){const x=_[2](a(y));c.set(y,[_,x])}else c.set(y,[_])}},u=y=>{var $;const _=c.get(y);_&&(c.delete(y),($=_[1])==null||$.call(_))},f=y=>(r.add(y),r.size===1&&c.forEach(([_,x],E)=>{if(x)throw new Error("remove already exists");const P=_[2](a(E));c.set(E,[_,P])}),()=>{r.delete(y),r.size===0&&c.forEach(([_,x],E)=>{x&&(x(),c.set(E,[_]))})});let d=!0;const h=Ibe(()=>d,l,u,s),p=Abe(e,h);Xg.set(e,p);const g=[e,o,f];return Zu.set(p,g),Reflect.ownKeys(e).forEach(y=>{const $=Object.getOwnPropertyDescriptor(e,y);"value"in $&&$.writable&&(p[y]=e[y])}),d=!1,p}function vn(e,t,n){const r=Zu.get(e);r||console.warn("Please use proxy object");let s;const i=[],o=r[2];let a=!1;const l=o(u=>{if(i.push(u),n){t(i.splice(0));return}s||(s=Promise.resolve().then(()=>{s=void 0,a&&t(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Jg(e){const t=Zu.get(e);t||console.warn("Please use proxy object");const[n,r]=t;return Sbe(n,r())}function Zh(e){return Yg.add(e),e}function _be(){return{proxyStateMap:Zu,refSet:Yg,snapCache:bx,versionHolder:S6,proxyCache:Xg}}function En(e,t,n,r){let s=e[t];return vn(e,()=>{const i=e[t];Object.is(s,i)||n(s=i)},r)}const{proxyStateMap:Obe,snapCache:Pbe}=_be(),I6=e=>Obe.has(e);function Tbe(e){const t=[];let n=0;const r=new Map,s=new WeakMap,i=()=>{const l=Pbe.get(a),u=l?.[1];if(u&&!s.has(u)){const f=new Map(r);s.set(u,f)}},o=l=>s.get(l)||r;if(e){if(typeof e[Symbol.iterator]!="function")throw new TypeError(`proxyMap:
|
|
42
42
|
initial state must be iterable
|
|
43
43
|
tip: structure should be [[key, value]]`);for(const[l,u]of e)r.set(l,n),t[n++]=u}const a={data:t,index:n,epoch:0,get size(){return I6(this)||i(),o(this).size},get(l){const f=o(this).get(l);if(f===void 0){this.epoch;return}return this.data[f]},has(l){const u=o(this);return this.epoch,u.has(l)},set(l,u){if(!I6(this))throw new Error("Cannot perform mutations on a snapshot");const f=r.get(l);return f===void 0?(r.set(l,this.index),this.data[this.index++]=u):this.data[f]=u,this.epoch++,this},delete(l){if(!I6(this))throw new Error("Cannot perform mutations on a snapshot");const u=r.get(l);return u===void 0?!1:(delete this.data[u],r.delete(l),this.epoch++,!0)},clear(){if(!I6(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,r.clear()},forEach(l){this.epoch,o(this).forEach((f,d)=>{l(this.data[f],d,this)})},*entries(){this.epoch;const l=o(this);for(const[u,f]of l)yield[u,this.data[f]]},*keys(){this.epoch;const l=o(this);for(const u of l.keys())yield u},*values(){this.epoch;const l=o(this);for(const u of l.values())yield this.data[u]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=Et(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}const wx=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",_M=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Nbe="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ye={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:wx,SECURE_SITE_DASHBOARD:`${wx}/dashboard`,SECURE_SITE_FAVICON:`${wx}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:[te.CHAIN.EVM,te.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[te.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[te.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[te.CHAIN.EVM,te.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[te.CHAIN.EVM,te.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[te.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"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:[te.CHAIN.EVM,te.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1},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"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},ce={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(e,t){return Date.now()-e>t},getActiveNetworkProps(){const e=ce.getActiveNamespace(),t=ce.getActiveCaipNetworkId(),n=t?t.split(":")[1]:void 0,r=n?isNaN(Number(n))?n:Number(n):void 0;return{namespace:e,caipNetworkId:t,chainId:r}},setWalletConnectDeepLink({name:e,href:t}){try{Ae.setItem(_e.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=Ae.getItem(_e.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Ae.removeItem(_e.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{Ae.setItem(_e.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{Ae.setItem(_e.ACTIVE_CAIP_NETWORK_ID,e),ce.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Ae.getItem(_e.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Ae.removeItem(_e.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=gx(e);Ae.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=ce.getRecentWallets();t.find(r=>r.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Ae.setItem(_e.RECENT_WALLETS,JSON.stringify(t)),Ae.setItem(_e.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=Ae.getItem(_e.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=Ae.getItem(_e.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Ae.removeItem(_e.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const n=gx(e);Ae.setItem(n,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Ae.getItem(_e.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=gx(e);return Ae.getItem(t)}catch{console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{Ae.setItem(_e.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Ae.getItem(_e.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Ae.removeItem(_e.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Ae.getItem(_e.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Ae.getItem(_e.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(e){try{Ae.setItem(_e.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Ae.getItem(_e.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=Ae.getItem(_e.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));Ae.setItem(_e.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=ce.getConnectedNamespaces();t.includes(e)||(t.push(e),ce.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=ce.getConnectedNamespaces(),n=t.indexOf(e);n>-1&&(t.splice(n,1),ce.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Ae.getItem(_e.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{Ae.setItem(_e.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Ae.removeItem(_e.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=Ae.getItem(_e.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=ce.getBalanceCache();Ae.setItem(_e.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const n=ce.getBalanceCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.portfolio))return n.balance;ce.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=ce.getBalanceCache();t[e.caipAddress]=e,Ae.setItem(_e.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=Ae.getItem(_e.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=ce.getBalanceCache();Ae.setItem(_e.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const n=ce.getNativeBalanceCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.nativeBalance))return n;console.info("Discarding cache for address",e),ce.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=ce.getNativeBalanceCache();t[e.caipAddress]=e,Ae.setItem(_e.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=Ae.getItem(_e.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const n=ce.getEnsCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.ens))return n.ens;ce.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=ce.getEnsCache();t[e.address]=e,Ae.setItem(_e.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=ce.getEnsCache();Ae.setItem(_e.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=Ae.getItem(_e.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const n=ce.getIdentityCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.identity))return n.identity;ce.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=ce.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Ae.setItem(_e.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=ce.getIdentityCache();Ae.setItem(_e.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},clearAddressCache(){try{Ae.removeItem(_e.PORTFOLIO_CACHE),Ae.removeItem(_e.NATIVE_BALANCE_CACHE),Ae.removeItem(_e.ENS_CACHE),Ae.removeItem(_e.IDENTITY_CACHE),Ae.removeItem(_e.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{Ae.setItem(_e.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=Ae.getItem(_e.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const n=ce.getConnections(),r=n[t]??[],s=new Map;for(const o of r)s.set(o.connectorId,{...o});for(const o of e){const a=s.get(o.connectorId),c=o.connectorId===te.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(f=>f.address.toLowerCase())),u=o.accounts.filter(f=>!l.has(f.address.toLowerCase()));a.accounts.push(...u)}else s.set(o.connectorId,{...o})}const i={...n,[t]:Array.from(s.values())};Ae.setItem(_e.CONNECTIONS,JSON.stringify(i))}catch(n){console.error("Unable to sync connections to storage",n)}},getConnections(){try{const e=Ae.getItem(_e.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:n}){try{const r=ce.getConnections(),s=r[n]??[],i=new Map(s.map(a=>[a.connectorId,a])),o=i.get(e);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase()).length===0?i.delete(e):i.set(e,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase())})),Ae.setItem(_e.CONNECTIONS,JSON.stringify({...r,[n]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const e=Ae.getItem(_e.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const n=ce.getDisconnectedConnectorIds(),r=n[t]??[];r.push(e),Ae.setItem(_e.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{const n=ce.getDisconnectedConnectorIds();let r=n[t]??[];r=r.filter(s=>s.toLowerCase()!==e.toLowerCase()),Ae.setItem(_e.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{return(ce.getDisconnectedConnectorIds()[t]??[]).some(s=>s.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{const e=Ae.getItem(_e.HISTORY_TRANSACTIONS_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{const r=ce.getTransactionsCache()[e]?.[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;ce.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:n,transactions:r}){try{const s=ce.getTransactionsCache();s[e]={...s[e],[t]:{timestamp:n,transactions:r}},Ae.setItem(_e.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(s))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:n,transactions:r})}},removeTransactionsCache({address:e,chainId:t}){try{const n=ce.getTransactionsCache(),r=n?.[e]||{},{[t]:s,...i}=r;Ae.setItem(_e.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...n,[e]:i}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=Ae.getItem(_e.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const n=ce.getTokenPriceCache()[e.join(",")];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.tokenPrice))return n.tokenPrice;ce.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=ce.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},Ae.setItem(_e.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=ce.getTokenPriceCache();Ae.setItem(_e.TOKEN_PRICE_CACHE,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{const e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const e=Ae.getItem(_e.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=ce.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,Ae.setItem(_e.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},oe={isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(e,t=""){return e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return oe.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(e){return e?e-Date.now()<=Ye.TEN_SEC_MS:!0},isAllowedRetry(e,t=Ye.ONE_SEC_MS){return Date.now()-e>=t},copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(oe.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const n=new URL(e),r=new URL(t);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ye.FOUR_MINUTES_MS},getNetworkId(e){return e?.split(":")[1]},getPlainAddress(e){return e?.split(":")[2]},async wait(e){return new Promise(t=>{setTimeout(t,e)})},debounce(e,t=500){let n;return(...r)=>{function s(){e(...r)}n&&clearTimeout(n),n=setTimeout(s,t)}},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},formatNativeUrl(e,t,n=null){if(oe.isHttpUrl(e))return this.formatUniversalUrl(e,t);let r=e,s=n;r&&(r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`)),s&&!s?.endsWith("/")&&(s=`${s}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const i=encodeURIComponent(t);return{redirect:`${r}wc?uri=${i}`,redirectUniversalLink:s?`${s}wc?uri=${i}`:void 0,href:r}},formatUniversalUrl(e,t){if(!oe.isHttpUrl(e))return this.formatNativeUrl(e,t);let n=e;n.endsWith("/")||(n=`${n}/`);const r=encodeURIComponent(t);return{redirect:`${n}wc?uri=${r}`,href:n}},getOpenTargetForPlatform(e){return e==="popupWindow"?e:this.isTelegram()?ce.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,n){window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},returnOpenHref(e,t,n){return window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const e=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,t=window?.navigator?.standalone;return!!(e||t)},async preloadImage(e){const t=new Promise((n,r)=>{const s=new Image;s.onload=n,s.onerror=r,s.crossOrigin="anonymous",s.src=e});return Promise.race([t,oe.wait(2e3)])},parseBalance(e,t){let n="0.000";if(typeof e=="string"){const c=Number(e);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(n=l)}}const[r,s]=n.split("."),i=r||"0",o=s||"000";return{formattedText:`${i}.${o}${t?` ${t}`:""}`,value:i,decimals:o,symbol:t}},getApiUrl(){return te.W3M_API_URL},getBlockchainApiUrl(){return te.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return te.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},parseError(e){return typeof e=="string"?e:typeof e?.issues?.[0]?.message=="string"?e.issues[0].message:e instanceof Error?e.message:"Unknown error"},sortRequestedNetworks(e,t=[]){const n={};return t&&e&&(e.forEach((r,s)=>{n[r]=s}),t.sort((r,s)=>{const i=n[r.id],o=n[s.id];return i!==void 0&&o!==void 0?i-o:i!==void 0?-1:o!==void 0?1:0})),t},calculateBalance(e){let t=0;for(const n of e)t+=n.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[n,r]=t.split(".");return{dollars:n,pennies:r}},isAddress(e,t="eip155"){switch(t){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)||/^(?:0x)?[0-9A-F]{40}$/iu.test(e))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);default:return!1}},uniqueBy(e,t){const n=new Set;return e.filter(r=>{const s=r[t];return n.has(s)?!1:(n.add(s),!0)})},generateSdkVersion(e,t,n){const s=e.length===0?Ye.ADAPTER_TYPES.UNIVERSAL:e.map(i=>i.adapterType).join(",");return`${t}-${s}-${n}`},createAccount(e,t,n,r,s){return{namespace:e,address:t,type:n,publicKey:r,path:s}},isCaipAddress(e){if(typeof e!="string")return!1;const t=e.split(":"),n=t[0];return t.filter(Boolean).length===3&&n in te.CHAIN_NAME_MAP},getAccount(e){return e?typeof e=="string"?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0}},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,n="state=";if(new URL(e).host==="auth.magic.link"){const s="provider_authorization_url=",i=e.substring(e.indexOf(s)+s.length),o=this.injectIntoUrl(decodeURIComponent(i),n,t);return e.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(e,n,t)},injectIntoUrl(e,t,n){const r=e.indexOf(t);if(r===-1)throw new Error(`${t} parameter not found in the URL: ${e}`);const s=e.indexOf("&",r),i=t.length,o=s!==-1?s:e.length,a=e.substring(0,r+i),c=e.substring(r+i,o),l=e.substring(s),u=c+n;return a+u+l}},Bbe="1.1.0";class Ln extends Error{constructor(t,n={}){const r=n.cause instanceof Ln?n.cause.details:n.cause?.message?n.cause.message:n.details,s=n.cause instanceof Ln&&n.cause.docsPath||n.docsPath,i=[t||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...r?[`Details: ${r}`]:[],`Version: abitype@${Bbe}`].join(`
|