@walletconnect/ethereum-provider 2.23.5 → 2.23.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -38,7 +38,7 @@ ${e.length}`,n=new TextEncoder().encode(t+e);return"0x"+Buffer.from(GZ(n)).toStr
38
38
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
39
39
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
40
40
  PERFORMANCE OF THIS SOFTWARE.
41
- ***************************************************************************** */var e4=function(e,t){return e4=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},e4(e,t)};function NJ(e,t){e4(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var t4=function(){return t4=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},t4.apply(this,arguments)};function PJ(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 i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function OJ(e,t,n,r){var i=arguments.length,s=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s}function kJ(e,t){return function(n,r){t(n,r,e)}}function RJ(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function BJ(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function MJ(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,i=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function DJ(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}function UJ(e,t){for(var n in e)n!=="default"&&!t.hasOwnProperty(n)&&(t[n]=e[n])}function n4(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 dI(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,s=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function LJ(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(dI(arguments[t]));return e}function FJ(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ah(e){return this instanceof Ah?(this.v=e,this):new Ah(e)}function HJ(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(f){return new Promise(function(p,g){s.push([h,f,p,g])>1||a(h,f)})})}function a(h,f){try{c(r[h](f))}catch(p){d(s[0][3],p)}}function c(h){h.value instanceof Ah?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function jJ(e){var t,n;return t={},r("next"),r("throw",function(i){throw i}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(i,s){t[i]=e[i]?function(o){return(n=!n)?{value:Ah(e[i](o)),done:i==="return"}:s?s(o):o}:s}}function zJ(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 n4=="function"?n4(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function VJ(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function WJ(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 qJ(e){return e&&e.__esModule?e:{default:e}}function ZJ(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function GJ(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 KJ=Object.freeze({__proto__:null,__extends:NJ,get __assign(){return t4},__rest:PJ,__decorate:OJ,__param:kJ,__metadata:RJ,__awaiter:BJ,__generator:MJ,__createBinding:DJ,__exportStar:UJ,__values:n4,__read:dI,__spread:LJ,__spreadArrays:FJ,__await:Ah,__asyncGenerator:HJ,__asyncDelegator:jJ,__asyncValues:zJ,__makeTemplateObject:VJ,__importStar:WJ,__importDefault:qJ,__classPrivateFieldGet:ZJ,__classPrivateFieldSet:GJ}),YJ=XE(KJ),tc={},fI;function XJ(){if(fI)return tc;fI=1,Object.defineProperty(tc,"__esModule",{value:!0}),tc.isBrowserCryptoAvailable=tc.getSubtleCrypto=tc.getBrowerCrypto=void 0;function e(){return Pn?.crypto||Pn?.msCrypto||{}}tc.getBrowerCrypto=e;function t(){const r=e();return r.subtle||r.webkitSubtle}tc.getSubtleCrypto=t;function n(){return!!e()&&!!t()}return tc.isBrowserCryptoAvailable=n,tc}var nc={},hI;function JJ(){if(hI)return nc;hI=1,Object.defineProperty(nc,"__esModule",{value:!0}),nc.isBrowser=nc.isNode=nc.isReactNative=void 0;function e(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}nc.isReactNative=e;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}nc.isNode=t;function n(){return!e()&&!t()}return nc.isBrowser=n,nc}(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=YJ;t.__exportStar(XJ(),e),t.__exportStar(JJ(),e)})(uI);function ro(e=3){const t=Date.now()*Math.pow(10,e),n=Math.floor(Math.random()*Math.pow(10,e));return t+n}function rl(e=6){return BigInt(ro(e))}function ws(e,t,n){return{id:n||ro(),jsonrpc:"2.0",method:e,params:t}}function Ch(e,t){return{id:e,jsonrpc:"2.0",result:t}}function um(e,t,n){return{id:e,jsonrpc:"2.0",error:QJ(t,n)}}function QJ(e,t){return typeof e>"u"?cI(oI):(typeof e=="string"&&(e=Object.assign(Object.assign({},cI(Q8)),{message:e})),typeof t<"u"&&(e.data=t),$J(e.code)&&(e=TJ(e.code)),e)}class eQ{}class tQ extends eQ{constructor(){super()}}class nQ extends tQ{constructor(t){super()}}const rQ="^https?:",iQ="^wss?:";function sQ(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function pI(e,t){const n=sQ(e);return typeof n>"u"?!1:new RegExp(t).test(n)}function gI(e){return pI(e,rQ)}function mI(e){return pI(e,iQ)}function oQ(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function yI(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function r4(e){return yI(e)&&"method"in e}function dm(e){return yI(e)&&(io(e)||ji(e))}function io(e){return"result"in e}function ji(e){return"error"in e}class i4 extends nQ{constructor(t){super(t),this.events=new zn.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(ws(t.method,t.params||[],t.id||rl().toString()),n)}async requestStrict(t,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${t.id}`,s=>{ji(s)?i(s.error):r(s.result)});try{await this.connection.send(t,n)}catch(s){i(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),dm(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 aQ=()=>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"),cQ=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",wI=e=>e.split("?")[0],bI=10,lQ=aQ();class uQ{constructor(t){if(this.url=t,this.events=new zn.exports.EventEmitter,this.registering=!1,!mI(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(ou(t))}catch(n){this.onError(t.id,n)}}register(t=this.url){if(!mI(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,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const i=uI.isReactNative()?void 0:{rejectUnauthorized:!oQ(t)},s=new lQ(t,[],i);cQ()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}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"?su(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),i=r.message||r.toString(),s=um(t,i);this.events.emit("payload",s)}parseError(t,n=this.url){return lI(t,wI(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>bI&&this.events.setMaxListeners(bI)}emitError(t){const n=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${wI(this.url)}`));return this.events.emit("register_error",n),n}}var dQ=Object.defineProperty,vI=Object.getOwnPropertySymbols,fQ=Object.prototype.hasOwnProperty,hQ=Object.prototype.propertyIsEnumerable,EI=(e,t,n)=>t in e?dQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nr=(e,t)=>{for(var n in t||(t={}))fQ.call(t,n)&&EI(e,n,t[n]);if(vI)for(var n of vI(t))hQ.call(t,n)&&EI(e,n,t[n]);return e};const AI="wc",CI=2,fm="core",so=`${AI}@2:${fm}:`,pQ={name:fm,logger:"error"},gQ={database:":memory:"},mQ="crypto",xI="client_ed25519_seed",yQ=ve.ONE_DAY,wQ="keychain",bQ="0.3",vQ="messages",EQ="0.3",AQ=ve.SIX_HOURS,CQ="publisher",_I="irn",xQ="error",SI="wss://relay.walletconnect.org",_Q="relayer",hn={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"},SQ="_subscription",zi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},IQ=.1,s4="2.23.5",Kt={link_mode:"link_mode",relay:"relay"},hm={inbound:"inbound",outbound:"outbound"},$Q="0.3",TQ="WALLETCONNECT_CLIENT_ID",II="WALLETCONNECT_LINK_MODE_APPS",Ci={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},NQ="subscription",PQ="0.3",OQ="pairing",kQ="0.3",xh={wc_pairingDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:0},res:{ttl:ve.ONE_DAY,prompt:!1,tag:0}}},vu={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},bs={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},RQ="history",BQ="0.3",MQ="expirer",Vi={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DQ="0.3",UQ="verify-api",LQ="https://verify.walletconnect.com",$I="https://verify.walletconnect.org",_h=$I,FQ=`${_h}/v3`,HQ=[LQ,$I],jQ="echo",zQ="https://echo.walletconnect.com",oo={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"},rc={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"},vs={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"},Eu={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"},Au={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"},Sh={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"},VQ=.1,WQ="event-client",qQ=86400,ZQ="https://pulse.walletconnect.org/batch";function GQ(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,A=0,_=p.length;A!==_&&p[A]===0;)A++,g++;for(var v=(_-A)*u+1>>>0,w=new Uint8Array(v);A!==_;){for(var T=p[A],O=0,D=v-1;(T!==0||O<y)&&D!==-1;D--,O++)T+=256*w[D]>>>0,w[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");y=O,A++}for(var F=v-y;F!==v&&w[F]===0;)F++;for(var U=c.repeat(g);F<v;++F)U+=e.charAt(w[F]);return U}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,A=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,v=new Uint8Array(_);p[g];){var w=n[p.charCodeAt(g)];if(w===255)return;for(var T=0,O=_-1;(w!==0||T<A)&&O!==-1;O--,T++)w+=a*v[O]>>>0,v[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=T,g++}if(p[g]!==" "){for(var D=_-A;D!==_&&v[D]===0;)D++;for(var F=new Uint8Array(y+(_-D)),U=y;D!==_;)F[U++]=v[D++];return F}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var KQ=GQ,YQ=KQ;const TI=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")},XQ=e=>new TextEncoder().encode(e),JQ=e=>new TextDecoder().decode(e);class QQ{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 eee{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 NI(this,t)}}class tee{constructor(t){this.decoders=t}or(t){return NI(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 NI=(e,t)=>new tee(Nr(Nr({},e.decoders||{[e.prefix]:e}),t.decoders||{[t.prefix]:t}));class nee{constructor(t,n,r,i){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new QQ(t,n,r),this.decoder=new eee(t,n,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const pm=({name:e,prefix:t,encode:n,decode:r})=>new nee(e,t,n,r),Ih=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=YQ(n,t);return pm({prefix:e,name:t,encode:r,decode:s=>TI(i(s))})},ree=(e,t,n,r)=>{const i={};for(let u=0;u<t.length;++u)i[t[u]]=u;let s=e.length;for(;e[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[e[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|d,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},iee=(e,t,n)=>{const r=t[t.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Gn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>pm({prefix:t,name:e,encode(i){return iee(i,r,n)},decode(i){return ree(i,r,n,e)}}),see=pm({prefix:"\0",name:"identity",encode:e=>JQ(e),decode:e=>XQ(e)});var oee=Object.freeze({__proto__:null,identity:see});const aee=Gn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cee=Object.freeze({__proto__:null,base2:aee});const lee=Gn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var uee=Object.freeze({__proto__:null,base8:lee});const dee=Ih({prefix:"9",name:"base10",alphabet:"0123456789"});var fee=Object.freeze({__proto__:null,base10:dee});const hee=Gn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pee=Gn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gee=Object.freeze({__proto__:null,base16:hee,base16upper:pee});const mee=Gn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yee=Gn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wee=Gn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bee=Gn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vee=Gn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eee=Gn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Aee=Gn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cee=Gn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xee=Gn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _ee=Object.freeze({__proto__:null,base32:mee,base32upper:yee,base32pad:wee,base32padupper:bee,base32hex:vee,base32hexupper:Eee,base32hexpad:Aee,base32hexpadupper:Cee,base32z:xee});const See=Ih({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iee=Ih({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $ee=Object.freeze({__proto__:null,base36:See,base36upper:Iee});const Tee=Ih({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nee=Ih({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Pee=Object.freeze({__proto__:null,base58btc:Tee,base58flickr:Nee});const Oee=Gn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kee=Gn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ree=Gn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bee=Gn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mee=Object.freeze({__proto__:null,base64:Oee,base64pad:kee,base64url:Ree,base64urlpad:Bee});const PI=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}"),Dee=PI.reduce((e,t,n)=>(e[n]=t,e),[]),Uee=PI.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function Lee(e){return e.reduce((t,n)=>(t+=Dee[n],t),"")}function Fee(e){const t=[];for(const n of e){const r=Uee[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const Hee=pm({prefix:"\u{1F680}",name:"base256emoji",encode:Lee,decode:Fee});var jee=Object.freeze({__proto__:null,base256emoji:Hee}),zee=kI,OI=128,Vee=127,Wee=~Vee,qee=Math.pow(2,31);function kI(e,t,n){t=t||[],n=n||0;for(var r=n;e>=qee;)t[n++]=e&255|OI,e/=128;for(;e&Wee;)t[n++]=e&255|OI,e>>>=7;return t[n]=e|0,kI.bytes=n-r+1,t}var Zee=o4,Gee=128,RI=127;function o4(e,r){var n=0,r=r||0,i=0,s=r,o,a=e.length;do{if(s>=a)throw o4.bytes=0,new RangeError("Could not decode varint");o=e[s++],n+=i<28?(o&RI)<<i:(o&RI)*Math.pow(2,i),i+=7}while(o>=Gee);return o4.bytes=s-r,n}var Kee=Math.pow(2,7),Yee=Math.pow(2,14),Xee=Math.pow(2,21),Jee=Math.pow(2,28),Qee=Math.pow(2,35),ete=Math.pow(2,42),tte=Math.pow(2,49),nte=Math.pow(2,56),rte=Math.pow(2,63),ite=function(e){return e<Kee?1:e<Yee?2:e<Xee?3:e<Jee?4:e<Qee?5:e<ete?6:e<tte?7:e<nte?8:e<rte?9:10},ste={encode:zee,decode:Zee,encodingLength:ite},BI=ste;const MI=(e,t,n=0)=>(BI.encode(e,t,n),t),DI=e=>BI.encodingLength(e),a4=(e,t)=>{const n=t.byteLength,r=DI(e),i=r+DI(n),s=new Uint8Array(i+n);return MI(e,s,0),MI(n,s,r),s.set(t,i),new ote(e,n,t,s)};class ote{constructor(t,n,r,i){this.code=t,this.size=n,this.digest=r,this.bytes=i}}const UI=({name:e,code:t,encode:n})=>new ate(e,t,n);class ate{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?a4(this.code,n):n.then(r=>a4(this.code,r))}else throw Error("Unknown type, must be binary type")}}const LI=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cte=UI({name:"sha2-256",code:18,encode:LI("SHA-256")}),lte=UI({name:"sha2-512",code:19,encode:LI("SHA-512")});var ute=Object.freeze({__proto__:null,sha256:cte,sha512:lte});const FI=0,dte="identity",HI=TI;var fte=Object.freeze({__proto__:null,identity:{code:FI,name:dte,encode:HI,digest:e=>a4(FI,HI(e))}});new TextEncoder,new TextDecoder;const jI=Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr({},oee),cee),uee),fee),gee),_ee),$ee),Pee),Mee),jee);Nr(Nr({},ute),fte);function zI(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function hte(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?zI(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function VI(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const WI=VI("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),c4=VI("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=hte(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),pte=Nr({utf8:WI,"utf-8":WI,hex:jI.base16,latin1:c4,ascii:c4,binary:c4},jI);function gte(e,t="utf8"){const n=pte[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?zI(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}var mte=Object.defineProperty,yte=(e,t,n)=>t in e?mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ao=(e,t,n)=>yte(e,typeof t!="symbol"?t+"":t,n);class wte{constructor(t,n){this.core=t,this.logger=n,ao(this,"keychain",new Map),ao(this,"name",wQ),ao(this,"version",bQ),ao(this,"initialized",!1),ao(this,"storagePrefix",so),ao(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ao(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ao(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),ao(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=Ae("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),ao(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=t,this.logger=vi(n,this.name)}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,l8(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var bte=Object.defineProperty,vte=(e,t,n)=>t in e?bte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t,n)=>vte(e,typeof t!="symbol"?t+"":t,n);class Ete{constructor(t,n,r){this.core=t,this.logger=n,Mn(this,"name",mQ),Mn(this,"keychain"),Mn(this,"randomSessionIdentifier",j8()),Mn(this,"initialized",!1),Mn(this,"clientId"),Mn(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Mn(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Mn(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=i_(i),o=r_(s.publicKey);return this.clientId=o,o}),Mn(this,"generateKeyPair",()=>{this.isInitialized();const i=iY();return this.setPrivateKey(i.publicKey,i.privateKey)}),Mn(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=i_(s),a=this.randomSessionIdentifier;return await IV(a,i,yQ,o)}),Mn(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=sY(a,s);return this.setSymKey(c,o)}),Mn(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||tm(i);return await this.keychain.set(o,i),o}),Mn(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"encode",async(i,s,o)=>{this.isInitialized();const a=kS(o),c=ou(s);if(BS(a))return cY(c,o?.encoding);if(RS(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return oY({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Mn(this,"decode",async(i,s,o)=>{this.isInitialized();const a=uY(s,o);if(BS(a)){const c=lY(s,o?.encoding);return su(c)}if(RS(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=aY({symKey:c,encoded:s,encoding:o?.encoding});return su(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Mn(this,"getPayloadType",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return mu(o.type)}),Mn(this,"getPayloadSenderPublicKey",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return o.senderPublicKey?Zr(o.senderPublicKey,Tr):void 0}),this.core=t,this.logger=vi(n,this.name),this.keychain=r||new wte(this.core,this.logger)}get context(){return Gr(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(xI)}catch{t=j8(),await this.keychain.set(xI,t)}return gte(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Ate=Object.defineProperty,Cte=Object.defineProperties,xte=Object.getOwnPropertyDescriptors,qI=Object.getOwnPropertySymbols,_te=Object.prototype.hasOwnProperty,Ste=Object.prototype.propertyIsEnumerable,l4=(e,t,n)=>t in e?Ate(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ite=(e,t)=>{for(var n in t||(t={}))_te.call(t,n)&&l4(e,n,t[n]);if(qI)for(var n of qI(t))Ste.call(t,n)&&l4(e,n,t[n]);return e},$te=(e,t)=>Cte(e,xte(t)),xi=(e,t,n)=>l4(e,typeof t!="symbol"?t+"":t,n);class Tte extends uJ{constructor(t,n){super(t,n),this.logger=t,this.core=n,xi(this,"messages",new Map),xi(this,"messagesWithoutClientAck",new Map),xi(this,"name",vQ),xi(this,"version",EQ),xi(this,"initialized",!1),xi(this,"storagePrefix",so),xi(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),xi(this,"set",async(r,i,s)=>{this.isInitialized();const o=Fi(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===hm.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,$te(Ite({},c),{[o]:i}))}return await this.persist(),o}),xi(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),xi(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),xi(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Fi(i);return typeof s[o]<"u"}),xi(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Fi(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),xi(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=vi(t,this.name),this.core=n}get context(){return Gr(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,l8(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,l8(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async getRelayerMessagesWithoutClientAck(){const t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?u8(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Nte=Object.defineProperty,Pte=Object.defineProperties,Ote=Object.getOwnPropertyDescriptors,ZI=Object.getOwnPropertySymbols,kte=Object.prototype.hasOwnProperty,Rte=Object.prototype.propertyIsEnumerable,u4=(e,t,n)=>t in e?Nte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a0=(e,t)=>{for(var n in t||(t={}))kte.call(t,n)&&u4(e,n,t[n]);if(ZI)for(var n of ZI(t))Rte.call(t,n)&&u4(e,n,t[n]);return e},GI=(e,t)=>Pte(e,Ote(t)),Wi=(e,t,n)=>u4(e,typeof t!="symbol"?t+"":t,n);class Bte extends dJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Wi(this,"events",new zn.exports.EventEmitter),Wi(this,"name",CQ),Wi(this,"queue",new Map),Wi(this,"publishTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),Wi(this,"initialPublishTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),Wi(this,"needsTransportRestart",!1),Wi(this,"publish",async(r,i,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const d=s?.ttl||AQ,h=s?.prompt||!1,f=s?.tag||0,p=s?.id||rl().toString(),g=i0(nm().protocol),y={id:p,method:s?.publishMethod||g.publish,params:a0({topic:r,message:i,ttl:d,prompt:h,tag:f,attestation:s?.attestation},s?.tvf)},A=`Failed to publish payload, please try again. id:${p} tag:${f}`;try{$n((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),$n((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const _=new Promise(async v=>{const w=({id:O})=>{var D;((D=y.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(hn.publish,w),v())};this.relayer.events.on(hn.publish,w);const T=Js(new Promise((O,D)=>{this.rpcPublish(y,s).then(O).catch(F=>{this.logger.warn(F,F?.message),D(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${f}`);try{await T,this.events.removeListener(hn.publish,w)}catch(O){this.queue.set(p,{request:y,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await Js(_,this.publishTimeout,A)}catch(_){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(_),(u=s?.internal)!=null&&u.throwOnFailedPublish)throw _}finally{this.queue.delete(p)}}),Wi(this,"publishCustom",async r=>{var i,s,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:d,tvf:h,publishMethod:f,prompt:p,tag:g,ttl:y=ve.FIVE_MINUTES}=u,A=u.id||rl().toString(),_=i0(nm().protocol),v=f||_.publish,w={id:A,method:v,params:a0(GI(a0({},l),{ttl:y,prompt:p,tag:g,attestation:d}),h)},T=`Failed to publish custom payload, please try again. id:${A} tag:${g}`;try{$n((i=w.params)==null?void 0:i.prompt)&&((s=w.params)==null||delete s.prompt),$n((o=w.params)==null?void 0:o.tag)&&((a=w.params)==null||delete a.tag);const O=new Promise(async D=>{const F=({id:j})=>{var W;((W=w.id)==null?void 0:W.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(hn.publish,F),D())};this.relayer.events.on(hn.publish,F);const U=Js(new Promise((j,W)=>{this.rpcPublish(w,u).then(j).catch(S=>{this.logger.warn(S,S?.message),W(S)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${v} id:${A} tag:${g}`);try{await U,this.events.removeListener(hn.publish,F)}catch(j){this.queue.set(A,{request:w,opts:u,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:A,payload:l,opts:u}}),await Js(O,this.publishTimeout,T)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(A)}}),Wi(this,"on",(r,i)=>{this.events.on(r,i)}),Wi(this,"once",(r,i)=>{this.events.once(r,i)}),Wi(this,"off",(r,i)=>{this.events.off(r,i)}),Wi(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=t,this.logger=vi(n,this.name),this.registerEventListeners()}get context(){return Gr(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(hn.publish,a0(a0({},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 i=t.attempt+1;this.queue.set(n,GI(a0({},t),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(r=t.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(wu.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hn.connection_stalled);return}this.checkQueue()}),this.relayer.on(hn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}var Mte=Object.defineProperty,Dte=(e,t,n)=>t in e?Mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,c0=(e,t,n)=>Dte(e,typeof t!="symbol"?t+"":t,n);class Ute{constructor(){c0(this,"map",new Map),c0(this,"set",(t,n)=>{const r=this.get(t);this.exists(t,n)||this.map.set(t,[...r,n])}),c0(this,"get",t=>this.map.get(t)||[]),c0(this,"exists",(t,n)=>this.get(t).includes(n)),c0(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 i=r.filter(s=>s!==n);if(!i.length){this.map.delete(t);return}this.map.set(t,i)}),c0(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Lte=Object.defineProperty,Fte=Object.defineProperties,Hte=Object.getOwnPropertyDescriptors,KI=Object.getOwnPropertySymbols,jte=Object.prototype.hasOwnProperty,zte=Object.prototype.propertyIsEnumerable,d4=(e,t,n)=>t in e?Lte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$h=(e,t)=>{for(var n in t||(t={}))jte.call(t,n)&&d4(e,n,t[n]);if(KI)for(var n of KI(t))zte.call(t,n)&&d4(e,n,t[n]);return e},f4=(e,t)=>Fte(e,Hte(t)),jt=(e,t,n)=>d4(e,typeof t!="symbol"?t+"":t,n);class Vte extends pJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,jt(this,"subscriptions",new Map),jt(this,"topicMap",new Ute),jt(this,"events",new zn.exports.EventEmitter),jt(this,"name",NQ),jt(this,"version",PQ),jt(this,"pending",new Map),jt(this,"cached",[]),jt(this,"initialized",!1),jt(this,"storagePrefix",so),jt(this,"subscribeTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),jt(this,"initialSubscribeTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),jt(this,"clientId"),jt(this,"batchSubscribeTopicsLimit",500),jt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),jt(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=nm(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),jt(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),jt(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),jt(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),jt(this,"on",(r,i)=>{this.events.on(r,i)}),jt(this,"once",(r,i)=>{this.events.once(r,i)}),jt(this,"off",(r,i)=>{this.events.off(r,i)}),jt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),jt(this,"start",async()=>{await this.onConnect()}),jt(this,"stop",async()=>{await this.onDisconnect()}),jt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),jt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),jt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(wu.pulse,async()=>{await this.checkPending()}),this.events.on(Ci.created,async r=>{const i=Ci.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Ci.deleted,async r=>{const i=Ci.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=t,this.logger=vi(n,this.name),this.clientId=""}get context(){return Gr(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 i=>await this.unsubscribeById(t,i,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 i=nm(r);await this.restartToComplete({topic:t,id:n,relay:i}),await this.rpcUnsubscribe(t,n,i);const s=Gt("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(t,n,r){var i,s;const o=await this.getSubscriptionId(t);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===Kt.relay)&&await this.restartToComplete({topic:t,id:t,relay:n});const a={method:i0(n.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===Kt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},ve.toMiliseconds(ve.ONE_SECOND)),o;const l=new Promise(async d=>{const h=f=>{f.topic===t&&(this.events.removeListener(Ci.created,h),d(f.id))};this.events.on(Ci.created,h);try{const f=await Js(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(Ci.created,h),d(f)}catch{}}),u=await Js(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(hn.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;const n=t[0].relay,r={method:i0(n.protocol).batchSubscribe,params:{topics:t.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await Js(new Promise((i,s)=>{this.relayer.request(r).then(i).catch(o=>{this.logger.warn(o),s(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(hn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;const n=t[0].relay,r={method:i0(n.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await Js(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(hn.connection_stalled)}return i}rpcUnsubscribe(t,n,r){const i={method:i0(r.protocol).unsubscribe,params:{topic:t,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(t,n){this.setSubscription(t,f4($h({},n),{id:t})),this.pending.delete(n.topic)}onBatchSubscribe(t){t.length&&t.forEach(n=>{this.setSubscription(n.id,$h({},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,$h({},n)),this.topicMap.set(n.topic,t),this.events.emit(Ci.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}=Ae("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(Ci.deleted,f4($h({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ci.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 i=t.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Ci.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}=Ae("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){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(t.map(async n=>f4($h({},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 xZ(ve.toMiliseconds(ve.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}=Ae("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 Fi(t+await this.getClientId())}}var Wte=Object.defineProperty,YI=Object.getOwnPropertySymbols,qte=Object.prototype.hasOwnProperty,Zte=Object.prototype.propertyIsEnumerable,h4=(e,t,n)=>t in e?Wte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,XI=(e,t)=>{for(var n in t||(t={}))qte.call(t,n)&&h4(e,n,t[n]);if(YI)for(var n of YI(t))Zte.call(t,n)&&h4(e,n,t[n]);return e},pt=(e,t,n)=>h4(e,typeof t!="symbol"?t+"":t,n);class Gte extends fJ{constructor(t){var n;super(t),pt(this,"protocol","wc"),pt(this,"version",2),pt(this,"core"),pt(this,"logger"),pt(this,"events",new zn.exports.EventEmitter),pt(this,"provider"),pt(this,"messages"),pt(this,"subscriber"),pt(this,"publisher"),pt(this,"name",_Q),pt(this,"transportExplicitlyClosed",!1),pt(this,"initialized",!1),pt(this,"connectionAttemptInProgress",!1),pt(this,"relayUrl"),pt(this,"projectId"),pt(this,"packageName"),pt(this,"bundleId"),pt(this,"hasExperiencedNetworkDisruption",!1),pt(this,"pingTimeout"),pt(this,"heartBeatTimeout",ve.toMiliseconds(ve.THIRTY_SECONDS+ve.FIVE_SECONDS)),pt(this,"reconnectTimeout"),pt(this,"connectPromise"),pt(this,"reconnectInProgress",!1),pt(this,"requestsInFlight",[]),pt(this,"connectTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),pt(this,"stalledRestartInProgress",!1),pt(this,"stalledRestartTimeout"),pt(this,"stalledRestartBackoff",0),pt(this,"stalledRestartBaseInterval",ve.toMiliseconds(ve.ONE_SECOND*2)),pt(this,"stalledRestartMaxInterval",ve.toMiliseconds(ve.THIRTY_SECONDS)),pt(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||rl().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.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}}),pt(this,"resetPingTimeout",()=>{Rg()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),pt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),pt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(hn.connect)}),pt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),pt(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(hn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(i=>this.logger.warn(i))}),pt(this,"registerProviderListeners",()=>{this.provider.on(zi.payload,this.onPayloadHandler),this.provider.on(zi.connect,this.onConnectHandler),this.provider.on(zi.disconnect,this.onDisconnectHandler),this.provider.on(zi.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=G8({logger:(n=t.logger)!=null?n:xQ,name:this.name}),this.messages=new Tte(this.logger,t.core),this.subscriber=new Vte(this,this.logger),this.publisher=new Bte(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||SI,cZ()?this.packageName=t7():lZ()&&(this.bundleId=t7()),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 Gr(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:Kt.relay},hm.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,n){var r,i,s;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:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c;const l=u=>{u.topic===t&&(this.subscriber.off(Ci.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Ci.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(t,XI({internal:{throwOnFailedPublish:o}},n)).catch(h=>{o&&d(h)})||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 Js(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(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.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await XS())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,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(t,n){const{topic:r}=t;if(!n.sessionExists){const i=mn(ve.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(hn.message,t),await this.recordMessageEvent(t,hm.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,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(zi.disconnect,s),await Js(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(zi.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(zi.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zi.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,ve.toMiliseconds(n*1))),n++}}startPingTimeout(){var t,n,r,i,s;if(Rg())try{(n=(t=this.provider)==null?void 0:t.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new i4(new uQ(pZ({sdkVersion:s4,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:i}=t;await this.messages.set(r,i,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 i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),r4(t)){if(!t.method.endsWith(SQ))return;const n=t.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:Kt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(XI({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else dm(t)&&this.events.emit(hn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,hm.inbound),this.events.emit(hn.message,t))}async acknowledgePayload(t){const n=Ch(t.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zi.payload,this.onPayloadHandler),this.provider.off(zi.connect,this.onConnectHandler),this.provider.off(zi.disconnect,this.onDisconnectHandler),this.provider.off(zi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await XS();uX(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(wu.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&hX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(hn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const n=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${n?` in ${n}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(r){this.logger.error(r,r?.message)}finally{this.stalledRestartInProgress=!1}},n)})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(hn.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},ve.toMiliseconds(IQ)))))}isInitialized(){if(!this.initialized){const{message:t}=Ae("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 Kte(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function JI(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function QI(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Yte="[object RegExp]",Xte="[object String]",Jte="[object Number]",Qte="[object Boolean]",e$="[object Arguments]",ene="[object Symbol]",tne="[object Date]",nne="[object Map]",rne="[object Set]",ine="[object Array]",sne="[object Function]",one="[object ArrayBuffer]",p4="[object Object]",ane="[object Error]",cne="[object DataView]",lne="[object Uint8Array]",une="[object Uint8ClampedArray]",dne="[object Uint16Array]",fne="[object Uint32Array]",hne="[object BigUint64Array]",pne="[object Int8Array]",gne="[object Int16Array]",mne="[object Int32Array]",yne="[object BigInt64Array]",wne="[object Float32Array]",bne="[object Float64Array]";function t$(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 vne(e,t,n){return Th(e,t,void 0,void 0,void 0,void 0,n)}function Th(e,t,n,r,i,s,o){const a=o(e,t,n,r,i,s);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 Nh(e,t,s,o)}return Nh(e,t,s,o)}function Nh(e,t,n,r){if(Object.is(e,t))return!0;let i=QI(e),s=QI(t);if(i===e$&&(i=p4),s===e$&&(s=p4),i!==s)return!1;switch(i){case Xte:return e.toString()===t.toString();case Jte:{const c=e.valueOf(),l=t.valueOf();return Kte(c,l)}case Qte:case tne:case ene:return Object.is(e.valueOf(),t.valueOf());case Yte:return e.source===t.source&&e.flags===t.flags;case sne: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(i){case nne:{if(e.size!==t.size)return!1;for(const[c,l]of e.entries())if(!t.has(c)||!Th(l,t.get(c),c,e,t,n,r))return!1;return!0}case rne:{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 d=c[u],h=l.findIndex(f=>Th(d,f,void 0,e,t,n,r));if(h===-1)return!1;l.splice(h,1)}return!0}case ine:case lne:case une:case dne:case fne:case hne:case pne:case gne:case mne:case yne:case wne:case bne:{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(!Th(e[c],t[c],c,e,t,n,r))return!1;return!0}case one:return e.byteLength!==t.byteLength?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case cne:return e.byteLength!==t.byteLength||e.byteOffset!==t.byteOffset?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case ane:return e.name===t.name&&e.message===t.message;case p4:{if(!(Nh(e.constructor,t.constructor,n,r)||t$(e)&&t$(t)))return!1;const c=[...Object.keys(e),...JI(e)],l=[...Object.keys(t),...JI(t)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=e[d];if(!Object.hasOwn(t,d))return!1;const f=t[d];if(!Th(h,f,d,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Ene(){}function Ane(e,t){return vne(e,t,Ene)}var Cne=Object.defineProperty,n$=Object.getOwnPropertySymbols,xne=Object.prototype.hasOwnProperty,_ne=Object.prototype.propertyIsEnumerable,g4=(e,t,n)=>t in e?Cne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,r$=(e,t)=>{for(var n in t||(t={}))xne.call(t,n)&&g4(e,n,t[n]);if(n$)for(var n of n$(t))_ne.call(t,n)&&g4(e,n,t[n]);return e},ei=(e,t,n)=>g4(e,typeof t!="symbol"?t+"":t,n);class Cu extends hJ{constructor(t,n,r,i=so,s=void 0){super(t,n,r,i),this.core=t,this.logger=n,this.name=r,ei(this,"map",new Map),ei(this,"version",$Q),ei(this,"cached",[]),ei(this,"initialized",!1),ei(this,"getKey"),ei(this,"storagePrefix",so),ei(this,"recentlyDeleted",[]),ei(this,"recentlyDeletedLimit",200),ei(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!$n(o)?this.map.set(this.getKey(o),o):HY(o)?this.map.set(o.id,o):jY(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ei(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())}),ei(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ei(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Ane(a[c],o[c]))):this.values)),ei(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=r$(r$({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ei(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=vi(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Gr(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:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(i),new Error(i)}const{message:r}=Ae("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}=Ae("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}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Sne=Object.defineProperty,Ine=(e,t,n)=>t in e?Sne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bt=(e,t,n)=>Ine(e,typeof t!="symbol"?t+"":t,n);class $ne{constructor(t,n){this.core=t,this.logger=n,bt(this,"name",OQ),bt(this,"version",kQ),bt(this,"events",new zn.exports),bt(this,"pairings"),bt(this,"initialized",!1),bt(this,"storagePrefix",so),bt(this,"ignoredPayloadTypes",[ec]),bt(this,"registeredMethods",[]),bt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),bt(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),bt(this,"create",async r=>{this.isInitialized();const i=j8(),s=await this.core.crypto.setSymKey(i),o=mn(ve.FIVE_MINUTES),a={protocol:_I},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},l=LS({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(vu.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:l}}),bt(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[oo.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=US(r.uri);i.props.properties.topic=s,i.addTrace(oo.pairing_uri_validation_success),i.addTrace(oo.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(oo.existing_pairing),u.active)throw i.setError(rc.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(oo.pairing_not_expired)}const d=c||mn(ve.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(oo.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(vu.create,h),i.addTrace(oo.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(oo.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(rc.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(rc.subscribe_pairing_topic_failure),f}return i.addTrace(oo.subscribe_pairing_topic_success),h}),bt(this,"activate",async({topic:r})=>{this.isInitialized();const i=mn(ve.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),bt(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:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=uu();this.events.once(Rt("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),bt(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),bt(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),bt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),bt(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(i))}),bt(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return LS({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),bt(this,"sendRequest",async(r,i,s)=>{const o=ws(i,s),a=await this.core.crypto.encode(r,o),c=xh[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),bt(this,"sendResult",async(r,i,s)=>{const o=Ch(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"sendError",async(r,i,s)=>{const o=um(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c]?xh[c].res:xh.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),bt(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Qs(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),bt(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),bt(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),bt(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(vu.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{io(i)?this.events.emit(Rt("pairing_ping",s),{}):ji(i)&&this.events.emit(Rt("pairing_ping",s),{error:i.error})},500)}),bt(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(vu.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Gt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),bt(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",r))}),bt(this,"isValidPair",(r,i)=>{var s;if(!Jr(r)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!FY(r.uri)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}const o=US(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&ve.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(rc.pairing_expired);const{message:a}=Ae("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),bt(this,"isValidPing",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidDisconnect",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidPairingTopic",async r=>{if(!yn(r,!1)){const{message:i}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Qs(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=Ae("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=t,this.logger=vi(n,this.name),this.pairings=new Cu(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Gr(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(hn.message,async t=>{const{topic:n,message:r,transportType:i}=t;if(this.pairings.keys.includes(n)&&i!==Kt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);r4(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):dm(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Vi.expired,async t=>{const{topic:n}=s7(t.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(vu.expire,{topic:n}))})}}var Tne=Object.defineProperty,Nne=(e,t,n)=>t in e?Tne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kn=(e,t,n)=>Nne(e,typeof t!="symbol"?t+"":t,n);class Pne extends lJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,Kn(this,"records",new Map),Kn(this,"events",new zn.exports.EventEmitter),Kn(this,"name",RQ),Kn(this,"version",BQ),Kn(this,"cached",[]),Kn(this,"initialized",!1),Kn(this,"storagePrefix",so),Kn(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)}),Kn(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:mn(ve.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(bs.created,o)}),Kn(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 i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=ji(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(bs.updated,i))}),Kn(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Kn(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(bs.deleted,s)}}),this.persist()}),Kn(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Kn(this,"on",(r,i)=>{this.events.on(r,i)}),Kn(this,"once",(r,i)=>{this.events.once(r,i)}),Kn(this,"off",(r,i)=>{this.events.off(r,i)}),Kn(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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:ws(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}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(bs.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:n}=Ae("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(bs.created,t=>{const n=bs.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.updated,t=>{const n=bs.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.deleted,t=>{const n=bs.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.core.heartbeat.on(wu.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(n=>{ve.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(bs.deleted,n,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var One=Object.defineProperty,kne=(e,t,n)=>t in e?One(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hr=(e,t,n)=>kne(e,typeof t!="symbol"?t+"":t,n);class Rne extends gJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,hr(this,"expirations",new Map),hr(this,"events",new zn.exports.EventEmitter),hr(this,"name",MQ),hr(this,"version",DQ),hr(this,"cached",[]),hr(this,"initialized",!1),hr(this,"storagePrefix",so),hr(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)}),hr(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),hr(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Vi.created,{target:s,expiration:o})}),hr(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),hr(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Vi.deleted,{target:i,expiration:s})}}),hr(this,"on",(r,i)=>{this.events.on(r,i)}),hr(this,"once",(r,i)=>{this.events.once(r,i)}),hr(this,"off",(r,i)=>{this.events.off(r,i)}),hr(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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 gZ(t);if(typeof t=="number")return mZ(t);const{message:n}=Ae("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(Vi.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:n}=Ae("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}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(t,n){const{expiry:r}=n;ve.toMiliseconds(r)-Date.now()<=0&&this.expire(t,n)}expire(t,n){this.expirations.delete(t),this.events.emit(Vi.expired,{target:t,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,n)=>this.checkExpiry(n,t))}registerEventListeners(){this.core.heartbeat.on(wu.pulse,()=>this.checkExpirations()),this.events.on(Vi.created,t=>{const n=Vi.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.expired,t=>{const n=Vi.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.deleted,t=>{const n=Vi.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Bne=Object.defineProperty,Mne=(e,t,n)=>t in e?Bne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wn=(e,t,n)=>Mne(e,typeof t!="symbol"?t+"":t,n);class Dne extends mJ{constructor(t,n,r){super(t,n,r),this.core=t,this.logger=n,this.store=r,wn(this,"name",UQ),wn(this,"abortController"),wn(this,"isDevEnv"),wn(this,"verifyUrlV3",FQ),wn(this,"storagePrefix",so),wn(this,"version",CI),wn(this,"publicKey"),wn(this,"fetchPromise"),wn(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&ve.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),wn(this,"register",async i=>{if(!Yd()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=Kl(),u=this.startAbortTimer(ve.ONE_SECOND*5),d=await new Promise((h,f)=>{const p=()=>{window.removeEventListener("message",y),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=A=>{if(A.data&&typeof A.data=="string")try{const _=JSON.parse(A.data);if(_.type==="verify_attestation"){if(Gb(_.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),h(_.attestation===null?"":_.attestation)}}catch(_){this.logger.warn(_)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(d,"jwt attestation"),d}catch(l){this.logger.warn(l)}return""}),wn(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Gb(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),wn(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(ve.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),wn(this,"getVerifyUrl",i=>{let s=i||_h;return HQ.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${_h}`),s=_h),s}),wn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(ve.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),wn(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),wn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),wn(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),wn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),wn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),wn(this,"validateAttestation",(i,s)=>{const o=fY(i,s.publicKey),a={hasExpired:ve.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=vi(n,this.name),this.abortController=new AbortController,this.isDevEnv=d8(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Gr(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ve.toMiliseconds(t))}}var Une=Object.defineProperty,Lne=(e,t,n)=>t in e?Une(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,i$=(e,t,n)=>Lne(e,typeof t!="symbol"?t+"":t,n);class Fne extends yJ{constructor(t,n){super(t,n),this.projectId=t,this.logger=n,i$(this,"context",jQ),i$(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${zQ}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=vi(n,this.context)}}var Hne=Object.defineProperty,s$=Object.getOwnPropertySymbols,jne=Object.prototype.hasOwnProperty,zne=Object.prototype.propertyIsEnumerable,m4=(e,t,n)=>t in e?Hne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ph=(e,t)=>{for(var n in t||(t={}))jne.call(t,n)&&m4(e,n,t[n]);if(s$)for(var n of s$(t))zne.call(t,n)&&m4(e,n,t[n]);return e},Dn=(e,t,n)=>m4(e,typeof t!="symbol"?t+"":t,n);class Vne extends wJ{constructor(t,n,r=!0){super(t,n,r),this.core=t,this.logger=n,Dn(this,"context",WQ),Dn(this,"storagePrefix",so),Dn(this,"storageVersion",VQ),Dn(this,"events",new Map),Dn(this,"shouldPersist",!1),Dn(this,"init",async()=>{if(!d8())try{const i={eventId:a7(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:r7(this.core.relayer.protocol,this.core.relayer.version,s4)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Dn(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=a7(),u=this.core.projectId||"",d=Date.now(),h=Ph({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Dn(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ph(Ph({},a),this.setMethods(a.eventId))}),Dn(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Dn(this,"setEventListeners",()=>{this.core.heartbeat.on(wu.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{ve.fromMiliseconds(Date.now())-ve.fromMiliseconds(i.timestamp)>qQ&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Dn(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Dn(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Dn(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ph(Ph({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Dn(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Dn(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZQ}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${s4}${s}`,{method:"POST",body:JSON.stringify(i)})}),Dn(this,"getAppDomain",()=>n7().url),this.logger=vi(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 Wne=Object.defineProperty,o$=Object.getOwnPropertySymbols,qne=Object.prototype.hasOwnProperty,Zne=Object.prototype.propertyIsEnumerable,y4=(e,t,n)=>t in e?Wne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a$=(e,t)=>{for(var n in t||(t={}))qne.call(t,n)&&y4(e,n,t[n]);if(o$)for(var n of o$(t))Zne.call(t,n)&&y4(e,n,t[n]);return e},qt=(e,t,n)=>y4(e,typeof t!="symbol"?t+"":t,n);class w4 extends sJ{constructor(t){var n;super(t),qt(this,"protocol",AI),qt(this,"version",CI),qt(this,"name",fm),qt(this,"relayUrl"),qt(this,"projectId"),qt(this,"customStoragePrefix"),qt(this,"events",new zn.exports.EventEmitter),qt(this,"logger"),qt(this,"heartbeat"),qt(this,"relayer"),qt(this,"crypto"),qt(this,"storage"),qt(this,"history"),qt(this,"expirer"),qt(this,"pairing"),qt(this,"verify"),qt(this,"echoClient"),qt(this,"linkModeSupportedApps"),qt(this,"eventClient"),qt(this,"initialized",!1),qt(this,"logChunkController"),qt(this,"on",(a,c)=>this.events.on(a,c)),qt(this,"once",(a,c)=>this.events.once(a,c)),qt(this,"off",(a,c)=>this.events.off(a,c)),qt(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),qt(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Kt.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||SI,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const i=Z_({level:typeof t?.logger=="string"&&t.logger?t.logger:pQ.logger,name:fm}),{logger:s,chunkLoggerController:o}=a8({opts:i,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=vi(s,this.name),this.heartbeat=new K8,this.crypto=new Ete(this,this.logger,t?.keychain),this.history=new Pne(this,this.logger),this.expirer=new Rne(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new nJ(a$(a$({},gQ),t?.storageOptions)),this.relayer=new Gte({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $ne(this,this.logger),this.verify=new Dne(this,this.logger,this.storage),this.echoClient=new Fne(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Vne(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new w4(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(TQ,r),n}get context(){return Gr(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(II,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(II)||[],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 Gne=w4,c$="wc",l$=2,u$="client",b4=`${c$}@${l$}:${u$}:`,v4={name:u$,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},d$="WALLETCONNECT_DEEPLINK_CHOICE",Kne="proposal",f$="Proposal expired",Yne="session",l0=ve.SEVEN_DAYS,Xne="engine",Yn={wc_sessionPropose:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ve.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ve.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1119}}},E4={min:ve.FIVE_MINUTES,max:ve.SEVEN_DAYS},co={idle:"IDLE",active:"ACTIVE"},Jne={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:""}},Qne="request",ere=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tre="wc",nre="auth",rre="authKeys",ire="pairingTopics",sre="requests",gm=`${tre}@${1.5}:${nre}:`,mm=`${gm}:PUB_KEY`;var ore=Object.defineProperty,are=Object.defineProperties,cre=Object.getOwnPropertyDescriptors,h$=Object.getOwnPropertySymbols,lre=Object.prototype.hasOwnProperty,ure=Object.prototype.propertyIsEnumerable,A4=(e,t,n)=>t in e?ore(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pt=(e,t)=>{for(var n in t||(t={}))lre.call(t,n)&&A4(e,n,t[n]);if(h$)for(var n of h$(t))ure.call(t,n)&&A4(e,n,t[n]);return e},Xn=(e,t)=>are(e,cre(t)),ye=(e,t,n)=>A4(e,typeof t!="symbol"?t+"":t,n);class dre extends AJ{constructor(t){super(t),ye(this,"name",Xne),ye(this,"events",new zn.exports),ye(this,"initialized",!1),ye(this,"requestQueue",{state:co.idle,queue:[]}),ye(this,"sessionRequestQueue",{state:co.idle,queue:[]}),ye(this,"emittedSessionRequests",new _Z({limit:500})),ye(this,"requestQueueDelay",ve.ONE_SECOND),ye(this,"expectedPairingMethodMap",new Map),ye(this,"recentlyDeletedMap",new Map),ye(this,"recentlyDeletedLimit",200),ye(this,"relayMessageCache",[]),ye(this,"pendingSessions",new Map),ye(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(Yn)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay)))}),ye(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Xn(Pt({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=BY(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:d,walletPay:h}=i,f=((r=d?.[0])==null?void 0:r.ttl)||Yn.wc_sessionPropose.req.ttl||ve.FIVE_MINUTES;this.validateRequestExpiry(f);let p=s,g,y=!1;try{if(p){const U=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),y=U.active}}catch(U){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),U}if(!p||!y){const{topic:U,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=U,g=j}if(!p){const{message:U}=Ae("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const A=await this.client.core.crypto.generateKeyPair(),_=mn(f),v=Pt(Xn(Pt(Pt({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:_I}],proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:_,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:ro()}),(d||h)&&{requests:{authentication:d?.map(U=>{const{domain:j,chains:W,nonce:S,uri:x,exp:I,nbf:m,type:b,statement:$,requestId:N,resources:P,signatureTypes:B}=U;return{domain:j,chains:W,nonce:S,type:b??"caip122",aud:x,version:"1",iat:new Date().toISOString(),exp:I,nbf:m,statement:$,requestId:N,resources:P,signatureTypes:B}}),walletPay:h}}),w=Rt("session_connect",v.id),{reject:T,resolve:O,done:D}=uu(f,f$),F=({id:U})=>{U===v.id&&(this.client.events.off("proposal_expire",F),this.pendingSessions.delete(v.id),this.events.emit(w,{error:{message:f$,code:0}}))};return this.client.events.on("proposal_expire",F),this.events.once(w,({error:U,session:j})=>{this.client.events.off("proposal_expire",F),U?T(U):j&&O(j)}),await this.setProposal(v.id,v),await this.sendProposeSession({proposal:v,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:v.id}}}).catch(U=>{throw this.deleteProposal(v.id),U}),{uri:g,approval:D}}),ye(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}}),ye(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[vs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Eu.no_internet_connection),j}try{await this.isValidProposalId(n?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Eu.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Eu.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:A,optionalNamespaces:_}=p;let v=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});v||(v=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:vs.session_approve_started,properties:{topic:g,trace:[vs.session_approve_started,vs.session_namespaces_validation_success]}}));const w=await this.client.core.crypto.generateKeyPair(),T=y.publicKey,O=await this.client.core.crypto.generateSharedKey(w,T),D=Xn(Pt(Pt(Pt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:w,metadata:this.client.metadata},expiry:mn(l0)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{proposalRequestsResponses:f}),F=Kt.relay;v.addTrace(vs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:F,internal:{skipSubscribe:!0}})}catch(j){throw v.setError(Eu.subscribe_session_topic_failure),j}v.addTrace(vs.subscribe_session_topic_success);const U=Xn(Pt({},D),{topic:O,requiredNamespaces:A,optionalNamespaces:_,pairingTopic:g,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:w,transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(O,U),v.addTrace(vs.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:w},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:Pt({correlationId:a},this.getTVFApproveParams(U))}}),v.addTrace(vs.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(O,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),j}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(O,mn(l0)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),ye(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:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Yn.wc_sessionPropose.reject}),await this.deleteProposal(r)}),ye(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=ro(),l=rl().toString(),u=this.client.session.get(r).namespaces;return this.events.once(Rt("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:s}}),ye(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,i=ro(),{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Rt("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,mn(l0)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),ye(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:i,topic:s,expiry:o=Yn.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=ro(),l=rl().toString(),{done:u,resolve:d,reject:h}=uu(o,"Request expired. Please try again.");this.events.once(Rt("session_request",c),({error:y,result:A})=>{y?h(y):d(A)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await u();const g={request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(A=>h(A)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var A;if(!((A=a.sessionConfig)!=null&&A.disableDeepLink)){const _=await vZ(this.client.core.storage,d$);await yZ({id:c,topic:s,wcDeepLink:_})}y()}),u()]).then(y=>y[2])}),ye(this,"respond",async n=>{var r,i;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((i=(r=n?.response)==null?void 0:r.id)==null?void 0:i.toString()),trace:[vs.session_request_response_started]}});try{await this.isValidRespond(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_validation_failure),d}s.addTrace(vs.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,l=this.client.session.get(o);l.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(vs.session_request_response_publish_started),io(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):ji(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_publish_failure),d}}),ye(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ro(),s=rl().toString(),{done:o,resolve:a,reject:c}=uu(ve.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Rt("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),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}))}),ye(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=rl().toString(),a=ro();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),ye(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:Gt("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:i}=Ae("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),ye(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>UY(r,n)))),ye(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),ye(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?Kt.link_mode:Kt.relay;o===Kt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:p,methods:g=[],expiry:y}=n,A=[...n.resources||[]],{topic:_,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:v}});const w=await this.client.core.crypto.generateKeyPair(),T=tm(w);if(await Promise.all([this.client.auth.authKeys.set(mm,{responseTopic:T,publicKey:w}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:_})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${_}`),g.length>0){const{namespace:P}=Ga(a[0]);let B=DG(P,"request",g);zg(A)&&(B=LG(B,A.pop())),A.push(B)}const O=y&&y>Yn.wc_sessionAuthenticate.req.ttl?y:Yn.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:p,resources:A},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(O)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},U={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(Yn.wc_sessionPropose.req.ttl),id:ro()},{done:j,resolve:W,reject:S}=uu(O,"Request expired"),x=ro(),I=Rt("session_connect",U.id),m=Rt("session_request",x),b=async({error:P,session:B})=>{this.events.off(m,$),P?S(P):B&&W({session:B})},$=async P=>{var B,V,Z;if(await this.deletePendingAuthRequest(x,{message:"fulfilled",code:0}),P.error){const ue=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===ue.code?void 0:(this.events.off(I,b),S(P.error.message))}await this.deleteProposal(U.id),this.events.off(I,b);const{cacaos:Y,responder:X}=P.result,G=[],ne=[];for(const ue of Y){await k7({cacao:ue,projectId:this.client.core.projectId})||(this.client.logger.error(ue,"Signature verification failed"),S(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ge}=ue,Be=zg(ge.resources),Fe=[b8(ge.iss)],qe=jg(ge.iss);if(Be){const ct=M7(Be),St=D7(Be);G.push(...ct),Fe.push(...St)}for(const ct of Fe)ne.push(`${ct}:${qe}`)}const se=await this.client.core.crypto.generateSharedKey(w,X.publicKey);let we;G.length>0&&(we={topic:se,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:mn(l0),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:VS([...new Set(G)],[...new Set(ne)]),transportType:o},await this.client.core.relayer.subscribe(se,{transportType:o}),await this.client.session.set(se,we),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:X.metadata}),we=this.client.session.get(se)),(B=this.client.metadata.redirect)!=null&&B.linkMode&&(V=X.metadata.redirect)!=null&&V.linkMode&&(Z=X.metadata.redirect)!=null&&Z.universal&&r&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(se,{transportType:Kt.link_mode})),W({auths:Y,session:we})};this.events.once(I,b),this.events.once(m,$);let N;try{if(s){const P=ws("wc_sessionAuthenticate",D,x);this.client.core.history.set(_,P);const B=await this.client.core.crypto.encode("",P,{type:mh,encoding:nl});N=rm(r,_,B)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:D,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:x}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:U,expiry:Yn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:U.id})])}catch(P){throw this.events.off(I,b),this.events.off(m,$),P}return await this.setProposal(U.id,U),await this.setAuthRequest(x,{request:Xn(Pt({},D),{verifyContext:{}}),pairingTopic:_,transportType:o}),{uri:N??v,response:j}}),ye(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Au.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Sh.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Sh.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Kt.relay;a===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=tm(c),d={type:ec,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const y of i){if(!await k7({cacao:y,projectId:this.client.core.projectId})){s.setError(Sh.invalid_cacao);const T=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:T,encodeOpts:d}),new Error(T.message)}s.addTrace(Au.cacaos_verified);const{p:A}=y,_=zg(A.resources),v=[b8(A.iss)],w=jg(A.iss);if(_){const T=M7(_),O=D7(_);h.push(...T),v.push(...O)}for(const T of v)f.push(`${T}:${w}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Au.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:mn(l0),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:VS([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Au.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw s.setError(Sh.subscribe_authenticated_session_topic_failure),y}s.addTrace(Au.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Au.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Au.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Sh.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:s.eventId}),{session:g}}),ye(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tm(o),l={type:ec,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:Yn.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),ye(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return R7(r,i)}),ye(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)}),ye(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),ye(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(d$).catch(l=>this.client.logger.warn(l)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=co.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===i).map(l=>this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),ye(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(Eu.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Gt("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),ye(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=co.idle,this.client.events.emit("session_request_expire",{id:n}))}),ye(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),ye(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}))}),ye(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,mn(Yn.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),ye(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=Kt.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),ye(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||mn(Yn.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),ye(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=n,f=ws(i,s,c);let p;const g=!!u;try{const _=g?nl:Xr;p=await this.client.core.crypto.encode(r,f,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),_}let y;if(ere.includes(i)){const _=Fi(JSON.stringify(f)),v=Fi(p);y=await this.client.core.verify.register({id:v,decryptedId:_})}const A=Pt(Pt({},Yn[i].req),h);if(A.attestation=y,o&&(A.ttl=o),a&&(A.id=a),this.client.core.history.set(r,f),g){const _=rm(u,r,p);await global.Linking.openURL(_,this.client.name)}else A.tvf=Xn(Pt({},d),{correlationId:f.id}),l?(A.internal=Xn(Pt({},A.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,A)):this.client.core.relayer.publish(r,p,A).catch(_=>this.client.logger.error(_));return f.id}),ye(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=ws("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:Xr}),a=Fi(JSON.stringify(s)),c=Fi(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:Xn(Pt({},i),{publishMethod:"wc_proposeSession",attestation:l})})}),ye(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=Ch(s.id,i),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Xr}),u=ws("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(r,u,{encoding:Xr});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:Xn(Pt({},a),{publishMethod:"wc_approveSession"})})}),ye(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=Ch(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,f;try{h=await this.client.core.history.get(i,r);const p=h.request;try{f=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(d){const p=rm(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Yn[p].res;g.tvf=Xn(Pt({},f),{correlationId:r}),o?(g.internal=Xn(Pt({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),ye(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=um(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,r)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),f}if(d){const f=rm(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,p=a||Yn[f].res;this.client.core.relayer.publish(i,u,p)}await this.client.core.history.resolve(l)}),ye(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;Qs(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Qs(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),ye(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),ye(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),ye(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===co.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=co.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=co.idle}),ye(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),ye(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),ye(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=Ae("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),ye(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),ye(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;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(rc.proposal_listener_not_found)),this.isValidConnect(Pt({},i.params));const u=a.expiryTimestamp||mn(Yn.wc_sessionPropose.req.ttl),d=Pt({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:Fi(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(oo.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Yn.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),ye(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(io(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:n,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:n})}else if(ji(r)){await this.deleteProposal(s);const o=Rt("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),ye(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=r.params,p=[...this.pendingSessions.values()].find(A=>A.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(p.proposalId),y=Xn(Pt(Pt(Pt({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Rt("session_connect",p.proposalId),{session:y})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;io(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(Rt("session_approve",i),{})):ji(r)&&(await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.events.emit(Rt("session_approve",i),{error:r.error}))}),ye(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Pt({topic:n},i));try{bh.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw bh.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),ye(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=Rt("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_update",i),{}):ji(r)&&this.events.emit(Rt("session_update",i),{error:r.error})}),ye(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,mn(l0)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=Rt("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_extend",i),{}):ji(r)&&this.events.emit(Rt("session_extend",i),{error:r.error})}),ye(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=Rt("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);io(r)?this.events.emit(Rt("session_ping",i),{}):ji(r)&&this.events.emit(Rt("session_ping",i),{error:r.error})},500)}),ye(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Gt("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),ye(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:d,params:h}=a;try{await this.isValidRequest(Pt({topic:o},h));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Fi(JSON.stringify(ws("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),u===Kt.link_mode&&(r=f.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),ye(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=Rt("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Pt({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),bh.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:Fi(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===Kt.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:ec,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Yn.wc_sessionAuthenticate.autoReject,appLink:h})}}),ye(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),ye(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=co.idle,this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay))}),ye(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(Rt("session_request",s.request.id),{error:r})})}),ye(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===co.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)}}),ye(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=co.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),ye(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:ws("wc_sessionPropose",Xn(Pt({},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})}),ye(this,"isValidConnect",async n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if($n(r)||await this.isValidPairingTopic(r),!YY(c,!0)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(i&&!$n(i)&&no(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!$n(s)&&no(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),ye(this,"validateNamespaces",(n,r)=>{const i=KY(n,"connect()",r);if(i)throw new Error(i.message)}),ye(this,"isValidApprove",async n=>{if(!Jr(n))throw new Error(Ae("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=W8(i,"approve()");if(l)throw new Error(l.message);const u=KS(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!yn(s,!0)){const{message:d}=Ae("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),ye(this,"isValidReject",async n=>{if(!Jr(n)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!JY(i)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),ye(this,"isValidSessionSettleRequest",n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!ZS(r)){const{message:l}=Ae("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=zY(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=W8(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Qs(o)){const{message:l}=Ae("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),ye(this,"isValidUpdate",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=W8(i,"update()");if(o)throw new Error(o.message);const a=KS(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),ye(this,"isValidExtend",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),ye(this,"isValidRequest",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!GS(a,s)){const{message:c}=Ae("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!QY(i)){const{message:c}=Ae("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!nX(a,s,i.method)){const{message:c}=Ae("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),ye(this,"isValidRespond",async n=>{var r;if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!eX(s)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==i){const{message:a}=Ae("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),ye(this,"isValidPing",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidEmit",async n=>{if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!GS(o,s)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!tX(i)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!rX(o,s,i.name)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),ye(this,"isValidDisconnect",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!yn(i,!1))throw new Error("uri is required parameter");if(!yn(s,!1))throw new Error("domain is required parameter");if(!yn(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ga(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ga(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),ye(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||_h,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Kt.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:i,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),ye(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=Ae("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),ye(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),ye(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),ye(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),ye(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,l,u,d,h;return!n||r!==Kt.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=n?.redirect)==null?void 0:u.universal)!==void 0&&((d=n?.redirect)==null?void 0:d.universal)!==""&&((h=n?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),ye(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),ye(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=o7(n,"topic")||"",i=decodeURIComponent(o7(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:Kt.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),ye(this,"registerLinkModeListeners",async()=>{var n;if(d8()||jc()&&(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 i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),ye(this,"getTVFApproveParams",n=>{try{const r=jS(n.namespaces),i=NY(n.namespaces),s=PY(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:i,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),ye(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,i);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}),ye(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),ye(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=Jne[s];if(s==="sui_signTransaction")return[wG(r.transactionBytes)];if(s==="near_signTransaction")return[$7(r)];if(s==="near_signTransactions")return r.map(c=>$7(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[EX({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Hi(r)?r.map(c=>T7(c)):[T7(r)];if(s==="cosmos_signDirect")return[vG(r)];if(s==="wallet_sendCalls")return EG(r);if(typeof r=="string")return[r];const a=r[o.key];if(Hi(a))return s==="solana_signAllTransactions"?a.map(c=>yG(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"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,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){const{topic:n,message:r,attestation:i,transportType:s}=t,{publicKey:o}=this.client.auth.authKeys.keys.includes(mm)?this.client.auth.authKeys.get(mm):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===Kt.link_mode?nl:Xr});r4(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Fi(r)})):dm(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Vi.expired,async t=>{const{topic:n,id:r}=s7(t.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Ae("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,Ae("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(vu.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(vu.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!yn(t,!1)){const{message:n}=Ae("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}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.core.pairing.pairings.get(t).expiry)){const{message:n}=Ae("EXPIRED",`pairing topic: ${t}`);throw new Error(n)}}async isValidSessionTopic(t){if(!yn(t,!1)){const{message:n}=Ae("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}=Ae("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});const{message:n}=Ae("EXPIRED",`session topic: ${t}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(t)){const{message:n}=Ae("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(yn(t,!1)){const{message:n}=Ae("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(n)}else{const{message:n}=Ae("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(n)}}async isValidProposalId(t){if(!XY(t)){const{message:n}=Ae("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(n)}if(!this.client.proposal.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);const{message:n}=Ae("EXPIRED",`proposal id: ${t}`);throw new Error(n)}}validateRequestExpiry(t){if(t&&!oX(t,E4)){const{message:n}=Ae("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${E4.min} and ${E4.max}`);throw new Error(n)}}}class fre extends Cu{constructor(t,n){super(t,n,Kne,b4),this.core=t,this.logger=n}}class hre extends Cu{constructor(t,n){super(t,n,Yne,b4),this.core=t,this.logger=n}}class pre extends Cu{constructor(t,n){super(t,n,Qne,b4,r=>r.id),this.core=t,this.logger=n}}class gre extends Cu{constructor(t,n){super(t,n,rre,gm,()=>mm),this.core=t,this.logger=n}}class mre extends Cu{constructor(t,n){super(t,n,ire,gm),this.core=t,this.logger=n}}class yre extends Cu{constructor(t,n){super(t,n,sre,gm,r=>r.id),this.core=t,this.logger=n}}var wre=Object.defineProperty,bre=(e,t,n)=>t in e?wre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C4=(e,t,n)=>bre(e,typeof t!="symbol"?t+"":t,n);class vre{constructor(t,n){this.core=t,this.logger=n,C4(this,"authKeys"),C4(this,"pairingTopics"),C4(this,"requests"),this.authKeys=new gre(this.core,this.logger),this.pairingTopics=new mre(this.core,this.logger),this.requests=new yre(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Ere=Object.defineProperty,Are=(e,t,n)=>t in e?Ere(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vt=(e,t,n)=>Are(e,typeof t!="symbol"?t+"":t,n);class x4 extends EJ{constructor(t){super(t),vt(this,"protocol",c$),vt(this,"version",l$),vt(this,"name",v4.name),vt(this,"metadata"),vt(this,"core"),vt(this,"logger"),vt(this,"events",new zn.exports.EventEmitter),vt(this,"engine"),vt(this,"session"),vt(this,"proposal"),vt(this,"pendingRequest"),vt(this,"auth"),vt(this,"signConfig"),vt(this,"on",(r,i)=>this.events.on(r,i)),vt(this,"once",(r,i)=>this.events.once(r,i)),vt(this,"off",(r,i)=>this.events.off(r,i)),vt(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),vt(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),vt(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),vt(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),vt(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=t?.name||v4.name,this.metadata=dZ(t?.metadata),this.signConfig=t?.signConfig;const n=G8({logger:t?.logger||v4.logger,name:this.name});this.logger=n,this.core=t?.core||new Gne(t),this.session=new hre(this.core,this.logger),this.proposal=new fre(this.core,this.logger),this.pendingRequest=new pre(this.core,this.logger),this.engine=new dre(this),this.auth=new vre(this.core,this.logger)}static async init(t){const n=new x4(t);return await n.initialize(),n}get context(){return Gr(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 Cre=x4;var _4={exports:{}};(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Pn<"u"&&Pn,r=function(){function s(){this.fetch=!1,this.DOMException=n.DOMException}return s.prototype=n,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Pn<"u"&&Pn||{},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]"],d=ArrayBuffer.isView||function(m){return m&&u.indexOf(Object.prototype.toString.call(m))>-1};function h(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 f(m){return typeof m!="string"&&(m=String(m)),m}function p(m){var b={next:function(){var $=m.shift();return{done:$===void 0,value:$}}};return c.iterable&&(b[Symbol.iterator]=function(){return b}),b}function g(m){this.map={},m instanceof g?m.forEach(function(b,$){this.append($,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=h(m),b=f(b);var $=this.map[m];this.map[m]=$?$+", "+b:b},g.prototype.delete=function(m){delete this.map[h(m)]},g.prototype.get=function(m){return m=h(m),this.has(m)?this.map[m]:null},g.prototype.has=function(m){return this.map.hasOwnProperty(h(m))},g.prototype.set=function(m,b){this.map[h(m)]=f(b)},g.prototype.forEach=function(m,b){for(var $ in this.map)this.map.hasOwnProperty($)&&m.call(b,this.map[$],$,this)},g.prototype.keys=function(){var m=[];return this.forEach(function(b,$){m.push($)}),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,$){m.push([$,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 A(m){return new Promise(function(b,$){m.onload=function(){b(m.result)},m.onerror=function(){$(m.error)}})}function _(m){var b=new FileReader,$=A(b);return b.readAsArrayBuffer(m),$}function v(m){var b=new FileReader,$=A(b),N=/charset=([A-Za-z0-9_-]+)/.exec(m.type),P=N?N[1]:"utf-8";return b.readAsText(m,P),$}function w(m){for(var b=new Uint8Array(m),$=new Array(b.length),N=0;N<b.length;N++)$[N]=String.fromCharCode(b[N]);return $.join("")}function T(m){if(m.slice)return m.slice(0);var b=new Uint8Array(m.byteLength);return b.set(new Uint8Array(m)),b.buffer}function O(){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=T(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||d(m))?this._bodyArrayBuffer=T(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 v(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(w(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(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(m){var b=m.toUpperCase();return D.indexOf(b)>-1?b:m}function U(m,b){if(!(this instanceof U))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var $=b.body;if(m instanceof U){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,!$&&m._bodyInit!=null&&($=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=F(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||function(){if("AbortController"in a){var B=new AbortController;return B.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&$)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody($),(this.method==="GET"||this.method==="HEAD")&&(b.cache==="no-store"||b.cache==="no-cache")){var N=/([?&])_=[^&]*/;if(N.test(this.url))this.url=this.url.replace(N,"$1_="+new Date().getTime());else{var P=/\?/;this.url+=(P.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function j(m){var b=new FormData;return m.trim().split("&").forEach(function($){if($){var N=$.split("="),P=N.shift().replace(/\+/g," "),B=N.join("=").replace(/\+/g," ");b.append(decodeURIComponent(P),decodeURIComponent(B))}}),b}function W(m){var b=new g,$=m.replace(/\r?\n[\t ]+/g," ");return $.split("\r").map(function(N){return N.indexOf(`
41
+ ***************************************************************************** */var e4=function(e,t){return e4=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},e4(e,t)};function NJ(e,t){e4(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var t4=function(){return t4=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},t4.apply(this,arguments)};function PJ(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 i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function OJ(e,t,n,r){var i=arguments.length,s=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s}function kJ(e,t){return function(n,r){t(n,r,e)}}function RJ(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function BJ(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function MJ(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,i=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function DJ(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}function UJ(e,t){for(var n in e)n!=="default"&&!t.hasOwnProperty(n)&&(t[n]=e[n])}function n4(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 dI(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,s=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function LJ(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(dI(arguments[t]));return e}function FJ(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ah(e){return this instanceof Ah?(this.v=e,this):new Ah(e)}function HJ(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(f){return new Promise(function(p,g){s.push([h,f,p,g])>1||a(h,f)})})}function a(h,f){try{c(r[h](f))}catch(p){d(s[0][3],p)}}function c(h){h.value instanceof Ah?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function jJ(e){var t,n;return t={},r("next"),r("throw",function(i){throw i}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(i,s){t[i]=e[i]?function(o){return(n=!n)?{value:Ah(e[i](o)),done:i==="return"}:s?s(o):o}:s}}function zJ(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 n4=="function"?n4(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function VJ(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function WJ(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 qJ(e){return e&&e.__esModule?e:{default:e}}function ZJ(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function GJ(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 KJ=Object.freeze({__proto__:null,__extends:NJ,get __assign(){return t4},__rest:PJ,__decorate:OJ,__param:kJ,__metadata:RJ,__awaiter:BJ,__generator:MJ,__createBinding:DJ,__exportStar:UJ,__values:n4,__read:dI,__spread:LJ,__spreadArrays:FJ,__await:Ah,__asyncGenerator:HJ,__asyncDelegator:jJ,__asyncValues:zJ,__makeTemplateObject:VJ,__importStar:WJ,__importDefault:qJ,__classPrivateFieldGet:ZJ,__classPrivateFieldSet:GJ}),YJ=XE(KJ),tc={},fI;function XJ(){if(fI)return tc;fI=1,Object.defineProperty(tc,"__esModule",{value:!0}),tc.isBrowserCryptoAvailable=tc.getSubtleCrypto=tc.getBrowerCrypto=void 0;function e(){return Pn?.crypto||Pn?.msCrypto||{}}tc.getBrowerCrypto=e;function t(){const r=e();return r.subtle||r.webkitSubtle}tc.getSubtleCrypto=t;function n(){return!!e()&&!!t()}return tc.isBrowserCryptoAvailable=n,tc}var nc={},hI;function JJ(){if(hI)return nc;hI=1,Object.defineProperty(nc,"__esModule",{value:!0}),nc.isBrowser=nc.isNode=nc.isReactNative=void 0;function e(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}nc.isReactNative=e;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}nc.isNode=t;function n(){return!e()&&!t()}return nc.isBrowser=n,nc}(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=YJ;t.__exportStar(XJ(),e),t.__exportStar(JJ(),e)})(uI);function ro(e=3){const t=Date.now()*Math.pow(10,e),n=Math.floor(Math.random()*Math.pow(10,e));return t+n}function rl(e=6){return BigInt(ro(e))}function ws(e,t,n){return{id:n||ro(),jsonrpc:"2.0",method:e,params:t}}function Ch(e,t){return{id:e,jsonrpc:"2.0",result:t}}function um(e,t,n){return{id:e,jsonrpc:"2.0",error:QJ(t,n)}}function QJ(e,t){return typeof e>"u"?cI(oI):(typeof e=="string"&&(e=Object.assign(Object.assign({},cI(Q8)),{message:e})),typeof t<"u"&&(e.data=t),$J(e.code)&&(e=TJ(e.code)),e)}class eQ{}class tQ extends eQ{constructor(){super()}}class nQ extends tQ{constructor(t){super()}}const rQ="^https?:",iQ="^wss?:";function sQ(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function pI(e,t){const n=sQ(e);return typeof n>"u"?!1:new RegExp(t).test(n)}function gI(e){return pI(e,rQ)}function mI(e){return pI(e,iQ)}function oQ(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function yI(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function r4(e){return yI(e)&&"method"in e}function dm(e){return yI(e)&&(io(e)||ji(e))}function io(e){return"result"in e}function ji(e){return"error"in e}class i4 extends nQ{constructor(t){super(t),this.events=new zn.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(ws(t.method,t.params||[],t.id||rl().toString()),n)}async requestStrict(t,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${t.id}`,s=>{ji(s)?i(s.error):r(s.result)});try{await this.connection.send(t,n)}catch(s){i(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),dm(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 aQ=()=>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"),cQ=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",wI=e=>e.split("?")[0],bI=10,lQ=aQ();class uQ{constructor(t){if(this.url=t,this.events=new zn.exports.EventEmitter,this.registering=!1,!mI(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(ou(t))}catch(n){this.onError(t.id,n)}}register(t=this.url){if(!mI(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,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const i=uI.isReactNative()?void 0:{rejectUnauthorized:!oQ(t)},s=new lQ(t,[],i);cQ()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}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"?su(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),i=r.message||r.toString(),s=um(t,i);this.events.emit("payload",s)}parseError(t,n=this.url){return lI(t,wI(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>bI&&this.events.setMaxListeners(bI)}emitError(t){const n=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${wI(this.url)}`));return this.events.emit("register_error",n),n}}var dQ=Object.defineProperty,vI=Object.getOwnPropertySymbols,fQ=Object.prototype.hasOwnProperty,hQ=Object.prototype.propertyIsEnumerable,EI=(e,t,n)=>t in e?dQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nr=(e,t)=>{for(var n in t||(t={}))fQ.call(t,n)&&EI(e,n,t[n]);if(vI)for(var n of vI(t))hQ.call(t,n)&&EI(e,n,t[n]);return e};const AI="wc",CI=2,fm="core",so=`${AI}@2:${fm}:`,pQ={name:fm,logger:"error"},gQ={database:":memory:"},mQ="crypto",xI="client_ed25519_seed",yQ=ve.ONE_DAY,wQ="keychain",bQ="0.3",vQ="messages",EQ="0.3",AQ=ve.SIX_HOURS,CQ="publisher",_I="irn",xQ="error",SI="wss://relay.walletconnect.org",_Q="relayer",hn={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"},SQ="_subscription",zi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},IQ=.1,s4="2.23.6",Kt={link_mode:"link_mode",relay:"relay"},hm={inbound:"inbound",outbound:"outbound"},$Q="0.3",TQ="WALLETCONNECT_CLIENT_ID",II="WALLETCONNECT_LINK_MODE_APPS",Ci={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},NQ="subscription",PQ="0.3",OQ="pairing",kQ="0.3",xh={wc_pairingDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:0},res:{ttl:ve.ONE_DAY,prompt:!1,tag:0}}},vu={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},bs={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},RQ="history",BQ="0.3",MQ="expirer",Vi={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DQ="0.3",UQ="verify-api",LQ="https://verify.walletconnect.com",$I="https://verify.walletconnect.org",_h=$I,FQ=`${_h}/v3`,HQ=[LQ,$I],jQ="echo",zQ="https://echo.walletconnect.com",oo={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"},rc={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"},vs={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"},Eu={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"},Au={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"},Sh={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"},VQ=.1,WQ="event-client",qQ=86400,ZQ="https://pulse.walletconnect.org/batch";function GQ(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,A=0,_=p.length;A!==_&&p[A]===0;)A++,g++;for(var v=(_-A)*u+1>>>0,w=new Uint8Array(v);A!==_;){for(var T=p[A],O=0,D=v-1;(T!==0||O<y)&&D!==-1;D--,O++)T+=256*w[D]>>>0,w[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");y=O,A++}for(var F=v-y;F!==v&&w[F]===0;)F++;for(var U=c.repeat(g);F<v;++F)U+=e.charAt(w[F]);return U}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,A=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,v=new Uint8Array(_);p[g];){var w=n[p.charCodeAt(g)];if(w===255)return;for(var T=0,O=_-1;(w!==0||T<A)&&O!==-1;O--,T++)w+=a*v[O]>>>0,v[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=T,g++}if(p[g]!==" "){for(var D=_-A;D!==_&&v[D]===0;)D++;for(var F=new Uint8Array(y+(_-D)),U=y;D!==_;)F[U++]=v[D++];return F}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var KQ=GQ,YQ=KQ;const TI=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")},XQ=e=>new TextEncoder().encode(e),JQ=e=>new TextDecoder().decode(e);class QQ{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 eee{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 NI(this,t)}}class tee{constructor(t){this.decoders=t}or(t){return NI(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 NI=(e,t)=>new tee(Nr(Nr({},e.decoders||{[e.prefix]:e}),t.decoders||{[t.prefix]:t}));class nee{constructor(t,n,r,i){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new QQ(t,n,r),this.decoder=new eee(t,n,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const pm=({name:e,prefix:t,encode:n,decode:r})=>new nee(e,t,n,r),Ih=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=YQ(n,t);return pm({prefix:e,name:t,encode:r,decode:s=>TI(i(s))})},ree=(e,t,n,r)=>{const i={};for(let u=0;u<t.length;++u)i[t[u]]=u;let s=e.length;for(;e[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[e[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|d,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},iee=(e,t,n)=>{const r=t[t.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Gn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>pm({prefix:t,name:e,encode(i){return iee(i,r,n)},decode(i){return ree(i,r,n,e)}}),see=pm({prefix:"\0",name:"identity",encode:e=>JQ(e),decode:e=>XQ(e)});var oee=Object.freeze({__proto__:null,identity:see});const aee=Gn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cee=Object.freeze({__proto__:null,base2:aee});const lee=Gn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var uee=Object.freeze({__proto__:null,base8:lee});const dee=Ih({prefix:"9",name:"base10",alphabet:"0123456789"});var fee=Object.freeze({__proto__:null,base10:dee});const hee=Gn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pee=Gn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gee=Object.freeze({__proto__:null,base16:hee,base16upper:pee});const mee=Gn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yee=Gn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wee=Gn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bee=Gn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vee=Gn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eee=Gn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Aee=Gn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cee=Gn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xee=Gn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _ee=Object.freeze({__proto__:null,base32:mee,base32upper:yee,base32pad:wee,base32padupper:bee,base32hex:vee,base32hexupper:Eee,base32hexpad:Aee,base32hexpadupper:Cee,base32z:xee});const See=Ih({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iee=Ih({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $ee=Object.freeze({__proto__:null,base36:See,base36upper:Iee});const Tee=Ih({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nee=Ih({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Pee=Object.freeze({__proto__:null,base58btc:Tee,base58flickr:Nee});const Oee=Gn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kee=Gn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ree=Gn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bee=Gn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mee=Object.freeze({__proto__:null,base64:Oee,base64pad:kee,base64url:Ree,base64urlpad:Bee});const PI=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}"),Dee=PI.reduce((e,t,n)=>(e[n]=t,e),[]),Uee=PI.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function Lee(e){return e.reduce((t,n)=>(t+=Dee[n],t),"")}function Fee(e){const t=[];for(const n of e){const r=Uee[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const Hee=pm({prefix:"\u{1F680}",name:"base256emoji",encode:Lee,decode:Fee});var jee=Object.freeze({__proto__:null,base256emoji:Hee}),zee=kI,OI=128,Vee=127,Wee=~Vee,qee=Math.pow(2,31);function kI(e,t,n){t=t||[],n=n||0;for(var r=n;e>=qee;)t[n++]=e&255|OI,e/=128;for(;e&Wee;)t[n++]=e&255|OI,e>>>=7;return t[n]=e|0,kI.bytes=n-r+1,t}var Zee=o4,Gee=128,RI=127;function o4(e,r){var n=0,r=r||0,i=0,s=r,o,a=e.length;do{if(s>=a)throw o4.bytes=0,new RangeError("Could not decode varint");o=e[s++],n+=i<28?(o&RI)<<i:(o&RI)*Math.pow(2,i),i+=7}while(o>=Gee);return o4.bytes=s-r,n}var Kee=Math.pow(2,7),Yee=Math.pow(2,14),Xee=Math.pow(2,21),Jee=Math.pow(2,28),Qee=Math.pow(2,35),ete=Math.pow(2,42),tte=Math.pow(2,49),nte=Math.pow(2,56),rte=Math.pow(2,63),ite=function(e){return e<Kee?1:e<Yee?2:e<Xee?3:e<Jee?4:e<Qee?5:e<ete?6:e<tte?7:e<nte?8:e<rte?9:10},ste={encode:zee,decode:Zee,encodingLength:ite},BI=ste;const MI=(e,t,n=0)=>(BI.encode(e,t,n),t),DI=e=>BI.encodingLength(e),a4=(e,t)=>{const n=t.byteLength,r=DI(e),i=r+DI(n),s=new Uint8Array(i+n);return MI(e,s,0),MI(n,s,r),s.set(t,i),new ote(e,n,t,s)};class ote{constructor(t,n,r,i){this.code=t,this.size=n,this.digest=r,this.bytes=i}}const UI=({name:e,code:t,encode:n})=>new ate(e,t,n);class ate{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?a4(this.code,n):n.then(r=>a4(this.code,r))}else throw Error("Unknown type, must be binary type")}}const LI=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cte=UI({name:"sha2-256",code:18,encode:LI("SHA-256")}),lte=UI({name:"sha2-512",code:19,encode:LI("SHA-512")});var ute=Object.freeze({__proto__:null,sha256:cte,sha512:lte});const FI=0,dte="identity",HI=TI;var fte=Object.freeze({__proto__:null,identity:{code:FI,name:dte,encode:HI,digest:e=>a4(FI,HI(e))}});new TextEncoder,new TextDecoder;const jI=Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr({},oee),cee),uee),fee),gee),_ee),$ee),Pee),Mee),jee);Nr(Nr({},ute),fte);function zI(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function hte(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?zI(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function VI(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const WI=VI("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),c4=VI("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=hte(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),pte=Nr({utf8:WI,"utf-8":WI,hex:jI.base16,latin1:c4,ascii:c4,binary:c4},jI);function gte(e,t="utf8"){const n=pte[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?zI(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}var mte=Object.defineProperty,yte=(e,t,n)=>t in e?mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ao=(e,t,n)=>yte(e,typeof t!="symbol"?t+"":t,n);class wte{constructor(t,n){this.core=t,this.logger=n,ao(this,"keychain",new Map),ao(this,"name",wQ),ao(this,"version",bQ),ao(this,"initialized",!1),ao(this,"storagePrefix",so),ao(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ao(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ao(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),ao(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=Ae("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),ao(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=t,this.logger=vi(n,this.name)}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,l8(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var bte=Object.defineProperty,vte=(e,t,n)=>t in e?bte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t,n)=>vte(e,typeof t!="symbol"?t+"":t,n);class Ete{constructor(t,n,r){this.core=t,this.logger=n,Mn(this,"name",mQ),Mn(this,"keychain"),Mn(this,"randomSessionIdentifier",j8()),Mn(this,"initialized",!1),Mn(this,"clientId"),Mn(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Mn(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Mn(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=i_(i),o=r_(s.publicKey);return this.clientId=o,o}),Mn(this,"generateKeyPair",()=>{this.isInitialized();const i=iY();return this.setPrivateKey(i.publicKey,i.privateKey)}),Mn(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=i_(s),a=this.randomSessionIdentifier;return await IV(a,i,yQ,o)}),Mn(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=sY(a,s);return this.setSymKey(c,o)}),Mn(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||tm(i);return await this.keychain.set(o,i),o}),Mn(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"encode",async(i,s,o)=>{this.isInitialized();const a=kS(o),c=ou(s);if(BS(a))return cY(c,o?.encoding);if(RS(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return oY({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Mn(this,"decode",async(i,s,o)=>{this.isInitialized();const a=uY(s,o);if(BS(a)){const c=lY(s,o?.encoding);return su(c)}if(RS(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=aY({symKey:c,encoded:s,encoding:o?.encoding});return su(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Mn(this,"getPayloadType",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return mu(o.type)}),Mn(this,"getPayloadSenderPublicKey",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return o.senderPublicKey?Zr(o.senderPublicKey,Tr):void 0}),this.core=t,this.logger=vi(n,this.name),this.keychain=r||new wte(this.core,this.logger)}get context(){return Gr(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(xI)}catch{t=j8(),await this.keychain.set(xI,t)}return gte(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Ate=Object.defineProperty,Cte=Object.defineProperties,xte=Object.getOwnPropertyDescriptors,qI=Object.getOwnPropertySymbols,_te=Object.prototype.hasOwnProperty,Ste=Object.prototype.propertyIsEnumerable,l4=(e,t,n)=>t in e?Ate(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ite=(e,t)=>{for(var n in t||(t={}))_te.call(t,n)&&l4(e,n,t[n]);if(qI)for(var n of qI(t))Ste.call(t,n)&&l4(e,n,t[n]);return e},$te=(e,t)=>Cte(e,xte(t)),xi=(e,t,n)=>l4(e,typeof t!="symbol"?t+"":t,n);class Tte extends uJ{constructor(t,n){super(t,n),this.logger=t,this.core=n,xi(this,"messages",new Map),xi(this,"messagesWithoutClientAck",new Map),xi(this,"name",vQ),xi(this,"version",EQ),xi(this,"initialized",!1),xi(this,"storagePrefix",so),xi(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),xi(this,"set",async(r,i,s)=>{this.isInitialized();const o=Fi(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===hm.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,$te(Ite({},c),{[o]:i}))}return await this.persist(),o}),xi(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),xi(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),xi(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Fi(i);return typeof s[o]<"u"}),xi(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Fi(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),xi(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=vi(t,this.name),this.core=n}get context(){return Gr(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,l8(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,l8(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async getRelayerMessagesWithoutClientAck(){const t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?u8(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Nte=Object.defineProperty,Pte=Object.defineProperties,Ote=Object.getOwnPropertyDescriptors,ZI=Object.getOwnPropertySymbols,kte=Object.prototype.hasOwnProperty,Rte=Object.prototype.propertyIsEnumerable,u4=(e,t,n)=>t in e?Nte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a0=(e,t)=>{for(var n in t||(t={}))kte.call(t,n)&&u4(e,n,t[n]);if(ZI)for(var n of ZI(t))Rte.call(t,n)&&u4(e,n,t[n]);return e},GI=(e,t)=>Pte(e,Ote(t)),Wi=(e,t,n)=>u4(e,typeof t!="symbol"?t+"":t,n);class Bte extends dJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Wi(this,"events",new zn.exports.EventEmitter),Wi(this,"name",CQ),Wi(this,"queue",new Map),Wi(this,"publishTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),Wi(this,"initialPublishTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),Wi(this,"needsTransportRestart",!1),Wi(this,"publish",async(r,i,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const d=s?.ttl||AQ,h=s?.prompt||!1,f=s?.tag||0,p=s?.id||rl().toString(),g=i0(nm().protocol),y={id:p,method:s?.publishMethod||g.publish,params:a0({topic:r,message:i,ttl:d,prompt:h,tag:f,attestation:s?.attestation},s?.tvf)},A=`Failed to publish payload, please try again. id:${p} tag:${f}`;try{$n((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),$n((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const _=new Promise(async v=>{const w=({id:O})=>{var D;((D=y.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(hn.publish,w),v())};this.relayer.events.on(hn.publish,w);const T=Js(new Promise((O,D)=>{this.rpcPublish(y,s).then(O).catch(F=>{this.logger.warn(F,F?.message),D(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${f}`);try{await T,this.events.removeListener(hn.publish,w)}catch(O){this.queue.set(p,{request:y,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await Js(_,this.publishTimeout,A)}catch(_){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(_),(u=s?.internal)!=null&&u.throwOnFailedPublish)throw _}finally{this.queue.delete(p)}}),Wi(this,"publishCustom",async r=>{var i,s,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:d,tvf:h,publishMethod:f,prompt:p,tag:g,ttl:y=ve.FIVE_MINUTES}=u,A=u.id||rl().toString(),_=i0(nm().protocol),v=f||_.publish,w={id:A,method:v,params:a0(GI(a0({},l),{ttl:y,prompt:p,tag:g,attestation:d}),h)},T=`Failed to publish custom payload, please try again. id:${A} tag:${g}`;try{$n((i=w.params)==null?void 0:i.prompt)&&((s=w.params)==null||delete s.prompt),$n((o=w.params)==null?void 0:o.tag)&&((a=w.params)==null||delete a.tag);const O=new Promise(async D=>{const F=({id:j})=>{var W;((W=w.id)==null?void 0:W.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(hn.publish,F),D())};this.relayer.events.on(hn.publish,F);const U=Js(new Promise((j,W)=>{this.rpcPublish(w,u).then(j).catch(S=>{this.logger.warn(S,S?.message),W(S)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${v} id:${A} tag:${g}`);try{await U,this.events.removeListener(hn.publish,F)}catch(j){this.queue.set(A,{request:w,opts:u,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:A,payload:l,opts:u}}),await Js(O,this.publishTimeout,T)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(A)}}),Wi(this,"on",(r,i)=>{this.events.on(r,i)}),Wi(this,"once",(r,i)=>{this.events.once(r,i)}),Wi(this,"off",(r,i)=>{this.events.off(r,i)}),Wi(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=t,this.logger=vi(n,this.name),this.registerEventListeners()}get context(){return Gr(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(hn.publish,a0(a0({},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 i=t.attempt+1;this.queue.set(n,GI(a0({},t),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(r=t.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(wu.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hn.connection_stalled);return}this.checkQueue()}),this.relayer.on(hn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}var Mte=Object.defineProperty,Dte=(e,t,n)=>t in e?Mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,c0=(e,t,n)=>Dte(e,typeof t!="symbol"?t+"":t,n);class Ute{constructor(){c0(this,"map",new Map),c0(this,"set",(t,n)=>{const r=this.get(t);this.exists(t,n)||this.map.set(t,[...r,n])}),c0(this,"get",t=>this.map.get(t)||[]),c0(this,"exists",(t,n)=>this.get(t).includes(n)),c0(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 i=r.filter(s=>s!==n);if(!i.length){this.map.delete(t);return}this.map.set(t,i)}),c0(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Lte=Object.defineProperty,Fte=Object.defineProperties,Hte=Object.getOwnPropertyDescriptors,KI=Object.getOwnPropertySymbols,jte=Object.prototype.hasOwnProperty,zte=Object.prototype.propertyIsEnumerable,d4=(e,t,n)=>t in e?Lte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$h=(e,t)=>{for(var n in t||(t={}))jte.call(t,n)&&d4(e,n,t[n]);if(KI)for(var n of KI(t))zte.call(t,n)&&d4(e,n,t[n]);return e},f4=(e,t)=>Fte(e,Hte(t)),jt=(e,t,n)=>d4(e,typeof t!="symbol"?t+"":t,n);class Vte extends pJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,jt(this,"subscriptions",new Map),jt(this,"topicMap",new Ute),jt(this,"events",new zn.exports.EventEmitter),jt(this,"name",NQ),jt(this,"version",PQ),jt(this,"pending",new Map),jt(this,"cached",[]),jt(this,"initialized",!1),jt(this,"storagePrefix",so),jt(this,"subscribeTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),jt(this,"initialSubscribeTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),jt(this,"clientId"),jt(this,"batchSubscribeTopicsLimit",500),jt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),jt(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=nm(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),jt(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),jt(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),jt(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),jt(this,"on",(r,i)=>{this.events.on(r,i)}),jt(this,"once",(r,i)=>{this.events.once(r,i)}),jt(this,"off",(r,i)=>{this.events.off(r,i)}),jt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),jt(this,"start",async()=>{await this.onConnect()}),jt(this,"stop",async()=>{await this.onDisconnect()}),jt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),jt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),jt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(wu.pulse,async()=>{await this.checkPending()}),this.events.on(Ci.created,async r=>{const i=Ci.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Ci.deleted,async r=>{const i=Ci.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=t,this.logger=vi(n,this.name),this.clientId=""}get context(){return Gr(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 i=>await this.unsubscribeById(t,i,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 i=nm(r);await this.restartToComplete({topic:t,id:n,relay:i}),await this.rpcUnsubscribe(t,n,i);const s=Gt("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(t,n,r){var i,s;const o=await this.getSubscriptionId(t);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===Kt.relay)&&await this.restartToComplete({topic:t,id:t,relay:n});const a={method:i0(n.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===Kt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},ve.toMiliseconds(ve.ONE_SECOND)),o;const l=new Promise(async d=>{const h=f=>{f.topic===t&&(this.events.removeListener(Ci.created,h),d(f.id))};this.events.on(Ci.created,h);try{const f=await Js(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(Ci.created,h),d(f)}catch{}}),u=await Js(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(hn.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;const n=t[0].relay,r={method:i0(n.protocol).batchSubscribe,params:{topics:t.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await Js(new Promise((i,s)=>{this.relayer.request(r).then(i).catch(o=>{this.logger.warn(o),s(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(hn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;const n=t[0].relay,r={method:i0(n.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await Js(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(hn.connection_stalled)}return i}rpcUnsubscribe(t,n,r){const i={method:i0(r.protocol).unsubscribe,params:{topic:t,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(t,n){this.setSubscription(t,f4($h({},n),{id:t})),this.pending.delete(n.topic)}onBatchSubscribe(t){t.length&&t.forEach(n=>{this.setSubscription(n.id,$h({},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,$h({},n)),this.topicMap.set(n.topic,t),this.events.emit(Ci.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}=Ae("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(Ci.deleted,f4($h({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ci.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 i=t.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Ci.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}=Ae("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){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(t.map(async n=>f4($h({},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 xZ(ve.toMiliseconds(ve.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}=Ae("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 Fi(t+await this.getClientId())}}var Wte=Object.defineProperty,YI=Object.getOwnPropertySymbols,qte=Object.prototype.hasOwnProperty,Zte=Object.prototype.propertyIsEnumerable,h4=(e,t,n)=>t in e?Wte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,XI=(e,t)=>{for(var n in t||(t={}))qte.call(t,n)&&h4(e,n,t[n]);if(YI)for(var n of YI(t))Zte.call(t,n)&&h4(e,n,t[n]);return e},pt=(e,t,n)=>h4(e,typeof t!="symbol"?t+"":t,n);class Gte extends fJ{constructor(t){var n;super(t),pt(this,"protocol","wc"),pt(this,"version",2),pt(this,"core"),pt(this,"logger"),pt(this,"events",new zn.exports.EventEmitter),pt(this,"provider"),pt(this,"messages"),pt(this,"subscriber"),pt(this,"publisher"),pt(this,"name",_Q),pt(this,"transportExplicitlyClosed",!1),pt(this,"initialized",!1),pt(this,"connectionAttemptInProgress",!1),pt(this,"relayUrl"),pt(this,"projectId"),pt(this,"packageName"),pt(this,"bundleId"),pt(this,"hasExperiencedNetworkDisruption",!1),pt(this,"pingTimeout"),pt(this,"heartBeatTimeout",ve.toMiliseconds(ve.THIRTY_SECONDS+ve.FIVE_SECONDS)),pt(this,"reconnectTimeout"),pt(this,"connectPromise"),pt(this,"reconnectInProgress",!1),pt(this,"requestsInFlight",[]),pt(this,"connectTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),pt(this,"stalledRestartInProgress",!1),pt(this,"stalledRestartTimeout"),pt(this,"stalledRestartBackoff",0),pt(this,"stalledRestartBaseInterval",ve.toMiliseconds(ve.ONE_SECOND*2)),pt(this,"stalledRestartMaxInterval",ve.toMiliseconds(ve.THIRTY_SECONDS)),pt(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||rl().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.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}}),pt(this,"resetPingTimeout",()=>{Rg()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),pt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),pt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(hn.connect)}),pt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),pt(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(hn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(i=>this.logger.warn(i))}),pt(this,"registerProviderListeners",()=>{this.provider.on(zi.payload,this.onPayloadHandler),this.provider.on(zi.connect,this.onConnectHandler),this.provider.on(zi.disconnect,this.onDisconnectHandler),this.provider.on(zi.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=G8({logger:(n=t.logger)!=null?n:xQ,name:this.name}),this.messages=new Tte(this.logger,t.core),this.subscriber=new Vte(this,this.logger),this.publisher=new Bte(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||SI,cZ()?this.packageName=t7():lZ()&&(this.bundleId=t7()),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 Gr(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:Kt.relay},hm.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,n){var r,i,s;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:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c;const l=u=>{u.topic===t&&(this.subscriber.off(Ci.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Ci.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(t,XI({internal:{throwOnFailedPublish:o}},n)).catch(h=>{o&&d(h)})||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 Js(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(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.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await XS())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,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(t,n){const{topic:r}=t;if(!n.sessionExists){const i=mn(ve.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(hn.message,t),await this.recordMessageEvent(t,hm.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,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(zi.disconnect,s),await Js(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(zi.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(zi.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zi.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,ve.toMiliseconds(n*1))),n++}}startPingTimeout(){var t,n,r,i,s;if(Rg())try{(n=(t=this.provider)==null?void 0:t.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new i4(new uQ(pZ({sdkVersion:s4,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:i}=t;await this.messages.set(r,i,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 i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),r4(t)){if(!t.method.endsWith(SQ))return;const n=t.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:Kt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(XI({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else dm(t)&&this.events.emit(hn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,hm.inbound),this.events.emit(hn.message,t))}async acknowledgePayload(t){const n=Ch(t.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zi.payload,this.onPayloadHandler),this.provider.off(zi.connect,this.onConnectHandler),this.provider.off(zi.disconnect,this.onDisconnectHandler),this.provider.off(zi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await XS();uX(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(wu.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&hX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(hn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const n=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${n?` in ${n}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(r){this.logger.error(r,r?.message)}finally{this.stalledRestartInProgress=!1}},n)})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(hn.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},ve.toMiliseconds(IQ)))))}isInitialized(){if(!this.initialized){const{message:t}=Ae("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 Kte(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function JI(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function QI(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Yte="[object RegExp]",Xte="[object String]",Jte="[object Number]",Qte="[object Boolean]",e$="[object Arguments]",ene="[object Symbol]",tne="[object Date]",nne="[object Map]",rne="[object Set]",ine="[object Array]",sne="[object Function]",one="[object ArrayBuffer]",p4="[object Object]",ane="[object Error]",cne="[object DataView]",lne="[object Uint8Array]",une="[object Uint8ClampedArray]",dne="[object Uint16Array]",fne="[object Uint32Array]",hne="[object BigUint64Array]",pne="[object Int8Array]",gne="[object Int16Array]",mne="[object Int32Array]",yne="[object BigInt64Array]",wne="[object Float32Array]",bne="[object Float64Array]";function t$(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 vne(e,t,n){return Th(e,t,void 0,void 0,void 0,void 0,n)}function Th(e,t,n,r,i,s,o){const a=o(e,t,n,r,i,s);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 Nh(e,t,s,o)}return Nh(e,t,s,o)}function Nh(e,t,n,r){if(Object.is(e,t))return!0;let i=QI(e),s=QI(t);if(i===e$&&(i=p4),s===e$&&(s=p4),i!==s)return!1;switch(i){case Xte:return e.toString()===t.toString();case Jte:{const c=e.valueOf(),l=t.valueOf();return Kte(c,l)}case Qte:case tne:case ene:return Object.is(e.valueOf(),t.valueOf());case Yte:return e.source===t.source&&e.flags===t.flags;case sne: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(i){case nne:{if(e.size!==t.size)return!1;for(const[c,l]of e.entries())if(!t.has(c)||!Th(l,t.get(c),c,e,t,n,r))return!1;return!0}case rne:{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 d=c[u],h=l.findIndex(f=>Th(d,f,void 0,e,t,n,r));if(h===-1)return!1;l.splice(h,1)}return!0}case ine:case lne:case une:case dne:case fne:case hne:case pne:case gne:case mne:case yne:case wne:case bne:{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(!Th(e[c],t[c],c,e,t,n,r))return!1;return!0}case one:return e.byteLength!==t.byteLength?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case cne:return e.byteLength!==t.byteLength||e.byteOffset!==t.byteOffset?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case ane:return e.name===t.name&&e.message===t.message;case p4:{if(!(Nh(e.constructor,t.constructor,n,r)||t$(e)&&t$(t)))return!1;const c=[...Object.keys(e),...JI(e)],l=[...Object.keys(t),...JI(t)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=e[d];if(!Object.hasOwn(t,d))return!1;const f=t[d];if(!Th(h,f,d,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Ene(){}function Ane(e,t){return vne(e,t,Ene)}var Cne=Object.defineProperty,n$=Object.getOwnPropertySymbols,xne=Object.prototype.hasOwnProperty,_ne=Object.prototype.propertyIsEnumerable,g4=(e,t,n)=>t in e?Cne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,r$=(e,t)=>{for(var n in t||(t={}))xne.call(t,n)&&g4(e,n,t[n]);if(n$)for(var n of n$(t))_ne.call(t,n)&&g4(e,n,t[n]);return e},ei=(e,t,n)=>g4(e,typeof t!="symbol"?t+"":t,n);class Cu extends hJ{constructor(t,n,r,i=so,s=void 0){super(t,n,r,i),this.core=t,this.logger=n,this.name=r,ei(this,"map",new Map),ei(this,"version",$Q),ei(this,"cached",[]),ei(this,"initialized",!1),ei(this,"getKey"),ei(this,"storagePrefix",so),ei(this,"recentlyDeleted",[]),ei(this,"recentlyDeletedLimit",200),ei(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!$n(o)?this.map.set(this.getKey(o),o):HY(o)?this.map.set(o.id,o):jY(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ei(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())}),ei(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ei(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Ane(a[c],o[c]))):this.values)),ei(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=r$(r$({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ei(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=vi(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Gr(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:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(i),new Error(i)}const{message:r}=Ae("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}=Ae("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}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Sne=Object.defineProperty,Ine=(e,t,n)=>t in e?Sne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bt=(e,t,n)=>Ine(e,typeof t!="symbol"?t+"":t,n);class $ne{constructor(t,n){this.core=t,this.logger=n,bt(this,"name",OQ),bt(this,"version",kQ),bt(this,"events",new zn.exports),bt(this,"pairings"),bt(this,"initialized",!1),bt(this,"storagePrefix",so),bt(this,"ignoredPayloadTypes",[ec]),bt(this,"registeredMethods",[]),bt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),bt(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),bt(this,"create",async r=>{this.isInitialized();const i=j8(),s=await this.core.crypto.setSymKey(i),o=mn(ve.FIVE_MINUTES),a={protocol:_I},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},l=LS({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(vu.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:l}}),bt(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[oo.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=US(r.uri);i.props.properties.topic=s,i.addTrace(oo.pairing_uri_validation_success),i.addTrace(oo.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(oo.existing_pairing),u.active)throw i.setError(rc.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(oo.pairing_not_expired)}const d=c||mn(ve.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(oo.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(vu.create,h),i.addTrace(oo.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(oo.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(rc.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(rc.subscribe_pairing_topic_failure),f}return i.addTrace(oo.subscribe_pairing_topic_success),h}),bt(this,"activate",async({topic:r})=>{this.isInitialized();const i=mn(ve.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),bt(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:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=uu();this.events.once(Rt("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),bt(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),bt(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),bt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),bt(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(i))}),bt(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return LS({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),bt(this,"sendRequest",async(r,i,s)=>{const o=ws(i,s),a=await this.core.crypto.encode(r,o),c=xh[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),bt(this,"sendResult",async(r,i,s)=>{const o=Ch(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"sendError",async(r,i,s)=>{const o=um(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c]?xh[c].res:xh.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),bt(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Qs(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),bt(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),bt(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),bt(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(vu.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{io(i)?this.events.emit(Rt("pairing_ping",s),{}):ji(i)&&this.events.emit(Rt("pairing_ping",s),{error:i.error})},500)}),bt(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(vu.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Gt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),bt(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",r))}),bt(this,"isValidPair",(r,i)=>{var s;if(!Jr(r)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!FY(r.uri)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}const o=US(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&ve.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(rc.pairing_expired);const{message:a}=Ae("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),bt(this,"isValidPing",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidDisconnect",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidPairingTopic",async r=>{if(!yn(r,!1)){const{message:i}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Qs(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=Ae("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=t,this.logger=vi(n,this.name),this.pairings=new Cu(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Gr(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(hn.message,async t=>{const{topic:n,message:r,transportType:i}=t;if(this.pairings.keys.includes(n)&&i!==Kt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);r4(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):dm(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Vi.expired,async t=>{const{topic:n}=s7(t.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(vu.expire,{topic:n}))})}}var Tne=Object.defineProperty,Nne=(e,t,n)=>t in e?Tne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kn=(e,t,n)=>Nne(e,typeof t!="symbol"?t+"":t,n);class Pne extends lJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,Kn(this,"records",new Map),Kn(this,"events",new zn.exports.EventEmitter),Kn(this,"name",RQ),Kn(this,"version",BQ),Kn(this,"cached",[]),Kn(this,"initialized",!1),Kn(this,"storagePrefix",so),Kn(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)}),Kn(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:mn(ve.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(bs.created,o)}),Kn(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 i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=ji(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(bs.updated,i))}),Kn(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Kn(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(bs.deleted,s)}}),this.persist()}),Kn(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Kn(this,"on",(r,i)=>{this.events.on(r,i)}),Kn(this,"once",(r,i)=>{this.events.once(r,i)}),Kn(this,"off",(r,i)=>{this.events.off(r,i)}),Kn(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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:ws(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}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(bs.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:n}=Ae("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(bs.created,t=>{const n=bs.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.updated,t=>{const n=bs.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.deleted,t=>{const n=bs.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.core.heartbeat.on(wu.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(n=>{ve.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(bs.deleted,n,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var One=Object.defineProperty,kne=(e,t,n)=>t in e?One(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hr=(e,t,n)=>kne(e,typeof t!="symbol"?t+"":t,n);class Rne extends gJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,hr(this,"expirations",new Map),hr(this,"events",new zn.exports.EventEmitter),hr(this,"name",MQ),hr(this,"version",DQ),hr(this,"cached",[]),hr(this,"initialized",!1),hr(this,"storagePrefix",so),hr(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)}),hr(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),hr(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Vi.created,{target:s,expiration:o})}),hr(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),hr(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Vi.deleted,{target:i,expiration:s})}}),hr(this,"on",(r,i)=>{this.events.on(r,i)}),hr(this,"once",(r,i)=>{this.events.once(r,i)}),hr(this,"off",(r,i)=>{this.events.off(r,i)}),hr(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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 gZ(t);if(typeof t=="number")return mZ(t);const{message:n}=Ae("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(Vi.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:n}=Ae("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}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(t,n){const{expiry:r}=n;ve.toMiliseconds(r)-Date.now()<=0&&this.expire(t,n)}expire(t,n){this.expirations.delete(t),this.events.emit(Vi.expired,{target:t,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,n)=>this.checkExpiry(n,t))}registerEventListeners(){this.core.heartbeat.on(wu.pulse,()=>this.checkExpirations()),this.events.on(Vi.created,t=>{const n=Vi.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.expired,t=>{const n=Vi.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.deleted,t=>{const n=Vi.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Bne=Object.defineProperty,Mne=(e,t,n)=>t in e?Bne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wn=(e,t,n)=>Mne(e,typeof t!="symbol"?t+"":t,n);class Dne extends mJ{constructor(t,n,r){super(t,n,r),this.core=t,this.logger=n,this.store=r,wn(this,"name",UQ),wn(this,"abortController"),wn(this,"isDevEnv"),wn(this,"verifyUrlV3",FQ),wn(this,"storagePrefix",so),wn(this,"version",CI),wn(this,"publicKey"),wn(this,"fetchPromise"),wn(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&ve.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),wn(this,"register",async i=>{if(!Yd()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=Kl(),u=this.startAbortTimer(ve.ONE_SECOND*5),d=await new Promise((h,f)=>{const p=()=>{window.removeEventListener("message",y),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=A=>{if(A.data&&typeof A.data=="string")try{const _=JSON.parse(A.data);if(_.type==="verify_attestation"){if(Gb(_.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),h(_.attestation===null?"":_.attestation)}}catch(_){this.logger.warn(_)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(d,"jwt attestation"),d}catch(l){this.logger.warn(l)}return""}),wn(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Gb(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),wn(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(ve.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),wn(this,"getVerifyUrl",i=>{let s=i||_h;return HQ.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${_h}`),s=_h),s}),wn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(ve.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),wn(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),wn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),wn(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),wn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),wn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),wn(this,"validateAttestation",(i,s)=>{const o=fY(i,s.publicKey),a={hasExpired:ve.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=vi(n,this.name),this.abortController=new AbortController,this.isDevEnv=d8(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Gr(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ve.toMiliseconds(t))}}var Une=Object.defineProperty,Lne=(e,t,n)=>t in e?Une(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,i$=(e,t,n)=>Lne(e,typeof t!="symbol"?t+"":t,n);class Fne extends yJ{constructor(t,n){super(t,n),this.projectId=t,this.logger=n,i$(this,"context",jQ),i$(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${zQ}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=vi(n,this.context)}}var Hne=Object.defineProperty,s$=Object.getOwnPropertySymbols,jne=Object.prototype.hasOwnProperty,zne=Object.prototype.propertyIsEnumerable,m4=(e,t,n)=>t in e?Hne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ph=(e,t)=>{for(var n in t||(t={}))jne.call(t,n)&&m4(e,n,t[n]);if(s$)for(var n of s$(t))zne.call(t,n)&&m4(e,n,t[n]);return e},Dn=(e,t,n)=>m4(e,typeof t!="symbol"?t+"":t,n);class Vne extends wJ{constructor(t,n,r=!0){super(t,n,r),this.core=t,this.logger=n,Dn(this,"context",WQ),Dn(this,"storagePrefix",so),Dn(this,"storageVersion",VQ),Dn(this,"events",new Map),Dn(this,"shouldPersist",!1),Dn(this,"init",async()=>{if(!d8())try{const i={eventId:a7(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:r7(this.core.relayer.protocol,this.core.relayer.version,s4)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Dn(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=a7(),u=this.core.projectId||"",d=Date.now(),h=Ph({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Dn(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ph(Ph({},a),this.setMethods(a.eventId))}),Dn(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Dn(this,"setEventListeners",()=>{this.core.heartbeat.on(wu.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{ve.fromMiliseconds(Date.now())-ve.fromMiliseconds(i.timestamp)>qQ&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Dn(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Dn(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Dn(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ph(Ph({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Dn(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Dn(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZQ}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${s4}${s}`,{method:"POST",body:JSON.stringify(i)})}),Dn(this,"getAppDomain",()=>n7().url),this.logger=vi(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 Wne=Object.defineProperty,o$=Object.getOwnPropertySymbols,qne=Object.prototype.hasOwnProperty,Zne=Object.prototype.propertyIsEnumerable,y4=(e,t,n)=>t in e?Wne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a$=(e,t)=>{for(var n in t||(t={}))qne.call(t,n)&&y4(e,n,t[n]);if(o$)for(var n of o$(t))Zne.call(t,n)&&y4(e,n,t[n]);return e},qt=(e,t,n)=>y4(e,typeof t!="symbol"?t+"":t,n);class w4 extends sJ{constructor(t){var n;super(t),qt(this,"protocol",AI),qt(this,"version",CI),qt(this,"name",fm),qt(this,"relayUrl"),qt(this,"projectId"),qt(this,"customStoragePrefix"),qt(this,"events",new zn.exports.EventEmitter),qt(this,"logger"),qt(this,"heartbeat"),qt(this,"relayer"),qt(this,"crypto"),qt(this,"storage"),qt(this,"history"),qt(this,"expirer"),qt(this,"pairing"),qt(this,"verify"),qt(this,"echoClient"),qt(this,"linkModeSupportedApps"),qt(this,"eventClient"),qt(this,"initialized",!1),qt(this,"logChunkController"),qt(this,"on",(a,c)=>this.events.on(a,c)),qt(this,"once",(a,c)=>this.events.once(a,c)),qt(this,"off",(a,c)=>this.events.off(a,c)),qt(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),qt(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Kt.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||SI,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const i=Z_({level:typeof t?.logger=="string"&&t.logger?t.logger:pQ.logger,name:fm}),{logger:s,chunkLoggerController:o}=a8({opts:i,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=vi(s,this.name),this.heartbeat=new K8,this.crypto=new Ete(this,this.logger,t?.keychain),this.history=new Pne(this,this.logger),this.expirer=new Rne(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new nJ(a$(a$({},gQ),t?.storageOptions)),this.relayer=new Gte({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $ne(this,this.logger),this.verify=new Dne(this,this.logger,this.storage),this.echoClient=new Fne(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Vne(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new w4(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(TQ,r),n}get context(){return Gr(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(II,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(II)||[],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 Gne=w4,c$="wc",l$=2,u$="client",b4=`${c$}@${l$}:${u$}:`,v4={name:u$,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},d$="WALLETCONNECT_DEEPLINK_CHOICE",Kne="proposal",f$="Proposal expired",Yne="session",l0=ve.SEVEN_DAYS,Xne="engine",Yn={wc_sessionPropose:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ve.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ve.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1119}}},E4={min:ve.FIVE_MINUTES,max:ve.SEVEN_DAYS},co={idle:"IDLE",active:"ACTIVE"},Jne={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:""}},Qne="request",ere=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tre="wc",nre="auth",rre="authKeys",ire="pairingTopics",sre="requests",gm=`${tre}@${1.5}:${nre}:`,mm=`${gm}:PUB_KEY`;var ore=Object.defineProperty,are=Object.defineProperties,cre=Object.getOwnPropertyDescriptors,h$=Object.getOwnPropertySymbols,lre=Object.prototype.hasOwnProperty,ure=Object.prototype.propertyIsEnumerable,A4=(e,t,n)=>t in e?ore(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pt=(e,t)=>{for(var n in t||(t={}))lre.call(t,n)&&A4(e,n,t[n]);if(h$)for(var n of h$(t))ure.call(t,n)&&A4(e,n,t[n]);return e},Xn=(e,t)=>are(e,cre(t)),ye=(e,t,n)=>A4(e,typeof t!="symbol"?t+"":t,n);class dre extends AJ{constructor(t){super(t),ye(this,"name",Xne),ye(this,"events",new zn.exports),ye(this,"initialized",!1),ye(this,"requestQueue",{state:co.idle,queue:[]}),ye(this,"sessionRequestQueue",{state:co.idle,queue:[]}),ye(this,"emittedSessionRequests",new _Z({limit:500})),ye(this,"requestQueueDelay",ve.ONE_SECOND),ye(this,"expectedPairingMethodMap",new Map),ye(this,"recentlyDeletedMap",new Map),ye(this,"recentlyDeletedLimit",200),ye(this,"relayMessageCache",[]),ye(this,"pendingSessions",new Map),ye(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(Yn)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay)))}),ye(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Xn(Pt({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=BY(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:d,walletPay:h}=i,f=((r=d?.[0])==null?void 0:r.ttl)||Yn.wc_sessionPropose.req.ttl||ve.FIVE_MINUTES;this.validateRequestExpiry(f);let p=s,g,y=!1;try{if(p){const U=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),y=U.active}}catch(U){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),U}if(!p||!y){const{topic:U,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=U,g=j}if(!p){const{message:U}=Ae("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const A=await this.client.core.crypto.generateKeyPair(),_=mn(f),v=Pt(Xn(Pt(Pt({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:_I}],proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:_,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:ro()}),(d||h)&&{requests:{authentication:d?.map(U=>{const{domain:j,chains:W,nonce:S,uri:x,exp:I,nbf:m,type:b,statement:$,requestId:N,resources:P,signatureTypes:B}=U;return{domain:j,chains:W,nonce:S,type:b??"caip122",aud:x,version:"1",iat:new Date().toISOString(),exp:I,nbf:m,statement:$,requestId:N,resources:P,signatureTypes:B}}),walletPay:h}}),w=Rt("session_connect",v.id),{reject:T,resolve:O,done:D}=uu(f,f$),F=({id:U})=>{U===v.id&&(this.client.events.off("proposal_expire",F),this.pendingSessions.delete(v.id),this.events.emit(w,{error:{message:f$,code:0}}))};return this.client.events.on("proposal_expire",F),this.events.once(w,({error:U,session:j})=>{this.client.events.off("proposal_expire",F),U?T(U):j&&O(j)}),await this.setProposal(v.id,v),await this.sendProposeSession({proposal:v,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:v.id}}}).catch(U=>{throw this.deleteProposal(v.id),U}),{uri:g,approval:D}}),ye(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}}),ye(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[vs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Eu.no_internet_connection),j}try{await this.isValidProposalId(n?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Eu.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Eu.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:A,optionalNamespaces:_}=p;let v=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});v||(v=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:vs.session_approve_started,properties:{topic:g,trace:[vs.session_approve_started,vs.session_namespaces_validation_success]}}));const w=await this.client.core.crypto.generateKeyPair(),T=y.publicKey,O=await this.client.core.crypto.generateSharedKey(w,T),D=Xn(Pt(Pt(Pt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:w,metadata:this.client.metadata},expiry:mn(l0)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{proposalRequestsResponses:f}),F=Kt.relay;v.addTrace(vs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:F,internal:{skipSubscribe:!0}})}catch(j){throw v.setError(Eu.subscribe_session_topic_failure),j}v.addTrace(vs.subscribe_session_topic_success);const U=Xn(Pt({},D),{topic:O,requiredNamespaces:A,optionalNamespaces:_,pairingTopic:g,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:w,transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(O,U),v.addTrace(vs.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:w},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:Pt({correlationId:a},this.getTVFApproveParams(U))}}),v.addTrace(vs.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(O,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),j}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(O,mn(l0)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),ye(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:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Yn.wc_sessionPropose.reject}),await this.deleteProposal(r)}),ye(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=ro(),l=rl().toString(),u=this.client.session.get(r).namespaces;return this.events.once(Rt("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:s}}),ye(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,i=ro(),{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Rt("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,mn(l0)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),ye(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:i,topic:s,expiry:o=Yn.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=ro(),l=rl().toString(),{done:u,resolve:d,reject:h}=uu(o,"Request expired. Please try again.");this.events.once(Rt("session_request",c),({error:y,result:A})=>{y?h(y):d(A)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await u();const g={request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(A=>h(A)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var A;if(!((A=a.sessionConfig)!=null&&A.disableDeepLink)){const _=await vZ(this.client.core.storage,d$);await yZ({id:c,topic:s,wcDeepLink:_})}y()}),u()]).then(y=>y[2])}),ye(this,"respond",async n=>{var r,i;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((i=(r=n?.response)==null?void 0:r.id)==null?void 0:i.toString()),trace:[vs.session_request_response_started]}});try{await this.isValidRespond(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_validation_failure),d}s.addTrace(vs.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,l=this.client.session.get(o);l.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(vs.session_request_response_publish_started),io(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):ji(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_publish_failure),d}}),ye(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ro(),s=rl().toString(),{done:o,resolve:a,reject:c}=uu(ve.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Rt("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),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}))}),ye(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=rl().toString(),a=ro();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),ye(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:Gt("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:i}=Ae("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),ye(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>UY(r,n)))),ye(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),ye(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?Kt.link_mode:Kt.relay;o===Kt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:p,methods:g=[],expiry:y}=n,A=[...n.resources||[]],{topic:_,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:v}});const w=await this.client.core.crypto.generateKeyPair(),T=tm(w);if(await Promise.all([this.client.auth.authKeys.set(mm,{responseTopic:T,publicKey:w}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:_})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${_}`),g.length>0){const{namespace:P}=Ga(a[0]);let B=DG(P,"request",g);zg(A)&&(B=LG(B,A.pop())),A.push(B)}const O=y&&y>Yn.wc_sessionAuthenticate.req.ttl?y:Yn.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:p,resources:A},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(O)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},U={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(Yn.wc_sessionPropose.req.ttl),id:ro()},{done:j,resolve:W,reject:S}=uu(O,"Request expired"),x=ro(),I=Rt("session_connect",U.id),m=Rt("session_request",x),b=async({error:P,session:B})=>{this.events.off(m,$),P?S(P):B&&W({session:B})},$=async P=>{var B,V,Z;if(await this.deletePendingAuthRequest(x,{message:"fulfilled",code:0}),P.error){const ue=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===ue.code?void 0:(this.events.off(I,b),S(P.error.message))}await this.deleteProposal(U.id),this.events.off(I,b);const{cacaos:Y,responder:X}=P.result,G=[],ne=[];for(const ue of Y){await k7({cacao:ue,projectId:this.client.core.projectId})||(this.client.logger.error(ue,"Signature verification failed"),S(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ge}=ue,Be=zg(ge.resources),Fe=[b8(ge.iss)],qe=jg(ge.iss);if(Be){const ct=M7(Be),St=D7(Be);G.push(...ct),Fe.push(...St)}for(const ct of Fe)ne.push(`${ct}:${qe}`)}const se=await this.client.core.crypto.generateSharedKey(w,X.publicKey);let we;G.length>0&&(we={topic:se,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:mn(l0),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:VS([...new Set(G)],[...new Set(ne)]),transportType:o},await this.client.core.relayer.subscribe(se,{transportType:o}),await this.client.session.set(se,we),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:X.metadata}),we=this.client.session.get(se)),(B=this.client.metadata.redirect)!=null&&B.linkMode&&(V=X.metadata.redirect)!=null&&V.linkMode&&(Z=X.metadata.redirect)!=null&&Z.universal&&r&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(se,{transportType:Kt.link_mode})),W({auths:Y,session:we})};this.events.once(I,b),this.events.once(m,$);let N;try{if(s){const P=ws("wc_sessionAuthenticate",D,x);this.client.core.history.set(_,P);const B=await this.client.core.crypto.encode("",P,{type:mh,encoding:nl});N=rm(r,_,B)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:D,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:x}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:U,expiry:Yn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:U.id})])}catch(P){throw this.events.off(I,b),this.events.off(m,$),P}return await this.setProposal(U.id,U),await this.setAuthRequest(x,{request:Xn(Pt({},D),{verifyContext:{}}),pairingTopic:_,transportType:o}),{uri:N??v,response:j}}),ye(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Au.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Sh.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Sh.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Kt.relay;a===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=tm(c),d={type:ec,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const y of i){if(!await k7({cacao:y,projectId:this.client.core.projectId})){s.setError(Sh.invalid_cacao);const T=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:T,encodeOpts:d}),new Error(T.message)}s.addTrace(Au.cacaos_verified);const{p:A}=y,_=zg(A.resources),v=[b8(A.iss)],w=jg(A.iss);if(_){const T=M7(_),O=D7(_);h.push(...T),v.push(...O)}for(const T of v)f.push(`${T}:${w}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Au.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:mn(l0),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:VS([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Au.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw s.setError(Sh.subscribe_authenticated_session_topic_failure),y}s.addTrace(Au.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Au.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Au.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Sh.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:s.eventId}),{session:g}}),ye(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tm(o),l={type:ec,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:Yn.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),ye(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return R7(r,i)}),ye(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)}),ye(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),ye(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(d$).catch(l=>this.client.logger.warn(l)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=co.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===i).map(l=>this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),ye(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(Eu.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Gt("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),ye(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=co.idle,this.client.events.emit("session_request_expire",{id:n}))}),ye(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),ye(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}))}),ye(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,mn(Yn.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),ye(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=Kt.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),ye(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||mn(Yn.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),ye(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=n,f=ws(i,s,c);let p;const g=!!u;try{const _=g?nl:Xr;p=await this.client.core.crypto.encode(r,f,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),_}let y;if(ere.includes(i)){const _=Fi(JSON.stringify(f)),v=Fi(p);y=await this.client.core.verify.register({id:v,decryptedId:_})}const A=Pt(Pt({},Yn[i].req),h);if(A.attestation=y,o&&(A.ttl=o),a&&(A.id=a),this.client.core.history.set(r,f),g){const _=rm(u,r,p);await global.Linking.openURL(_,this.client.name)}else A.tvf=Xn(Pt({},d),{correlationId:f.id}),l?(A.internal=Xn(Pt({},A.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,A)):this.client.core.relayer.publish(r,p,A).catch(_=>this.client.logger.error(_));return f.id}),ye(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=ws("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:Xr}),a=Fi(JSON.stringify(s)),c=Fi(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:Xn(Pt({},i),{publishMethod:"wc_proposeSession",attestation:l})})}),ye(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=Ch(s.id,i),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Xr}),u=ws("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(r,u,{encoding:Xr});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:Xn(Pt({},a),{publishMethod:"wc_approveSession"})})}),ye(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=Ch(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,f;try{h=await this.client.core.history.get(i,r);const p=h.request;try{f=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(d){const p=rm(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Yn[p].res;g.tvf=Xn(Pt({},f),{correlationId:r}),o?(g.internal=Xn(Pt({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),ye(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=um(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,r)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),f}if(d){const f=rm(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,p=a||Yn[f].res;this.client.core.relayer.publish(i,u,p)}await this.client.core.history.resolve(l)}),ye(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;Qs(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Qs(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),ye(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),ye(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),ye(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===co.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=co.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=co.idle}),ye(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),ye(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),ye(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=Ae("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),ye(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),ye(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;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(rc.proposal_listener_not_found)),this.isValidConnect(Pt({},i.params));const u=a.expiryTimestamp||mn(Yn.wc_sessionPropose.req.ttl),d=Pt({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:Fi(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(oo.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Yn.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),ye(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(io(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:n,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:n})}else if(ji(r)){await this.deleteProposal(s);const o=Rt("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),ye(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=r.params,p=[...this.pendingSessions.values()].find(A=>A.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(p.proposalId),y=Xn(Pt(Pt(Pt({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Rt("session_connect",p.proposalId),{session:y})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;io(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(Rt("session_approve",i),{})):ji(r)&&(await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.events.emit(Rt("session_approve",i),{error:r.error}))}),ye(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Pt({topic:n},i));try{bh.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw bh.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),ye(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=Rt("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_update",i),{}):ji(r)&&this.events.emit(Rt("session_update",i),{error:r.error})}),ye(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,mn(l0)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=Rt("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_extend",i),{}):ji(r)&&this.events.emit(Rt("session_extend",i),{error:r.error})}),ye(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=Rt("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);io(r)?this.events.emit(Rt("session_ping",i),{}):ji(r)&&this.events.emit(Rt("session_ping",i),{error:r.error})},500)}),ye(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Gt("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),ye(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:d,params:h}=a;try{await this.isValidRequest(Pt({topic:o},h));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Fi(JSON.stringify(ws("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),u===Kt.link_mode&&(r=f.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),ye(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=Rt("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Pt({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),bh.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:Fi(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===Kt.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:ec,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Yn.wc_sessionAuthenticate.autoReject,appLink:h})}}),ye(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),ye(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=co.idle,this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay))}),ye(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(Rt("session_request",s.request.id),{error:r})})}),ye(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===co.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)}}),ye(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=co.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),ye(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:ws("wc_sessionPropose",Xn(Pt({},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})}),ye(this,"isValidConnect",async n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if($n(r)||await this.isValidPairingTopic(r),!YY(c,!0)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(i&&!$n(i)&&no(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!$n(s)&&no(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),ye(this,"validateNamespaces",(n,r)=>{const i=KY(n,"connect()",r);if(i)throw new Error(i.message)}),ye(this,"isValidApprove",async n=>{if(!Jr(n))throw new Error(Ae("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=W8(i,"approve()");if(l)throw new Error(l.message);const u=KS(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!yn(s,!0)){const{message:d}=Ae("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),ye(this,"isValidReject",async n=>{if(!Jr(n)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!JY(i)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),ye(this,"isValidSessionSettleRequest",n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!ZS(r)){const{message:l}=Ae("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=zY(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=W8(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Qs(o)){const{message:l}=Ae("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),ye(this,"isValidUpdate",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=W8(i,"update()");if(o)throw new Error(o.message);const a=KS(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),ye(this,"isValidExtend",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),ye(this,"isValidRequest",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!GS(a,s)){const{message:c}=Ae("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!QY(i)){const{message:c}=Ae("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!nX(a,s,i.method)){const{message:c}=Ae("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),ye(this,"isValidRespond",async n=>{var r;if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!eX(s)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==i){const{message:a}=Ae("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),ye(this,"isValidPing",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidEmit",async n=>{if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!GS(o,s)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!tX(i)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!rX(o,s,i.name)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),ye(this,"isValidDisconnect",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!yn(i,!1))throw new Error("uri is required parameter");if(!yn(s,!1))throw new Error("domain is required parameter");if(!yn(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ga(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ga(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),ye(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||_h,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Kt.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:i,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),ye(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=Ae("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),ye(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),ye(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),ye(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),ye(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,l,u,d,h;return!n||r!==Kt.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=n?.redirect)==null?void 0:u.universal)!==void 0&&((d=n?.redirect)==null?void 0:d.universal)!==""&&((h=n?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),ye(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),ye(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=o7(n,"topic")||"",i=decodeURIComponent(o7(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:Kt.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),ye(this,"registerLinkModeListeners",async()=>{var n;if(d8()||jc()&&(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 i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),ye(this,"getTVFApproveParams",n=>{try{const r=jS(n.namespaces),i=NY(n.namespaces),s=PY(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:i,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),ye(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,i);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}),ye(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),ye(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=Jne[s];if(s==="sui_signTransaction")return[wG(r.transactionBytes)];if(s==="near_signTransaction")return[$7(r)];if(s==="near_signTransactions")return r.map(c=>$7(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[EX({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Hi(r)?r.map(c=>T7(c)):[T7(r)];if(s==="cosmos_signDirect")return[vG(r)];if(s==="wallet_sendCalls")return EG(r);if(typeof r=="string")return[r];const a=r[o.key];if(Hi(a))return s==="solana_signAllTransactions"?a.map(c=>yG(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"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,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){const{topic:n,message:r,attestation:i,transportType:s}=t,{publicKey:o}=this.client.auth.authKeys.keys.includes(mm)?this.client.auth.authKeys.get(mm):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===Kt.link_mode?nl:Xr});r4(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Fi(r)})):dm(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Vi.expired,async t=>{const{topic:n,id:r}=s7(t.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Ae("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,Ae("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(vu.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(vu.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!yn(t,!1)){const{message:n}=Ae("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}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.core.pairing.pairings.get(t).expiry)){const{message:n}=Ae("EXPIRED",`pairing topic: ${t}`);throw new Error(n)}}async isValidSessionTopic(t){if(!yn(t,!1)){const{message:n}=Ae("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}=Ae("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});const{message:n}=Ae("EXPIRED",`session topic: ${t}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(t)){const{message:n}=Ae("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(yn(t,!1)){const{message:n}=Ae("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(n)}else{const{message:n}=Ae("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(n)}}async isValidProposalId(t){if(!XY(t)){const{message:n}=Ae("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(n)}if(!this.client.proposal.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);const{message:n}=Ae("EXPIRED",`proposal id: ${t}`);throw new Error(n)}}validateRequestExpiry(t){if(t&&!oX(t,E4)){const{message:n}=Ae("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${E4.min} and ${E4.max}`);throw new Error(n)}}}class fre extends Cu{constructor(t,n){super(t,n,Kne,b4),this.core=t,this.logger=n}}class hre extends Cu{constructor(t,n){super(t,n,Yne,b4),this.core=t,this.logger=n}}class pre extends Cu{constructor(t,n){super(t,n,Qne,b4,r=>r.id),this.core=t,this.logger=n}}class gre extends Cu{constructor(t,n){super(t,n,rre,gm,()=>mm),this.core=t,this.logger=n}}class mre extends Cu{constructor(t,n){super(t,n,ire,gm),this.core=t,this.logger=n}}class yre extends Cu{constructor(t,n){super(t,n,sre,gm,r=>r.id),this.core=t,this.logger=n}}var wre=Object.defineProperty,bre=(e,t,n)=>t in e?wre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C4=(e,t,n)=>bre(e,typeof t!="symbol"?t+"":t,n);class vre{constructor(t,n){this.core=t,this.logger=n,C4(this,"authKeys"),C4(this,"pairingTopics"),C4(this,"requests"),this.authKeys=new gre(this.core,this.logger),this.pairingTopics=new mre(this.core,this.logger),this.requests=new yre(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Ere=Object.defineProperty,Are=(e,t,n)=>t in e?Ere(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vt=(e,t,n)=>Are(e,typeof t!="symbol"?t+"":t,n);class x4 extends EJ{constructor(t){super(t),vt(this,"protocol",c$),vt(this,"version",l$),vt(this,"name",v4.name),vt(this,"metadata"),vt(this,"core"),vt(this,"logger"),vt(this,"events",new zn.exports.EventEmitter),vt(this,"engine"),vt(this,"session"),vt(this,"proposal"),vt(this,"pendingRequest"),vt(this,"auth"),vt(this,"signConfig"),vt(this,"on",(r,i)=>this.events.on(r,i)),vt(this,"once",(r,i)=>this.events.once(r,i)),vt(this,"off",(r,i)=>this.events.off(r,i)),vt(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),vt(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),vt(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),vt(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),vt(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=t?.name||v4.name,this.metadata=dZ(t?.metadata),this.signConfig=t?.signConfig;const n=G8({logger:t?.logger||v4.logger,name:this.name});this.logger=n,this.core=t?.core||new Gne(t),this.session=new hre(this.core,this.logger),this.proposal=new fre(this.core,this.logger),this.pendingRequest=new pre(this.core,this.logger),this.engine=new dre(this),this.auth=new vre(this.core,this.logger)}static async init(t){const n=new x4(t);return await n.initialize(),n}get context(){return Gr(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 Cre=x4;var _4={exports:{}};(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Pn<"u"&&Pn,r=function(){function s(){this.fetch=!1,this.DOMException=n.DOMException}return s.prototype=n,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Pn<"u"&&Pn||{},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]"],d=ArrayBuffer.isView||function(m){return m&&u.indexOf(Object.prototype.toString.call(m))>-1};function h(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 f(m){return typeof m!="string"&&(m=String(m)),m}function p(m){var b={next:function(){var $=m.shift();return{done:$===void 0,value:$}}};return c.iterable&&(b[Symbol.iterator]=function(){return b}),b}function g(m){this.map={},m instanceof g?m.forEach(function(b,$){this.append($,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=h(m),b=f(b);var $=this.map[m];this.map[m]=$?$+", "+b:b},g.prototype.delete=function(m){delete this.map[h(m)]},g.prototype.get=function(m){return m=h(m),this.has(m)?this.map[m]:null},g.prototype.has=function(m){return this.map.hasOwnProperty(h(m))},g.prototype.set=function(m,b){this.map[h(m)]=f(b)},g.prototype.forEach=function(m,b){for(var $ in this.map)this.map.hasOwnProperty($)&&m.call(b,this.map[$],$,this)},g.prototype.keys=function(){var m=[];return this.forEach(function(b,$){m.push($)}),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,$){m.push([$,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 A(m){return new Promise(function(b,$){m.onload=function(){b(m.result)},m.onerror=function(){$(m.error)}})}function _(m){var b=new FileReader,$=A(b);return b.readAsArrayBuffer(m),$}function v(m){var b=new FileReader,$=A(b),N=/charset=([A-Za-z0-9_-]+)/.exec(m.type),P=N?N[1]:"utf-8";return b.readAsText(m,P),$}function w(m){for(var b=new Uint8Array(m),$=new Array(b.length),N=0;N<b.length;N++)$[N]=String.fromCharCode(b[N]);return $.join("")}function T(m){if(m.slice)return m.slice(0);var b=new Uint8Array(m.byteLength);return b.set(new Uint8Array(m)),b.buffer}function O(){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=T(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||d(m))?this._bodyArrayBuffer=T(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 v(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(w(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(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(m){var b=m.toUpperCase();return D.indexOf(b)>-1?b:m}function U(m,b){if(!(this instanceof U))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var $=b.body;if(m instanceof U){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,!$&&m._bodyInit!=null&&($=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=F(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||function(){if("AbortController"in a){var B=new AbortController;return B.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&$)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody($),(this.method==="GET"||this.method==="HEAD")&&(b.cache==="no-store"||b.cache==="no-cache")){var N=/([?&])_=[^&]*/;if(N.test(this.url))this.url=this.url.replace(N,"$1_="+new Date().getTime());else{var P=/\?/;this.url+=(P.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function j(m){var b=new FormData;return m.trim().split("&").forEach(function($){if($){var N=$.split("="),P=N.shift().replace(/\+/g," "),B=N.join("=").replace(/\+/g," ");b.append(decodeURIComponent(P),decodeURIComponent(B))}}),b}function W(m){var b=new g,$=m.replace(/\r?\n[\t ]+/g," ");return $.split("\r").map(function(N){return N.indexOf(`
42
42
  `)===0?N.substr(1,N.length):N}).forEach(function(N){var P=N.split(":"),B=P.shift().trim();if(B){var V=P.join(":").trim();try{b.append(B,V)}catch(Z){console.warn("Response "+Z.message)}}}),b}O.call(U.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)}O.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 x=[301,302,303,307,308];S.redirect=function(m,b){if(x.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,$){this.message=b,this.name=$;var N=Error(b);this.stack=N.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function I(m,b){return new Promise(function($,N){var P=new U(m,b);if(P.signal&&P.signal.aborted)return N(new o.DOMException("Aborted","AbortError"));var B=new XMLHttpRequest;function V(){B.abort()}B.onload=function(){var X={statusText:B.statusText,headers:W(B.getAllResponseHeaders()||"")};P.url.indexOf("file://")===0&&(B.status<200||B.status>599)?X.status=200:X.status=B.status,X.url="responseURL"in B?B.responseURL:X.headers.get("X-Request-URL");var G="response"in B?B.response:B.responseText;setTimeout(function(){$(new S(G,X))},0)},B.onerror=function(){setTimeout(function(){N(new TypeError("Network request failed"))},0)},B.ontimeout=function(){setTimeout(function(){N(new TypeError("Network request timed out"))},0)},B.onabort=function(){setTimeout(function(){N(new o.DOMException("Aborted","AbortError"))},0)};function Z(X){try{return X===""&&a.location.href?a.location.href:X}catch{return X}}if(B.open(P.method,Z(P.url),!0),P.credentials==="include"?B.withCredentials=!0:P.credentials==="omit"&&(B.withCredentials=!1),"responseType"in B&&(c.blob?B.responseType="blob":c.arrayBuffer&&(B.responseType="arraybuffer")),b&&typeof b.headers=="object"&&!(b.headers instanceof g||a.Headers&&b.headers instanceof a.Headers)){var Y=[];Object.getOwnPropertyNames(b.headers).forEach(function(X){Y.push(h(X)),B.setRequestHeader(X,f(b.headers[X]))}),P.headers.forEach(function(X,G){Y.indexOf(G)===-1&&B.setRequestHeader(G,X)})}else P.headers.forEach(function(X,G){B.setRequestHeader(G,X)});P.signal&&(P.signal.addEventListener("abort",V),B.onreadystatechange=function(){B.readyState===4&&P.signal.removeEventListener("abort",V)}),B.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return I.polyfill=!0,a.fetch||(a.fetch=I,a.Headers=g,a.Request=U,a.Response=S),o.Headers=g,o.Request=U,o.Response=S,o.fetch=I,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})(_4,_4.exports);var p$=JB(_4.exports),xre=Object.defineProperty,_re=Object.defineProperties,Sre=Object.getOwnPropertyDescriptors,g$=Object.getOwnPropertySymbols,Ire=Object.prototype.hasOwnProperty,$re=Object.prototype.propertyIsEnumerable,m$=(e,t,n)=>t in e?xre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y$=(e,t)=>{for(var n in t||(t={}))Ire.call(t,n)&&m$(e,n,t[n]);if(g$)for(var n of g$(t))$re.call(t,n)&&m$(e,n,t[n]);return e},w$=(e,t)=>_re(e,Sre(t));const Tre={Accept:"application/json","Content-Type":"application/json"},Nre="POST",b$={headers:Tre,method:Nre},v$=10;class E${constructor(t,n=!1){if(this.url=t,this.disableProviderPing=n,this.events=new zn.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!gI(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=ou(t),r=await(await p$(this.url,w$(y$({},b$),{body:n}))).json();this.onPayload({data:r})}catch(n){this.onError(t.id,n)}}async register(t=this.url){if(!gI(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,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));r()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){const n=ou({id:1,jsonrpc:"2.0",method:"test",params:[]});await p$(t,w$(y$({},b$),{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"?su(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),i=r.message||r.toString(),s=um(t,i);this.events.emit("payload",s)}parseError(t,n=this.url){return lI(t,n,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>v$&&this.events.setMaxListeners(v$)}}var Pre=Object.defineProperty,A$=Object.getOwnPropertySymbols,Ore=Object.prototype.hasOwnProperty,kre=Object.prototype.propertyIsEnumerable,C$=(e,t,n)=>t in e?Pre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,x$=(e,t)=>{for(var n in t||(t={}))Ore.call(t,n)&&C$(e,n,t[n]);if(A$)for(var n of A$(t))kre.call(t,n)&&C$(e,n,t[n]);return e};function Rre(e){return Number.isSafeInteger(e)&&e>=0}function Bre(e){return e!=null&&typeof e!="function"&&Rre(e.length)}function Mre(e){return e==="__proto__"}function S4(e){return e==null||typeof e!="object"&&typeof e!="function"}function _$(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function I4(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Dre="[object RegExp]",S$="[object String]",I$="[object Number]",$$="[object Boolean]",T$="[object Arguments]",Ure="[object Symbol]",Lre="[object Date]",Fre="[object Map]",Hre="[object Set]",jre="[object Array]",zre="[object ArrayBuffer]",N$="[object Object]",Vre="[object DataView]",Wre="[object Uint8Array]",qre="[object Uint8ClampedArray]",Zre="[object Uint16Array]",Gre="[object Uint32Array]",Kre="[object Int8Array]",Yre="[object Int16Array]",Xre="[object Int32Array]",Jre="[object Float32Array]",Qre="[object Float64Array]";function $4(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function eie(e,t){return u0(e,void 0,e,new Map,t)}function u0(e,t,n,r=new Map,i=void 0){const s=i?.(e,t,n,r);if(s!==void 0)return s;if(S4(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]=u0(e[a],a,n,r,i);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,u0(c,a,n,r,i));return o}if(e instanceof Set){const o=new Set;r.set(e,o);for(const a of e)o.add(u0(a,void 0,n,r,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if($4(e)){const o=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,o);for(let a=0;a<e.length;a++)o[a]=u0(e[a],a,n,r,i);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),Es(o,e,n,r,i),o}if(typeof File<"u"&&e instanceof File){const o=new File([e],e.name,{type:e.type});return r.set(e,o),Es(o,e,n,r,i),o}if(typeof Blob<"u"&&e instanceof Blob){const o=new Blob([e],{type:e.type});return r.set(e,o),Es(o,e,n,r,i),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,Es(o,e,n,r,i),o}if(e instanceof Boolean){const o=new Boolean(e.valueOf());return r.set(e,o),Es(o,e,n,r,i),o}if(e instanceof Number){const o=new Number(e.valueOf());return r.set(e,o),Es(o,e,n,r,i),o}if(e instanceof String){const o=new String(e.valueOf());return r.set(e,o),Es(o,e,n,r,i),o}if(typeof e=="object"&&tie(e)){const o=Object.create(Object.getPrototypeOf(e));return r.set(e,o),Es(o,e,n,r,i),o}return e}function Es(e,t,n=e,r,i){const s=[...Object.keys(t),..._$(t)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(e,a);(c==null||c.writable)&&(e[a]=u0(t[a],a,n,r,i))}}function tie(e){switch(I4(e)){case T$:case jre:case zre:case Vre:case $$:case Lre:case Jre:case Qre:case Kre:case Yre:case Xre:case Fre:case I$:case N$:case Dre:case Hre:case S$:case Ure:case Wre:case qre:case Zre:case Gre:return!0;default:return!1}}function nie(e,t){return eie(e,(n,r,i,s)=>{const o=t?.(n,r,i,s);if(o!==void 0)return o;if(typeof e=="object"){if(I4(e)===N$&&typeof e.constructor!="function"){const a={};return s.set(e,a),Es(a,e,i,s),a}switch(Object.prototype.toString.call(e)){case I$:case S$:case $$:{const a=new e.constructor(e?.valueOf());return Es(a,e),a}case T$:{const a={};return Es(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}}})}function P$(e){return nie(e)}function O$(e){return e!==null&&typeof e=="object"&&I4(e)==="[object Arguments]"}function T4(e){return typeof e=="object"&&e!==null}function rie(e){return T4(e)&&Bre(e)}function iie(){}function N4(e){return $4(e)}function P4(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 sie(e){if(S4(e))return e;if(Array.isArray(e)||$4(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(t==null)return Object.assign(Object.create(t),e);const n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){const 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){let r;return e instanceof AggregateError?r=new n(e.errors,e.message,{cause:e.cause}):r=new n(e.message,{cause:e.cause}),r.stack=e.stack,Object.assign(r,e),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 oie(e,...t){const n=t.slice(0,-1),r=t[t.length-1];let i=e;for(let s=0;s<n.length;s++){const o=n[s];i=O4(i,o,r,new Map)}return i}function O4(e,t,n,r){var i;if(S4(e)&&(e=Object(e)),t==null||typeof t!="object")return e;if(r.has(t))return sie(r.get(t));if(r.set(t,e),Array.isArray(t)){t=t.slice();for(let o=0;o<t.length;o++)t[o]=(i=t[o])!=null?i:void 0}const s=[...Object.keys(t),..._$(t)];for(let o=0;o<s.length;o++){const a=s[o];if(Mre(a))continue;let c=t[a],l=e[a];if(O$(c)&&(c=x$({},c)),O$(l)&&(l=x$({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=P$(c)),Array.isArray(c))if(Array.isArray(l)){const d=[],h=Reflect.ownKeys(l);for(let f=0;f<h.length;f++){const p=h[f];d[p]=l[p]}l=d}else if(rie(l)){const d=[];for(let h=0;h<l.length;h++)d[h]=l[h];l=d}else l=[];const u=n(l,c,a,e,t,r);u!==void 0?e[a]=u:Array.isArray(c)||T4(l)&&T4(c)&&(P4(l)||P4(c)||N4(l)||N4(c))?e[a]=O4(l,c,n,r):l==null&&P4(c)?e[a]=O4({},c,n,r):l==null&&N4(c)?e[a]=P$(c):(l===void 0||c!==void 0)&&(e[a]=c)}return e}function aie(e,...t){return oie(e,...t,iie)}const k$="error",cie="wss://relay.walletconnect.org",lie="wc",R$="universal_provider",ym=`${lie}@2:${R$}:`,B$="https://rpc.walletconnect.org/v1/",M$="generic",uie=`${B$}bundler`,d0="call_status",die=86400,k4={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var fie=Object.defineProperty,hie=Object.defineProperties,pie=Object.getOwnPropertyDescriptors,D$=Object.getOwnPropertySymbols,gie=Object.prototype.hasOwnProperty,mie=Object.prototype.propertyIsEnumerable,U$=(e,t,n)=>t in e?fie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wm=(e,t)=>{for(var n in t||(t={}))gie.call(t,n)&&U$(e,n,t[n]);if(D$)for(var n of D$(t))mie.call(t,n)&&U$(e,n,t[n]);return e},yie=(e,t)=>hie(e,pie(t));function L$(e,t,n){var r;const i=Ga(e);return((r=t.rpcMap)==null?void 0:r[i.reference])||`${B$}?chainId=${i.namespace}:${i.reference}&projectId=${n}`}function wie(e){return e.includes(":")?e.split(":")[1]:e}function F$(e){return e.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function bie(e,t){const n=Object.keys(t.namespaces).filter(i=>i.includes(e));if(!n.length)return[];const r=[];return n.forEach(i=>{const s=t.namespaces[i].accounts;r.push(...s)}),r}function H$(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>{var r,i;return((r=n?.chains)==null?void 0:r.length)&&((i=n?.chains)==null?void 0:i.length)>0}))}function bm(e={},t={}){const n=H$(j$(e)),r=H$(j$(t));return aie(n,r)}function j$(e){var t,n,r,i,s;const o={};if(!no(e))return o;for(const[a,c]of Object.entries(e)){const l=im(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},f=o0(a);o[f]=yie(wm(wm({},o[f]),c),{chains:eo(l,(t=o[f])==null?void 0:t.chains),methods:eo(u,(n=o[f])==null?void 0:n.methods),events:eo(d,(r=o[f])==null?void 0:r.events)}),(no(h)||no(((i=o[f])==null?void 0:i.rpcMap)||{}))&&(o[f].rpcMap=wm(wm({},h),(s=o[f])==null?void 0:s.rpcMap))}return o}function z$(e){return e.includes(":")?e.split(":")[2]:e}function V$(e){const t={};for(const[n,r]of Object.entries(e)){const i=r.methods||[],s=r.events||[],o=r.accounts||[],a=im(n)?[n]:r.chains?r.chains:F$(r.accounts);t[n]={chains:a,methods:i,events:s,accounts:o}}return t}function R4(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 vie(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}const W$={},f0=e=>W$[e],B4=(e,t)=>{W$[e]=t};var Eie=Object.defineProperty,q$=Object.getOwnPropertySymbols,Aie=Object.prototype.hasOwnProperty,Cie=Object.prototype.propertyIsEnumerable,Z$=(e,t,n)=>t in e?Eie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G$=(e,t)=>{for(var n in t||(t={}))Aie.call(t,n)&&Z$(e,n,t[n]);if(q$)for(var n of q$(t))Cie.call(t,n)&&Z$(e,n,t[n]);return e};const K$="eip155",xie=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],_ie=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,M4=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,Y$=e=>Object.keys(e).filter(t=>xie.includes(t)).reduce((t,n)=>(t[n]=Sie(e[n]),t),{}),Sie=e=>typeof e=="string"&&vie(e)?JSON.parse(e):e,Iie=(e,t,n)=>{const{sessionProperties:r={},scopedProperties:i={}}=e,s={};if(!no(i)&&!no(r))return;const o=Y$(r);for(const a of n){const c=_ie(a);if(!c)continue;s[M4(c)]=o;const l=i?.[`${K$}:${c}`];if(l){const u=l?.[`${K$}:${c}:${t}`];s[M4(c)]=G$(G$({},s[M4(c)]),Y$(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var $ie=Object.defineProperty,Tie=(e,t,n)=>t in e?$ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nie=(e,t,n)=>Tie(e,typeof t!="symbol"?t+"":t,n);let D4;class U4{constructor(t){Nie(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 D4||(D4=new U4(t)),D4}}var Pie=Object.defineProperty,Oie=Object.defineProperties,kie=Object.getOwnPropertyDescriptors,X$=Object.getOwnPropertySymbols,Rie=Object.prototype.hasOwnProperty,Bie=Object.prototype.propertyIsEnumerable,J$=(e,t,n)=>t in e?Pie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mie=(e,t)=>{for(var n in t||(t={}))Rie.call(t,n)&&J$(e,n,t[n]);if(X$)for(var n of X$(t))Bie.call(t,n)&&J$(e,n,t[n]);return e},Die=(e,t)=>Oie(e,kie(t));async function Uie(e,t){const n=Ga(e.result.capabilities.caip345.caip2),r=e.result.capabilities.caip345.transactionHashes,i=await Promise.allSettled(r.map(d=>Lie(n.reference,d,t))),s=i.filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d);i.filter(d=>d.status==="rejected").forEach(d=>console.warn("Failed to fetch transaction receipt:",d.reason));const o=!s.length||s.some(d=>!d),a=s.every(d=>d?.status==="0x1"),c=s.every(d=>d?.status==="0x0"),l=s.some(d=>d?.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:s,status:u}}async function Lie(e,t,n){return await n(parseInt(e)).request(ws("eth_getTransactionReceipt",[t]))}async function Fie({sendCalls:e,storage:t}){const n=await t.getItem(d0);await t.setItem(d0,Die(Mie({},n),{[e.result.id]:{request:e.request,result:e.result,expiry:mn(die)}}))}async function Hie({resultId:e,storage:t}){const n=await t.getItem(d0);if(n){delete n[e],await t.setItem(d0,n);for(const r in n)Qs(n[r].expiry)&&delete n[r];await t.setItem(d0,n)}}async function jie({resultId:e,storage:t}){const n=await t.getItem(d0),r=n?.[e];if(r&&!Qs(r.expiry))return r;await Hie({resultId:e,storage:t})}var zie=Object.defineProperty,Vie=Object.defineProperties,Wie=Object.getOwnPropertyDescriptors,Q$=Object.getOwnPropertySymbols,qie=Object.prototype.hasOwnProperty,Zie=Object.prototype.propertyIsEnumerable,L4=(e,t,n)=>t in e?zie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,F4=(e,t)=>{for(var n in t||(t={}))qie.call(t,n)&&L4(e,n,t[n]);if(Q$)for(var n of Q$(t))Zie.call(t,n)&&L4(e,n,t[n]);return e},H4=(e,t)=>Vie(e,Wie(t)),xu=(e,t,n)=>L4(e,typeof t!="symbol"?t+"":t,n);class Gie{constructor(t){xu(this,"name","eip155"),xu(this,"client"),xu(this,"chainId"),xu(this,"namespace"),xu(this,"httpProviders"),xu(this,"events"),xu(this,"storage"),this.namespace=t.namespace,this.events=f0("events"),this.client=f0("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=U4.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(k4.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||L$(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${t}`);return new i4(new E$(r,f0("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 i=parseInt(wie(n));t[i]=this.createHttpProvider(i,(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=H4(F4({},this.httpProviders),{[n]:this.createHttpProvider(n)}),this.httpProviders[n])}async handleSwitchChain(t){var n,r;let i=t.request.params?(n=t.request.params[0])==null?void 0:n.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const s=parseInt(i,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:i}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var n,r,i,s,o;const a=(r=(n=t.request)==null?void 0:n.params)==null?void 0:r[0],c=((s=(i=t.request)==null?void 0:i.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(t.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},d=c.length>0?c.join(","):`0x${this.chainId.toString(16)}`,h=`${a}${d}`,f=u?.[h];if(f)return f;let p;try{p=Iie(l,a,c)}catch(y){console.warn("Failed to extract capabilities from session",y)}if(p)return p;const g=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:H4(F4({},l.sessionProperties||{}),{capabilities:H4(F4({},u||{}),{[h]:g})})})}catch(y){console.warn("Failed to update session with capabilities",y)}return g}async getCallStatus(t){var n,r,i;const s=this.client.session.get(t.topic),o=(n=s.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=s.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 jie({resultId:(i=t.request.params)==null?void 0:i[0],storage:this.storage});if(c)try{return await Uie(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 i=new URL(t),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ws("eth_getUserOperationReceipt",[(r=n.request.params)==null?void 0:r[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(t,n){return`${uie}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${n}`}async sendCalls(t){var n,r,i;const s=await this.client.request(t),o=(n=t.request.params)==null?void 0:n[0],a=s?.id,c=s?.capabilities||{},l=(r=c?.caip345)==null?void 0:r.caip2,u=(i=c?.caip345)==null?void 0:i.transactionHashes;return!a||!l||!(u!=null&&u.length)||await Fie({sendCalls:{request:o,result:s},storage:this.storage}),s}}var Kie=Object.defineProperty,Yie=(e,t,n)=>t in e?Kie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,h0=(e,t,n)=>Yie(e,typeof t!="symbol"?t+"":t,n);class Xie{constructor(t){h0(this,"name",M$),h0(this,"client"),h0(this,"httpProviders"),h0(this,"events"),h0(this,"namespace"),h0(this,"chainId"),this.namespace=t.namespace,this.events=f0("events"),this.client=f0("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(k4.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 Ga(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(i=>{var s,o;const a=Ga(i),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];r[a.reference]=this.createHttpProvider(i,c)}),r}getHttpProvider(t){const n=Ga(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||L$(t,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${t}`);return new i4(new E$(r,f0("disableProviderPing")))}}var Jie=Object.defineProperty,Qie=Object.defineProperties,ese=Object.getOwnPropertyDescriptors,eT=Object.getOwnPropertySymbols,tse=Object.prototype.hasOwnProperty,nse=Object.prototype.propertyIsEnumerable,j4=(e,t,n)=>t in e?Jie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Oh=(e,t)=>{for(var n in t||(t={}))tse.call(t,n)&&j4(e,n,t[n]);if(eT)for(var n of eT(t))nse.call(t,n)&&j4(e,n,t[n]);return e},vm=(e,t)=>Qie(e,ese(t)),_i=(e,t,n)=>j4(e,typeof t!="symbol"?t+"":t,n);class Em{constructor(t){_i(this,"client"),_i(this,"namespaces"),_i(this,"optionalNamespaces"),_i(this,"sessionProperties"),_i(this,"scopedProperties"),_i(this,"events",new zn.exports),_i(this,"rpcProviders",{}),_i(this,"session"),_i(this,"providerOpts"),_i(this,"logger"),_i(this,"uri"),_i(this,"disableProviderPing",!1),_i(this,"connectParams");var n,r;this.providerOpts=t,this.logger=G8({logger:(n=t.logger)!=null?n:k$,name:(r=this.providerOpts.name)!=null?r:R$}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){const n=new Em(t);return await n.initialize(),n}async request(t,n,r){const[i,s]=this.validateChain(n);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Oh({},t),chainId:`${i}:${s}`,topic:this.session.topic,expiry:r})}sendAsync(t,n,r,i){const s=new Date().getTime();this.request(t,r,i).then(o=>n(null,Ch(s,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:Gt("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,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:i}=await this.client.authenticate(t,n);r&&(this.uri=r,this.events.emit("display_uri",r));const s=await i();if(this.session=s.session,this.session){const o=V$(this.session.namespaces);this.namespaces=bm(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}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){var n,r;const{uri:i,approval:s}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(n=this.connectParams)==null?void 0:n.authentication,walletPay:(r=this.connectParams)==null?void 0:r.walletPay});i&&(this.uri=i,this.events.emit("display_uri",i));const o=await s();this.session=o;const a=V$(o.namespaces);return this.namespaces=bm(this.namespaces,a),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,i]=this.validateChain(t),s=this.getProvider(r);s?s.setDefaultChain(i,n):this.session&&this.logger.warn(`Provider for namespace '${r}' not found in setDefaultChain`)}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(!Hi(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 Cre.init({core:this.providerOpts.core,logger:this.providerOpts.logger||k$,relayUrl:this.providerOpts.relayUrl||cie,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=>o0(n)))];B4("client",this.client),B4("events",this.events),B4("disableProviderPing",this.disableProviderPing),t.forEach(n=>{if(!this.session)return;const r=bie(n,this.session);if(r?.length===0)return;const i=F$(r),s=bm(this.namespaces,this.optionalNamespaces),o=vm(Oh({},s[n]),{accounts:r,chains:i});switch(n){case"eip155":this.rpcProviders[n]=new Gie({namespace:o});break;default:this.rpcProviders[n]=new Xie({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:i}=t;if(i!==((n=this.session)==null?void 0:n.topic))return;const{event:s}=r;if(s.name==="accountsChanged"){const o=s.data;o&&Hi(o)&&this.events.emit("accountsChanged",o.map(z$))}else if(s.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=o0(o),l=R4(o)!==R4(a)?`${c}:${R4(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:n})=>{var r,i;if(t!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:s}=n,o=(i=this.client)==null?void 0:i.session.get(t);this.session=vm(Oh({},o),{namespaces:s}),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",vm(Oh({},Gt("USER_DISCONNECTED")),{data:t.topic})))}),this.on(k4.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(vm(Oh({},t),{internal:!0}))})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[M$]}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:i,scopedProperties:s}=t;this.optionalNamespaces=bm(n,r),this.sessionProperties=i,this.scopedProperties=s}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=>o0(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 i=o0(Object.keys(this.namespaces)[0]),s=this.rpcProviders[i].getDefaultChain();return[i,s]}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[i,s]=this.validateChain(t);if(s){if(this.updateNamespaceChain(i,s),r)this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:i,currentCaipChainId:t,previousCaipChainId:n});else{const o=this.getProvider(i);o?o.setDefaultChain(s):this.session&&this.logger.warn(`Provider for namespace '${i}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:n,previousCaipChainId:r}){var i,s;try{if(r===n)return;const o=(s=(i=this.session)==null?void 0:i.namespaces[t])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${n}:`)).map(z$);if(!Hi(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}`,i={chains:[],methods:[],events:[],defaultChain:n};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=n):this.namespaces[r]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,n){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${ym}/${t}${i}`,n)}async getFromStore(t){var n;const r=((n=this.session)==null?void 0:n.topic)||"";return await this.client.core.storage.getItem(`${ym}/${t}${r}`)}async deleteFromStore(t){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.removeItem(`${ym}/${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(ym)&&await this.client.core.storage.removeItem(r)}catch(n){this.logger.warn(n,"Failed to cleanup storage")}}}const rse=Em,ise="wc",sse="ethereum_provider",ose=`${ise}@2:${sse}:`,ase="https://rpc.walletconnect.org/v1/",Am=["eth_sendTransaction","personal_sign"],tT=["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"],Cm=["chainChanged","accountsChanged"],nT=["chainChanged","accountsChanged","message","disconnect","connect"],cse=async()=>{const{createAppKit:e}=await Promise.resolve().then(function(){return wge});return e};var lse=Object.defineProperty,use=Object.defineProperties,dse=Object.getOwnPropertyDescriptors,rT=Object.getOwnPropertySymbols,fse=Object.prototype.hasOwnProperty,hse=Object.prototype.propertyIsEnumerable,z4=(e,t,n)=>t in e?lse(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_u=(e,t)=>{for(var n in t||(t={}))fse.call(t,n)&&z4(e,n,t[n]);if(rT)for(var n of rT(t))hse.call(t,n)&&z4(e,n,t[n]);return e},kh=(e,t)=>use(e,dse(t)),Si=(e,t,n)=>z4(e,typeof t!="symbol"?t+"":t,n);function xm(e){return Number(e[0].split(":")[1])}function _m(e){return`0x${e.toString(16)}`}function pse(e){const{chains:t,optionalChains:n,methods:r,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=e;if(!Hi(t))throw new Error("Invalid chains");const c={chains:t,methods:r||Am,events:s||Cm,rpcMap:_u({},t.length?{[xm(t)]:a[xm(t)]}:{})},l=s?.filter(f=>!Cm.includes(f)),u=r?.filter(f=>!Am.includes(f));if(!n&&!o&&!i&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:t.length?c:void 0};const d=l?.length&&u?.length||!n,h={chains:[...new Set(d?c.chains.concat(n||[]):n)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:tT))],events:[...new Set(c.events.concat(o!=null&&o.length?o:nT))],rpcMap:a};return{required:t.length?c:void 0,optional:n.length?h:void 0}}class Sm{constructor(){Si(this,"events",new zn.exports.EventEmitter),Si(this,"namespace","eip155"),Si(this,"accounts",[]),Si(this,"signer"),Si(this,"chainId",1),Si(this,"modal"),Si(this,"rpc"),Si(this,"STORAGE_KEY",ose),Si(this,"on",(t,n)=>(this.events.on(t,n),this)),Si(this,"once",(t,n)=>(this.events.once(t,n),this)),Si(this,"removeListener",(t,n)=>(this.events.removeListener(t,n),this)),Si(this,"off",(t,n)=>(this.events.off(t,n),this)),Si(this,"parseAccount",t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t),this.signer={},this.rpc={}}static async init(t){const n=new Sm;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:i}=pse(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const d=t!=null&&t.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect(kh(_u({namespaces:_u({},r&&{[this.namespace]:r})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic,scopedProperties:d})).then(h=>{a(h)}).catch(h=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(h.message))})});if(!s)return;const o=Y_(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_m(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}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 i=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(kh(_u({},t),{chains:this.rpc.chains}),n).then(u=>{o(u)}).catch(u=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=i.session;if(s){const o=Y_(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_m(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}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",_m(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",kh(_u({},Gt("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",_m(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,i]=t.split(":");return{chainId:`${n}:${r}`,address:i}}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 i=(n=t?.chains)!=null?n:[],s=(r=t?.optionalChains)!=null?r:[],o=i.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=i.length?t?.methods||Am:[],c=i.length?t?.events||Cm:[],l=t?.optionalMethods||[],u=t?.optionalEvents||[],d=t?.rpcMap||this.buildRpcMap(o,t.projectId),h=t?.qrModalOptions||void 0;return{chains:i?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:d,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:h,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,n){const r={};return t.forEach(i=>{r[i]=this.getRpcUrl(i,n)}),r}async initialize(t){var n;if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?xm(this.rpc.chains):xm(this.rpc.optionalChains),this.signer=await rse.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 i=await cse(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return $ge}),o=s(kh(_u({},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");r=i(kh(_u({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((n=this.rpc.qrModalOptions)==null?void 0:n.enableMobileFullScreen)===!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:n,optionalChains:r,rpcMap:i}=t;n&&Hi(n)&&(this.rpc.chains=n.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),r&&Hi(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r?.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(t,n){var r;return((r=this.rpc.rpcMap)==null?void 0:r[t])||`${ase}?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 gse=Sm,iT={isLowerCaseMatch(e,t){return e?.toLowerCase()===t?.toLowerCase()}};var sT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){var n=1e3,r=6e4,i=36e5,s="millisecond",o="second",a="minute",c="hour",l="day",u="week",d="month",h="quarter",f="year",p="date",g="Invalid Date",y=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,A=/\[([^\]]+)]|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(I){var m=["th","st","nd","rd"],b=I%100;return"["+I+(m[(b-20)%10]||m[b]||m[0])+"]"}},v=function(I,m,b){var $=String(I);return!$||$.length>=m?I:""+Array(m+1-$.length).join(b)+I},w={s:v,z:function(I){var m=-I.utcOffset(),b=Math.abs(m),$=Math.floor(b/60),N=b%60;return(m<=0?"+":"-")+v($,2,"0")+":"+v(N,2,"0")},m:function I(m,b){if(m.date()<b.date())return-I(b,m);var $=12*(b.year()-m.year())+(b.month()-m.month()),N=m.clone().add($,d),P=b-N<0,B=m.clone().add($+(P?-1:1),d);return+(-($+(b-N)/(P?N-B:B-N))||0)},a:function(I){return I<0?Math.ceil(I)||0:Math.floor(I)},p:function(I){return{M:d,y:f,w:u,d:l,D:p,h:c,m:a,s:o,ms:s,Q:h}[I]||String(I||"").toLowerCase().replace(/s$/,"")},u:function(I){return I===void 0}},T="en",O={};O[T]=_;var D="$isDayjsObject",F=function(I){return I instanceof S||!(!I||!I[D])},U=function I(m,b,$){var N;if(!m)return T;if(typeof m=="string"){var P=m.toLowerCase();O[P]&&(N=P),b&&(O[P]=b,N=P);var B=m.split("-");if(!N&&B.length>1)return I(B[0])}else{var V=m.name;O[V]=m,N=V}return!$&&N&&(T=N),N||!$&&T},j=function(I,m){if(F(I))return I.clone();var b=typeof m=="object"?m:{};return b.date=I,b.args=arguments,new S(b)},W=w;W.l=U,W.i=F,W.w=function(I,m){return j(I,{locale:m.$L,utc:m.$u,x:m.$x,$offset:m.$offset})};var S=function(){function I(b){this.$L=U(b.locale,null,!0),this.parse(b),this.$x=this.$x||b.x||{},this[D]=!0}var m=I.prototype;return m.parse=function(b){this.$d=function($){var N=$.date,P=$.utc;if(N===null)return new Date(NaN);if(W.u(N))return new Date;if(N instanceof Date)return new Date(N);if(typeof N=="string"&&!/Z$/i.test(N)){var B=N.match(y);if(B){var V=B[2]-1||0,Z=(B[7]||"0").substring(0,3);return P?new Date(Date.UTC(B[1],V,B[3]||1,B[4]||0,B[5]||0,B[6]||0,Z)):new Date(B[1],V,B[3]||1,B[4]||0,B[5]||0,B[6]||0,Z)}}return new Date(N)}(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 W},m.isValid=function(){return this.$d.toString()!==g},m.isSame=function(b,$){var N=j(b);return this.startOf($)<=N&&N<=this.endOf($)},m.isAfter=function(b,$){return j(b)<this.startOf($)},m.isBefore=function(b,$){return this.endOf($)<j(b)},m.$g=function(b,$,N){return W.u(b)?this[$]:this.set(N,b)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(b,$){var N=this,P=!!W.u($)||$,B=W.p(b),V=function(ue,ge){var Be=W.w(N.$u?Date.UTC(N.$y,ge,ue):new Date(N.$y,ge,ue),N);return P?Be:Be.endOf(l)},Z=function(ue,ge){return W.w(N.toDate()[ue].apply(N.toDate("s"),(P?[0,0,0,0]:[23,59,59,999]).slice(ge)),N)},Y=this.$W,X=this.$M,G=this.$D,ne="set"+(this.$u?"UTC":"");switch(B){case f:return P?V(1,0):V(31,11);case d:return P?V(1,X):V(0,X+1);case u:var se=this.$locale().weekStart||0,we=(Y<se?Y+7:Y)-se;return V(P?G-we:G+(6-we),X);case l:case p:return Z(ne+"Hours",0);case c:return Z(ne+"Minutes",1);case a:return Z(ne+"Seconds",2);case o:return Z(ne+"Milliseconds",3);default:return this.clone()}},m.endOf=function(b){return this.startOf(b,!1)},m.$set=function(b,$){var N,P=W.p(b),B="set"+(this.$u?"UTC":""),V=(N={},N[l]=B+"Date",N[p]=B+"Date",N[d]=B+"Month",N[f]=B+"FullYear",N[c]=B+"Hours",N[a]=B+"Minutes",N[o]=B+"Seconds",N[s]=B+"Milliseconds",N)[P],Z=P===l?this.$D+($-this.$W):$;if(P===d||P===f){var Y=this.clone().set(p,1);Y.$d[V](Z),Y.init(),this.$d=Y.set(p,Math.min(this.$D,Y.daysInMonth())).$d}else V&&this.$d[V](Z);return this.init(),this},m.set=function(b,$){return this.clone().$set(b,$)},m.get=function(b){return this[W.p(b)]()},m.add=function(b,$){var N,P=this;b=Number(b);var B=W.p($),V=function(X){var G=j(P);return W.w(G.date(G.date()+Math.round(X*b)),P)};if(B===d)return this.set(d,this.$M+b);if(B===f)return this.set(f,this.$y+b);if(B===l)return V(1);if(B===u)return V(7);var Z=(N={},N[a]=r,N[c]=i,N[o]=n,N)[B]||1,Y=this.$d.getTime()+b*Z;return W.w(Y,this)},m.subtract=function(b,$){return this.add(-1*b,$)},m.format=function(b){var $=this,N=this.$locale();if(!this.isValid())return N.invalidDate||g;var P=b||"YYYY-MM-DDTHH:mm:ssZ",B=W.z(this),V=this.$H,Z=this.$m,Y=this.$M,X=N.weekdays,G=N.months,ne=N.meridiem,se=function(ge,Be,Fe,qe){return ge&&(ge[Be]||ge($,P))||Fe[Be].slice(0,qe)},we=function(ge){return W.s(V%12||12,ge,"0")},ue=ne||function(ge,Be,Fe){var qe=ge<12?"AM":"PM";return Fe?qe.toLowerCase():qe};return P.replace(A,function(ge,Be){return Be||function(Fe){switch(Fe){case"YY":return String($.$y).slice(-2);case"YYYY":return W.s($.$y,4,"0");case"M":return Y+1;case"MM":return W.s(Y+1,2,"0");case"MMM":return se(N.monthsShort,Y,G,3);case"MMMM":return se(G,Y);case"D":return $.$D;case"DD":return W.s($.$D,2,"0");case"d":return String($.$W);case"dd":return se(N.weekdaysMin,$.$W,X,2);case"ddd":return se(N.weekdaysShort,$.$W,X,3);case"dddd":return X[$.$W];case"H":return String(V);case"HH":return W.s(V,2,"0");case"h":return we(1);case"hh":return we(2);case"a":return ue(V,Z,!0);case"A":return ue(V,Z,!1);case"m":return String(Z);case"mm":return W.s(Z,2,"0");case"s":return String($.$s);case"ss":return W.s($.$s,2,"0");case"SSS":return W.s($.$ms,3,"0");case"Z":return B}return null}(ge)||B.replace(":","")})},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(b,$,N){var P,B=this,V=W.p($),Z=j(b),Y=(Z.utcOffset()-this.utcOffset())*r,X=this-Z,G=function(){return W.m(B,Z)};switch(V){case f:P=G()/12;break;case d:P=G();break;case h:P=G()/3;break;case u:P=(X-Y)/6048e5;break;case l:P=(X-Y)/864e5;break;case c:P=X/i;break;case a:P=X/r;break;case o:P=X/n;break;default:P=X}return N?P:W.a(P)},m.daysInMonth=function(){return this.endOf(d).$D},m.$locale=function(){return O[this.$L]},m.locale=function(b,$){if(!b)return this.$L;var N=this.clone(),P=U(b,$,!0);return P&&(N.$L=P),N},m.clone=function(){return W.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()},I}(),x=S.prototype;return j.prototype=x,[["$ms",s],["$s",o],["$m",a],["$H",c],["$W",l],["$M",d],["$y",f],["$D",p]].forEach(function(I){x[I[1]]=function(m){return this.$g(m,I[0],I[1])}}),j.extend=function(I,m){return I.$i||(I(m,S,j),I.$i=!0),j},j.locale=U,j.isDayjs=F,j.unix=function(I){return j(1e3*I)},j.en=O[T],j.Ls=O,j.p={},j})})(sT);var V4=sT.exports,oT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,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"],i=n%100;return"["+n+(r[(i-20)%10]||r[i]||r[0])+"]"}}})})(oT);var mse=oT.exports,aT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){return function(n,r,i){n=n||{};var s=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,d,h){return s.fromToBase(l,u,d,h)}i.en.relativeTime=o,s.fromToBase=function(l,u,d,h,f){for(var p,g,y,A=d.$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"}],v=_.length,w=0;w<v;w+=1){var T=_[w];T.d&&(p=h?i(l).diff(d,T.d,!0):d.diff(l,T.d,!0));var O=(n.rounding||Math.round)(Math.abs(p));if(y=p>0,O<=T.r||!T.r){O<=1&&w>0&&(T=_[w-1]);var D=A[T.l];f&&(O=f(""+O)),g=typeof D=="string"?D.replace("%d",O):D(O,u,T.l,y);break}}if(u)return g;var F=y?A.future:A.past;return typeof F=="function"?F(g):F.replace("%s",g)},s.to=function(l,u){return a(l,u,this,!0)},s.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?i.utc():i()};s.toNow=function(l){return this.to(c(this),l)},s.fromNow=function(l){return this.from(c(this),l)}}})})(aT);var yse=aT.exports,cT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){return function(n,r,i){i.updateLocale=function(s,o){var a=i.Ls[s];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(cT);var wse=cT.exports;V4.extend(yse),V4.extend(wse);const bse={...mse,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"}};V4.locale("en-web3-modal",bse);const J={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(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."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:typeof process<"u"&&process.env.NODE_ENV==="development",DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"},W4={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(i=>i.caipNetworkId===t);if(n)return n.name;const[r]=t.split(":");return J.CHAIN_NAME_MAP?.[r]||void 0}},lT=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var vse=20,Ese=1,Su=1e6,uT=1e6,Ase=-7,Cse=21,xse=!1,Rh="[big.js] ",Iu=Rh+"Invalid ",Im=Iu+"decimal places",_se=Iu+"rounding mode",dT=Rh+"Division by zero",Bt={},lo=void 0,Sse=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function fT(){function e(t){var n=this;if(!(n instanceof e))return t===lo?fT():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(Iu+"value");t=t===0&&1/t<0?"-0":String(t)}Ise(n,t)}n.constructor=e}return e.prototype=Bt,e.DP=vse,e.RM=Ese,e.NE=Ase,e.PE=Cse,e.strict=xse,e.roundDown=0,e.roundHalfUp=1,e.roundHalfEven=2,e.roundUp=3,e}function Ise(e,t){var n,r,i;if(!Sse.test(t))throw Error(Iu+"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),i=t.length,r=0;r<i&&t.charAt(r)=="0";)++r;if(r==i)e.c=[e.e=0];else{for(;i>0&&t.charAt(--i)=="0";);for(e.e=n-r-1,e.c=[],n=0;r<=i;)e.c[n++]=+t.charAt(r++)}return e}function $u(e,t,n,r){var i=e.c;if(n===lo&&(n=e.constructor.RM),n!==0&&n!==1&&n!==2&&n!==3)throw Error(_se);if(t<1)r=n===3&&(r||!!i[0])||t===0&&(n===1&&i[0]>=5||n===2&&(i[0]>5||i[0]===5&&(r||i[1]!==lo))),i.length=1,r?(e.e=e.e-t+1,i[0]=1):i[0]=e.e=0;else if(t<i.length){if(r=n===1&&i[t]>=5||n===2&&(i[t]>5||i[t]===5&&(r||i[t+1]!==lo||i[t-1]&1))||n===3&&(r||!!i[0]),i.length=t,r){for(;++i[--t]>9;)if(i[t]=0,t===0){++e.e,i.unshift(1);break}}for(t=i.length;!i[--t];)i.pop()}return e}function Tu(e,t,n){var r=e.e,i=e.c.join(""),s=i.length;if(t)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>s)for(r-=s;r--;)i+="0";else r<s&&(i=i.slice(0,r)+"."+i.slice(r));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return e.s<0&&n?"-"+i:i}Bt.abs=function(){var e=new this.constructor(this);return e.s=1,e},Bt.cmp=function(e){var t,n=this,r=n.c,i=(e=new n.constructor(e)).c,s=n.s,o=e.s,a=n.e,c=e.e;if(!r[0]||!i[0])return r[0]?s:i[0]?-o:0;if(s!=o)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,s=-1;++s<o;)if(r[s]!=i[s])return r[s]>i[s]^t?1:-1;return a==c?0:a>c^t?1:-1},Bt.div=function(e){var t=this,n=t.constructor,r=t.c,i=(e=new n(e)).c,s=t.s==e.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>Su)throw Error(Im);if(!i[0])throw Error(dT);if(!r[0])return e.s=s,e.c=[e.e=0],e;var a,c,l,u,d,h=i.slice(),f=a=i.length,p=r.length,g=r.slice(0,a),y=g.length,A=e,_=A.c=[],v=0,w=o+(A.e=t.e-e.e)+1;for(A.s=s,s=w<0?0:w,h.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(d=-1,u=0;++d<a;)if(i[d]!=g[d]){u=i[d]>g[d]?1:-1;break}if(u<0){for(c=y==a?i:h;y;){if(g[--y]<c[y]){for(d=y;d&&!g[--d];)g[d]=9;--g[d],g[y]+=10}g[y]-=c[y]}for(;!g[0];)g.shift()}else break}_[v++]=u?l:++l,g[0]&&u?g[y]=r[f]||0:g=[r[f]]}while((f++<p||g[0]!==lo)&&s--);return!_[0]&&v!=1&&(_.shift(),A.e--,w--),v>w&&$u(A,w,n.RM,g[0]!==lo),A},Bt.eq=function(e){return this.cmp(e)===0},Bt.gt=function(e){return this.cmp(e)>0},Bt.gte=function(e){return this.cmp(e)>-1},Bt.lt=function(e){return this.cmp(e)<0},Bt.lte=function(e){return this.cmp(e)<1},Bt.minus=Bt.sub=function(e){var t,n,r,i,s=this,o=s.constructor,a=s.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,s.plus(e);var l=s.c.slice(),u=s.e,d=e.c,h=e.e;if(!l[0]||!d[0])return d[0]?e.s=-c:l[0]?e=new o(s):e.s=1,e;if(a=u-h){for((i=a<0)?(a=-a,r=l):(h=u,r=d),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((i=l.length<d.length)?l:d).length,a=c=0;c<n;c++)if(l[c]!=d[c]){i=l[c]<d[c];break}if(i&&(r=l,l=d,d=r,e.s=-e.s),(c=(n=d.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;n>a;){if(l[--n]<d[n]){for(t=n;t&&!l[--t];)l[t]=9;--l[t],l[n]+=10}l[n]-=d[n]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(e.s=1,l=[h=0]),e.c=l,e.e=h,e},Bt.mod=function(e){var t,n=this,r=n.constructor,i=n.s,s=(e=new r(e)).s;if(!e.c[0])throw Error(dT);return n.s=e.s=1,t=e.cmp(n)==1,n.s=i,e.s=s,t?new r(n):(i=r.DP,s=r.RM,r.DP=r.RM=0,n=n.div(e),r.DP=i,r.RM=s,this.minus(n.times(e)))},Bt.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},Bt.plus=Bt.add=function(e){var t,n,r,i=this,s=i.constructor;if(e=new s(e),i.s!=e.s)return e.s=-e.s,i.minus(e);var o=i.e,a=i.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new s(i):e.s=i.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,r=l):(t=-t,r=a),r.reverse();t--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),t=l.length,n=0;t;a[t]%=10)n=(a[--t]=a[t]+l[t]+n)/10|0;for(n&&(a.unshift(n),++c),t=a.length;a[--t]===0;)a.pop();return e.c=a,e.e=c,e},Bt.pow=function(e){var t=this,n=new t.constructor("1"),r=n,i=e<0;if(e!==~~e||e<-uT||e>uT)throw Error(Iu+"exponent");for(i&&(e=-e);e&1&&(r=r.times(t)),e>>=1,!!e;)t=t.times(t);return i?n.div(r):r},Bt.prec=function(e,t){if(e!==~~e||e<1||e>Su)throw Error(Iu+"precision");return $u(new this.constructor(this),e,t)},Bt.round=function(e,t){if(e===lo)e=0;else if(e!==~~e||e<-Su||e>Su)throw Error(Im);return $u(new this.constructor(this),e+this.e+1,t)},Bt.sqrt=function(){var e,t,n,r=this,i=r.constructor,s=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(s<0)throw Error(Rh+"No square root");s=Math.sqrt(+Tu(r,!0,!0)),s===0||s===1/0?(t=r.c.join(""),t.length+o&1||(t+="0"),s=Math.sqrt(t),o=((o+1)/2|0)-(o<0||o&1),e=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):e=new i(s+""),o=e.e+(i.DP+=4);do n=e,e=a.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return $u(e,(i.DP-=4)+e.e+1,i.RM)},Bt.times=Bt.mul=function(e){var t,n=this,r=n.constructor,i=n.c,s=(e=new r(e)).c,o=i.length,a=s.length,c=n.e,l=e.e;if(e.s=n.s==e.s?1:-1,!i[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=i,i=s,s=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+s[c]*i[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},Bt.toExponential=function(e,t){var n=this,r=n.c[0];if(e!==lo){if(e!==~~e||e<0||e>Su)throw Error(Im);for(n=$u(new n.constructor(n),++e,t);n.c.length<e;)n.c.push(0)}return Tu(n,!0,!!r)},Bt.toFixed=function(e,t){var n=this,r=n.c[0];if(e!==lo){if(e!==~~e||e<0||e>Su)throw Error(Im);for(n=$u(new n.constructor(n),e+n.e+1,t),e=e+n.e+1;n.c.length<e;)n.c.push(0)}return Tu(n,!1,!!r)},Bt[Symbol.for("nodejs.util.inspect.custom")]=Bt.toJSON=Bt.toString=function(){var e=this,t=e.constructor;return Tu(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},Bt.toNumber=function(){var e=+Tu(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(e.toString()))throw Error(Rh+"Imprecise conversion");return e},Bt.toPrecision=function(e,t){var n=this,r=n.constructor,i=n.c[0];if(e!==lo){if(e!==~~e||e<1||e>Su)throw Error(Iu+"precision");for(n=$u(new r(n),e,t);n.c.length<e;)n.c.push(0)}return Tu(n,e<=n.e||n.e<=r.NE||n.e>=r.PE,!!i)},Bt.valueOf=function(){var e=this,t=e.constructor;if(t.strict===!0)throw Error(Rh+"valueOf disallowed");return Tu(e,e.e<=t.NE||e.e>=t.PE,!0)};var uo=fT();const Et={bigNumber(e,t={safe:!1}){try{return e?new uo(e):new uo(0)}catch(n){if(t.safe)return new uo(0);throw n}},formatNumber(e,t){const{decimals:n,round:r=8,safe:i=!0}=t;return Et.bigNumber(e,{safe:i}).div(new uo(10).pow(n)).round(r)},multiply(e,t){if(e===void 0||t===void 0)return new uo(0);const n=new uo(e),r=new uo(t);return n.times(r)},toFixed(e,t=2){return e===void 0||e===""?new uo(0).toFixed(t):new uo(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 uo(t).toNumber()}},$se=[{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"}]}],Tse=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Nse=[{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"}]}],hT={getERC20Abi:e=>J.USDT_CONTRACT_ADDRESSES.includes(e)?Nse:$se,getSwapAbi:()=>Tse},p0={ConnectorExplorerIds:{[J.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[J.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[J.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[J.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[J.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[J.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[J.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[J.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[J.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[J.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[J.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[J.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[J.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[J.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[J.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[J.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[J.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[J.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[J.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"},ConnectorImageIds:{[J.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[J.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[J.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[J.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[J.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[J.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[J.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[J.CONNECTOR_ID.INJECTED]:"Browser Wallet",[J.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[J.CONNECTOR_ID.COINBASE]:"Coinbase",[J.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[J.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[J.CONNECTOR_ID.LEDGER]:"Ledger",[J.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[J.CONNECTOR_ID.INJECTED]:"INJECTED",[J.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[J.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[J.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},yt={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,i]=t;if(!n||!r||!i)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:n,chainId:r,address:i}},parseCaipNetworkId(e){const t=e.split(":");if(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}}},As={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if(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){if(As.isRpcProviderError(e)){const t=e.code===As.RPC_ERROR_CODE.USER_REJECTED_REQUEST,n=e.code===As.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||n||As.isUserRejectedMessage(e.message)}return e instanceof Error?As.isUserRejectedMessage(e.message):!1}};class Pse extends Error{constructor(t,n){super(n.message,{cause:t}),this.name=As.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=n.code}}class pT extends Pse{constructor(t){super(t,{code:As.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=As.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const De={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",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};function q4(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const Ne={setItem(e,t){Bh()&&t!==void 0&&localStorage.setItem(e,t)},getItem(e){if(Bh())return localStorage.getItem(e)||void 0},removeItem(e){Bh()&&localStorage.removeItem(e)},clear(){Bh()&&localStorage.clear()}};function Bh(){return typeof window<"u"&&typeof localStorage<"u"}function $m(e,t){const n=e?.["--apkt-accent"]??e?.["--w3m-accent"];return t==="light"?{"--w3m-accent":n||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":n||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const Ose=Symbol(),gT=Object.getPrototypeOf,Z4=new WeakMap,kse=e=>e&&(Z4.has(e)?Z4.get(e):gT(e)===Object.prototype||gT(e)===Array.prototype),Rse=e=>kse(e)&&e[Ose]||null,mT=(e,t=!0)=>{Z4.set(e,t)},G4=e=>typeof e=="object"&&e!==null,Bse=e=>G4(e)&&!Mh.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),yT=(e,t)=>{const n=K4.get(e);if(n?.[0]===t)return n[1];const r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return mT(r,!0),K4.set(e,[t,r]),Reflect.ownKeys(e).forEach(i=>{if(Object.getOwnPropertyDescriptor(r,i))return;const s=Reflect.get(e,i),{enumerable:o}=Reflect.getOwnPropertyDescriptor(e,i),a={value:s,enumerable:o,configurable:!0};if(Mh.has(s))mT(s,!1);else if(il.has(s)){const[c,l]=il.get(s);a.value=yT(c,l())}Object.defineProperty(r,i,a)}),Object.preventExtensions(r)},Mse=(e,t,n,r)=>({deleteProperty(i,s){const o=Reflect.get(i,s);n(s);const a=Reflect.deleteProperty(i,s);return a&&r(["delete",[s],o]),a},set(i,s,o,a){const c=!e()&&Reflect.has(i,s),l=Reflect.get(i,s,a);if(c&&(wT(l,o)||Dh.has(o)&&wT(l,Dh.get(o))))return!0;n(s),G4(o)&&(o=Rse(o)||o);const u=!il.has(o)&&Use(o)?Ot(o):o;return t(s,u),Reflect.set(i,s,u,a),r(["set",[s],o,l]),!0}}),il=new WeakMap,Mh=new WeakSet,K4=new WeakMap,Tm=[1],Dh=new WeakMap;let wT=Object.is,Dse=(e,t)=>new Proxy(e,t),Use=Bse,Lse=yT,Fse=Mse;function Ot(e={}){if(!G4(e))throw new Error("object required");const t=Dh.get(e);if(t)return t;let n=Tm[0];const r=new Set,i=(y,A=++Tm[0])=>{n!==A&&(s=n=A,r.forEach(_=>_(y,A)))};let s=n;const o=(y=Tm[0])=>(s!==y&&(s=y,c.forEach(([A])=>{const _=A[1](y);_>n&&(n=_)})),n),a=y=>(A,_)=>{const v=[...A];v[1]=[y,...v[1]],i(v,_)},c=new Map,l=(y,A)=>{const _=!Mh.has(A)&&il.get(A);if(_){if(c.has(y))throw new Error("prop listener already exists");if(r.size){const v=_[2](a(y));c.set(y,[_,v])}else c.set(y,[_])}},u=y=>{var A;const _=c.get(y);_&&(c.delete(y),(A=_[1])==null||A.call(_))},d=y=>(r.add(y),r.size===1&&c.forEach(([_,v],w)=>{if(v)throw new Error("remove already exists");const T=_[2](a(w));c.set(w,[_,T])}),()=>{r.delete(y),r.size===0&&c.forEach(([_,v],w)=>{v&&(v(),c.set(w,[_]))})});let h=!0;const f=Fse(()=>h,l,u,i),p=Dse(e,f);Dh.set(e,p);const g=[e,o,d];return il.set(p,g),Reflect.ownKeys(e).forEach(y=>{const A=Object.getOwnPropertyDescriptor(e,y);"value"in A&&A.writable&&(p[y]=e[y])}),h=!1,p}function bn(e,t,n){const r=il.get(e);r||console.warn("Please use proxy object");let i;const s=[],o=r[2];let a=!1;const l=o(u=>{if(s.push(u),n){t(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Uh(e){const t=il.get(e);t||console.warn("Please use proxy object");const[n,r]=t;return Lse(n,r())}function Lh(e){return Mh.add(e),e}function Hse(){return{proxyStateMap:il,refSet:Mh,snapCache:K4,versionHolder:Tm,proxyCache:Dh}}function vn(e,t,n,r){let i=e[t];return bn(e,()=>{const s=e[t];Object.is(i,s)||n(i=s)},r)}const{proxyStateMap:jse,snapCache:zse}=Hse(),Nm=e=>jse.has(e);function Vse(e){const t=[];let n=0;const r=new Map,i=new WeakMap,s=()=>{const l=zse.get(a),u=l?.[1];if(u&&!i.has(u)){const d=new Map(r);i.set(u,d)}},o=l=>i.get(l)||r;if(e){if(typeof e[Symbol.iterator]!="function")throw new TypeError(`proxyMap:
43
43
  initial state must be iterable
44
44
  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 Nm(this)||s(),o(this).size},get(l){const d=o(this).get(l);if(d===void 0){this.epoch;return}return this.data[d]},has(l){const u=o(this);return this.epoch,u.has(l)},set(l,u){if(!Nm(this))throw new Error("Cannot perform mutations on a snapshot");const d=r.get(l);return d===void 0?(r.set(l,this.index),this.data[this.index++]=u):this.data[d]=u,this.epoch++,this},delete(l){if(!Nm(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(!Nm(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((d,h)=>{l(this.data[d],h,this)})},*entries(){this.epoch;const l=o(this);for(const[u,d]of l)yield[u,this.data[d]]},*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=Ot(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 Y4=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",bT=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Wse="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",it={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Y4,SECURE_SITE_DASHBOARD:`${Y4}/dashboard`,SECURE_SITE_FAVICON:`${Y4}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD\u20AE0"]},BALANCE_SUPPORTED_CHAINS:[J.CHAIN.EVM,J.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[J.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:[J.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[p0.ConnectorExplorerIds[J.CONNECTOR_ID.COINBASE],p0.ConnectorExplorerIds[J.CONNECTOR_ID.COINBASE_SDK],p0.ConnectorExplorerIds[J.CONNECTOR_ID.BASE_ACCOUNT],p0.ConnectorExplorerIds[J.SOLFLARE_CONNECTOR_NAME],p0.ConnectorExplorerIds[J.PHANTOM_CONNECTOR_NAME],p0.ConnectorExplorerIds[J.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},me={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired(e,t){return Date.now()-e>t},getActiveNetworkProps(){const e=me.getActiveNamespace(),t=me.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{Ne.setItem(De.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=Ne.getItem(De.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Ne.removeItem(De.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{Ne.setItem(De.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{Ne.setItem(De.ACTIVE_CAIP_NETWORK_ID,e),me.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Ne.getItem(De.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Ne.removeItem(De.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=q4(e);Ne.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=me.getRecentWallets();t.find(r=>r.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Ne.setItem(De.RECENT_WALLETS,JSON.stringify(t)),Ne.setItem(De.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=Ne.getItem(De.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=Ne.getItem(De.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Ne.removeItem(De.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const n=q4(e);Ne.setItem(n,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Ne.getItem(De.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=q4(e);return Ne.getItem(t)}catch{console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{Ne.setItem(De.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Ne.getItem(De.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Ne.removeItem(De.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Ne.getItem(De.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Ne.getItem(De.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(e){try{Ne.setItem(De.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Ne.getItem(De.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=Ne.getItem(De.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));Ne.setItem(De.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=me.getConnectedNamespaces();t.includes(e)||(t.push(e),me.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=me.getConnectedNamespaces(),n=t.indexOf(e);n>-1&&(t.splice(n,1),me.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Ne.getItem(De.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{Ne.setItem(De.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Ne.removeItem(De.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=Ne.getItem(De.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=me.getBalanceCache();Ne.setItem(De.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const n=me.getBalanceCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.portfolio))return n.balance;me.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=me.getBalanceCache();t[e.caipAddress]=e,Ne.setItem(De.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=Ne.getItem(De.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=me.getBalanceCache();Ne.setItem(De.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=me.getNativeBalanceCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.nativeBalance))return n;console.info("Discarding cache for address",e),me.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=me.getNativeBalanceCache();t[e.caipAddress]=e,Ne.setItem(De.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=Ne.getItem(De.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const n=me.getEnsCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.ens))return n.ens;me.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=me.getEnsCache();t[e.address]=e,Ne.setItem(De.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=me.getEnsCache();Ne.setItem(De.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=Ne.getItem(De.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const n=me.getIdentityCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.identity))return n.identity;me.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=me.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Ne.setItem(De.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=me.getIdentityCache();Ne.setItem(De.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{const e=Ne.getItem(De.TON_WALLETS_CACHE),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;me.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{const t=me.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=new Date().getTime(),t.wallets=e,Ne.setItem(De.TON_WALLETS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{Ne.removeItem(De.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{Ne.removeItem(De.PORTFOLIO_CACHE),Ne.removeItem(De.NATIVE_BALANCE_CACHE),Ne.removeItem(De.ENS_CACHE),Ne.removeItem(De.IDENTITY_CACHE),Ne.removeItem(De.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{Ne.setItem(De.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=Ne.getItem(De.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const n=me.getConnections(),r=n[t]??[],i=new Map;for(const o of r)i.set(o.connectorId,{...o});for(const o of e){const a=i.get(o.connectorId),c=o.connectorId===J.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(d=>d.address.toLowerCase())),u=o.accounts.filter(d=>!l.has(d.address.toLowerCase()));a.accounts.push(...u)}else i.set(o.connectorId,{...o})}const s={...n,[t]:Array.from(i.values())};Ne.setItem(De.CONNECTIONS,JSON.stringify(s))}catch(n){console.error("Unable to sync connections to storage",n)}},getConnections(){try{const e=Ne.getItem(De.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=me.getConnections(),i=r[n]??[],s=new Map(i.map(a=>[a.connectorId,a])),o=s.get(e);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase()).length===0?s.delete(e):s.set(e,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase())})),Ne.setItem(De.CONNECTIONS,JSON.stringify({...r,[n]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const e=Ne.getItem(De.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const n=me.getDisconnectedConnectorIds(),r=n[t]??[];r.push(e),Ne.setItem(De.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=me.getDisconnectedConnectorIds();let r=n[t]??[];r=r.filter(i=>i.toLowerCase()!==e.toLowerCase()),Ne.setItem(De.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(me.getDisconnectedConnectorIds()[t]??[]).some(i=>i.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{const e=Ne.getItem(De.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=me.getTransactionsCache()[e]?.[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;me.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:n,transactions:r}){try{const i=me.getTransactionsCache();i[e]={...i[e],[t]:{timestamp:n,transactions:r}},Ne.setItem(De.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(i))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:n,transactions:r})}},removeTransactionsCache({address:e,chainId:t}){try{const n=me.getTransactionsCache(),r=n?.[e]||{},{[t]:i,...s}=r;Ne.setItem(De.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...n,[e]:s}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=Ne.getItem(De.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const n=me.getTokenPriceCache()[e.join(",")];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.tokenPrice))return n.tokenPrice;me.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=me.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},Ne.setItem(De.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=me.getTokenPriceCache();Ne.setItem(De.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=Ne.getItem(De.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=me.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,Ne.setItem(De.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},he={getWindow(){if(!(typeof window>"u"))return window},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 he.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()<=it.TEN_SEC_MS:!0},isAllowedRetry(e,t=it.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(he.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()+it.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 i(){e(...r)}n&&clearTimeout(n),n=setTimeout(i,t)}},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},formatNativeUrl(e,t,n=null){if(he.isHttpUrl(e))return this.formatUniversalUrl(e,t);let r=e,i=n;r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const s=encodeURIComponent(t);return{redirect:`${r}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:r}},formatUniversalUrl(e,t){if(!he.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()?me.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 i=new Image;i.onload=n,i.onerror=r,i.crossOrigin="anonymous",i.src=e});return Promise.race([t,he.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,i]=n.split("."),s=r||"0",o=i||"000";return{formattedText:`${s}.${o}${t?` ${t}`:""}`,value:s,decimals:o,symbol:t}},getApiUrl(){return J.W3M_API_URL},getBlockchainApiUrl(){return J.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return J.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,i)=>{n[r]=i}),t.sort((r,i)=>{const s=n[r.id],o=n[i.id];return s!==void 0&&o!==void 0?s-o:s!==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);case"bip122":{const n=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),r=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),i=/^bc1[a-z0-9]{39,87}$/u.test(e),s=/^bc1p[a-z0-9]{58}$/u.test(e);return n||r||i||s}default:return!1}},uniqueBy(e,t){const n=new Set;return e.filter(r=>{const i=r[t];return n.has(i)?!1:(n.add(i),!0)})},generateSdkVersion(e,t,n){const i=e.length===0?it.ADAPTER_TYPES.UNIVERSAL:e.map(s=>s.adapterType).join(",");return`${t}-${i}-${n}`},createAccount(e,t,n,r,i){return{namespace:e,address:t,type:n,publicKey:r,path:i}},isCaipAddress(e){if(typeof e!="string")return!1;const t=e.split(":"),n=t[0];return t.filter(Boolean).length===3&&n in J.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 i="provider_authorization_url=",s=e.substring(e.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),n,t);return e.replace(s,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 i=e.indexOf("&",r),s=t.length,o=i!==-1?i:e.length,a=e.substring(0,r+s),c=e.substring(r+s,o),l=e.substring(i),u=c+n;return a+u+l},isNumber(e){return typeof e!="number"&&typeof e!="string"?!1:!isNaN(Number(e))}};var vT={},Pm={};Pm.byteLength=Gse,Pm.toByteArray=Yse,Pm.fromByteArray=Qse;for(var fo=[],qi=[],qse=typeof Uint8Array<"u"?Uint8Array:Array,X4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g0=0,Zse=X4.length;g0<Zse;++g0)fo[g0]=X4[g0],qi[X4.charCodeAt(g0)]=g0;qi[45]=62,qi[95]=63;function ET(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function Gse(e){var t=ET(e),n=t[0],r=t[1];return(n+r)*3/4-r}function Kse(e,t,n){return(t+n)*3/4-n}function Yse(e){var t,n=ET(e),r=n[0],i=n[1],s=new qse(Kse(e,r,i)),o=0,a=i>0?r-4:r,c;for(c=0;c<a;c+=4)t=qi[e.charCodeAt(c)]<<18|qi[e.charCodeAt(c+1)]<<12|qi[e.charCodeAt(c+2)]<<6|qi[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=qi[e.charCodeAt(c)]<<2|qi[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=qi[e.charCodeAt(c)]<<10|qi[e.charCodeAt(c+1)]<<4|qi[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function Xse(e){return fo[e>>18&63]+fo[e>>12&63]+fo[e>>6&63]+fo[e&63]}function Jse(e,t,n){for(var r,i=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(Xse(r));return i.join("")}function Qse(e){for(var t,n=e.length,r=n%3,i=[],s=16383,o=0,a=n-r;o<a;o+=s)i.push(Jse(e,o,o+s>a?a:o+s));return r===1?(t=e[n-1],i.push(fo[t>>2]+fo[t<<4&63]+"==")):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(fo[t>>10]+fo[t>>4&63]+fo[t<<2&63]+"=")),i.join("")}var J4={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */J4.read=function(e,t,n,r,i){var s,o,a=i*8-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?i-1:0,h=n?-1:1,f=e[t+d];for(d+=h,s=f&(1<<-u)-1,f>>=-u,u+=a;u>0;s=s*256+e[t+d],d+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=h,u-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(f?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-l}return(f?-1:1)*o*Math.pow(2,s-r)},J4.write=function(e,t,n,r,i,s){var o,a,c,l=s*8-i-1,u=(1<<l)-1,d=u>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?t+=h/c:t+=h*Math.pow(2,1-d),t*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*c-1)*Math.pow(2,i),o=o+d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=a&255,f+=p,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;e[n+f]=o&255,f+=p,o/=256,l-=8);e[n+f-p]|=g*128};/*!