@walletconnect/pos-client 1.0.5 → 1.0.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
@@ -37,5 +37,5 @@ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(f5(n)).toStr
37
37
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
38
38
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
39
39
  PERFORMANCE OF THIS SOFTWARE.
40
- ***************************************************************************** */var El=function(t,e){return El=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])},El(t,e)};function W9(t,e){El(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var xl=function(){return xl=Object.assign||function(e){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)&&(e[s]=n[s])}return e},xl.apply(this,arguments)};function Z9(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function Y9(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function X9(t,e){return function(n,r){e(n,r,t)}}function J9(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Q9(t,e,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(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function e7(t,e){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(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function t7(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function n7(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function _l(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function F1(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >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 r7(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F1(arguments[e]));return t}function i7(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ns(t){return this instanceof Ns?(this.v=t,this):new Ns(t)}function s7(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){r[d]&&(i[d]=function(h){return new Promise(function(p,b){s.push([d,h,p,b])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Ns?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function o7(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Ns(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function a7(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof _l=="function"?_l(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function c7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function u7(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function l7(t){return t&&t.__esModule?t:{default:t}}function f7(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h7(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var d7=Object.freeze({__proto__:null,__extends:W9,get __assign(){return xl},__rest:Z9,__decorate:Y9,__param:X9,__metadata:J9,__awaiter:Q9,__generator:e7,__createBinding:t7,__exportStar:n7,__values:_l,__read:F1,__spread:r7,__spreadArrays:i7,__await:Ns,__asyncGenerator:s7,__asyncDelegator:o7,__asyncValues:a7,__makeTemplateObject:c7,__importStar:u7,__importDefault:l7,__classPrivateFieldGet:f7,__classPrivateFieldSet:h7}),p7=Gl(d7),kn={},L1;function g7(){if(L1)return kn;L1=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.isBrowserCryptoAvailable=kn.getSubtleCrypto=kn.getBrowerCrypto=void 0;function t(){return nn?.crypto||nn?.msCrypto||{}}kn.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}kn.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return kn.isBrowserCryptoAvailable=n,kn}var qn={},k1;function y7(){if(k1)return qn;k1=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function n(){return!t()&&!e()}return qn.isBrowser=n,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=p7;e.__exportStar(g7(),t),e.__exportStar(y7(),t)})(U1);function Pt(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Sr(t=6){return BigInt(Pt(t))}function Mn(t,e,n){return{id:n||Pt(),jsonrpc:"2.0",method:t,params:e}}function va(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Il(t,e,n){return{id:t,jsonrpc:"2.0",error:b7(e,n)}}function b7(t,e){return typeof t>"u"?C1(R1):(typeof t=="string"&&(t=Object.assign(Object.assign({},C1(vl)),{message:t})),typeof e<"u"&&(t.data=e),K9(t.code)&&(t=H9(t.code)),t)}class w7{}class m7 extends w7{constructor(){super()}}class v7 extends m7{constructor(e){super()}}const E7="^wss?:";function x7(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function _7(t,e){const n=x7(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function q1(t){return _7(t,E7)}function I7(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function M1(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Sl(t){return M1(t)&&"method"in t}function Ea(t){return M1(t)&&(ln(t)||jt(t))}function ln(t){return"result"in t}function jt(t){return"error"in t}class S7 extends v7{constructor(e){super(e),this.events=new rt.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(Mn(e.method,e.params||[],e.id||Sr().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{jt(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Ea(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const O7=()=>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"),B7=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",j1=t=>t.split("?")[0],z1=10,A7=O7();class $7{constructor(e){if(this.url=e,this.events=new rt.exports.EventEmitter,this.registering=!1,!q1(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(zi(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!q1(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);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=e,this.registering=!0,new Promise((n,r)=>{const i=U1.isReactNative()?void 0:{rejectUnauthorized:!I7(e)},s=new A7(e,[],i);B7()?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(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?ri(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=Il(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return G9(e,j1(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>z1&&this.events.setMaxListeners(z1)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${j1(this.url)}`));return this.events.emit("register_error",n),n}}var D7=Object.defineProperty,V1=Object.getOwnPropertySymbols,T7=Object.prototype.hasOwnProperty,P7=Object.prototype.propertyIsEnumerable,K1=(t,e,n)=>e in t?D7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ft=(t,e)=>{for(var n in e||(e={}))T7.call(e,n)&&K1(t,n,e[n]);if(V1)for(var n of V1(e))P7.call(e,n)&&K1(t,n,e[n]);return t};const H1="wc",G1=2,xa="core",fn=`${H1}@2:${xa}:`,R7={name:xa,logger:"error"},N7={database:":memory:"},C7="crypto",W1="client_ed25519_seed",U7=H.ONE_DAY,F7="keychain",L7="0.3",k7="messages",q7="0.3",M7=H.SIX_HOURS,j7="publisher",Z1="irn",z7="error",Y1="wss://relay.walletconnect.org",V7="relayer",Se={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"},K7="_subscription",zt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},H7=.1,Ol="2.23.5",ve={link_mode:"link_mode",relay:"relay"},_a={inbound:"inbound",outbound:"outbound"},G7="0.3",W7="WALLETCONNECT_CLIENT_ID",X1="WALLETCONNECT_LINK_MODE_APPS",Rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Z7="subscription",Y7="0.3",X7="pairing",J7="0.3",Cs={wc_pairingDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:H.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:H.ONE_DAY,prompt:!1,tag:0},res:{ttl:H.ONE_DAY,prompt:!1,tag:0}}},Xr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},en={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Q7="history",eO="0.3",tO="expirer",Vt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},nO="0.3",rO="verify-api",iO="https://verify.walletconnect.com",J1="https://verify.walletconnect.org",Us=J1,sO=`${Us}/v3`,oO=[iO,J1],aO="echo",cO="https://echo.walletconnect.com",hn={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"},jn={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"},tn={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"},Jr={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"},Qr={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"},Fs={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},uO=.1,lO="event-client",fO=86400,hO="https://pulse.walletconnect.org/batch";function dO(t,e){if(t.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<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,m=0,B=0,D=p.length;B!==D&&p[B]===0;)B++,b++;for(var _=(D-B)*l+1>>>0,x=new Uint8Array(_);B!==D;){for(var T=p[B],P=0,C=_-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*x[C]>>>0,x[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=_-m;U!==_&&x[U]===0;)U++;for(var $=c.repeat(b);U<_;++U)$+=t.charAt(x[U]);return $}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var m=0,B=0;p[b]===c;)m++,b++;for(var D=(p.length-b)*u+1>>>0,_=new Uint8Array(D);p[b];){var x=n[p.charCodeAt(b)];if(x===255)return;for(var T=0,P=D-1;(x!==0||T<B)&&P!==-1;P--,T++)x+=a*_[P]>>>0,_[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");B=T,b++}if(p[b]!==" "){for(var C=D-B;C!==D&&_[C]===0;)C++;for(var U=new Uint8Array(m+(D-C)),$=m;C!==D;)U[$++]=_[C++];return U}}}function h(p){var b=d(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var pO=dO,gO=pO;const Q1=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},yO=t=>new TextEncoder().encode(t),bO=t=>new TextDecoder().decode(t);class wO{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class mO{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ey(this,e)}}class vO{constructor(e){this.decoders=e}or(e){return ey(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ey=(t,e)=>new vO(ft(ft({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class EO{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new wO(e,n,r),this.decoder=new mO(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ia=({name:t,prefix:e,encode:n,decode:r})=>new EO(t,e,n,r),Ls=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=gO(n,e);return Ia({prefix:t,name:e,encode:r,decode:s=>Q1(i(s))})},xO=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},_O=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},ze=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ia({prefix:e,name:t,encode(i){return _O(i,r,n)},decode(i){return xO(i,r,n,t)}}),IO=Ia({prefix:"\0",name:"identity",encode:t=>bO(t),decode:t=>yO(t)});var SO=Object.freeze({__proto__:null,identity:IO});const OO=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var BO=Object.freeze({__proto__:null,base2:OO});const AO=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $O=Object.freeze({__proto__:null,base8:AO});const DO=Ls({prefix:"9",name:"base10",alphabet:"0123456789"});var TO=Object.freeze({__proto__:null,base10:DO});const PO=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),RO=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var NO=Object.freeze({__proto__:null,base16:PO,base16upper:RO});const CO=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),UO=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),FO=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LO=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kO=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qO=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),MO=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jO=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zO=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var VO=Object.freeze({__proto__:null,base32:CO,base32upper:UO,base32pad:FO,base32padupper:LO,base32hex:kO,base32hexupper:qO,base32hexpad:MO,base32hexpadupper:jO,base32z:zO});const KO=Ls({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),HO=Ls({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var GO=Object.freeze({__proto__:null,base36:KO,base36upper:HO});const WO=Ls({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ZO=Ls({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var YO=Object.freeze({__proto__:null,base58btc:WO,base58flickr:ZO});const XO=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),JO=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QO=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eB=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tB=Object.freeze({__proto__:null,base64:XO,base64pad:JO,base64url:QO,base64urlpad:eB});const ty=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}"),nB=ty.reduce((t,e,n)=>(t[n]=e,t),[]),rB=ty.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function iB(t){return t.reduce((e,n)=>(e+=nB[n],e),"")}function sB(t){const e=[];for(const n of t){const r=rB[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const oB=Ia({prefix:"\u{1F680}",name:"base256emoji",encode:iB,decode:sB});var aB=Object.freeze({__proto__:null,base256emoji:oB}),cB=ry,ny=128,uB=127,lB=~uB,fB=Math.pow(2,31);function ry(t,e,n){e=e||[],n=n||0;for(var r=n;t>=fB;)e[n++]=t&255|ny,t/=128;for(;t&lB;)e[n++]=t&255|ny,t>>>=7;return e[n]=t|0,ry.bytes=n-r+1,e}var hB=Bl,dB=128,iy=127;function Bl(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Bl.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&iy)<<i:(o&iy)*Math.pow(2,i),i+=7}while(o>=dB);return Bl.bytes=s-r,n}var pB=Math.pow(2,7),gB=Math.pow(2,14),yB=Math.pow(2,21),bB=Math.pow(2,28),wB=Math.pow(2,35),mB=Math.pow(2,42),vB=Math.pow(2,49),EB=Math.pow(2,56),xB=Math.pow(2,63),_B=function(t){return t<pB?1:t<gB?2:t<yB?3:t<bB?4:t<wB?5:t<mB?6:t<vB?7:t<EB?8:t<xB?9:10},IB={encode:cB,decode:hB,encodingLength:_B},sy=IB;const oy=(t,e,n=0)=>(sy.encode(t,e,n),e),ay=t=>sy.encodingLength(t),Al=(t,e)=>{const n=e.byteLength,r=ay(t),i=r+ay(n),s=new Uint8Array(i+n);return oy(t,s,0),oy(n,s,r),s.set(e,i),new SB(t,n,e,s)};class SB{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const cy=({name:t,code:e,encode:n})=>new OB(t,e,n);class OB{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Al(this.code,n):n.then(r=>Al(this.code,r))}else throw Error("Unknown type, must be binary type")}}const uy=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),BB=cy({name:"sha2-256",code:18,encode:uy("SHA-256")}),AB=cy({name:"sha2-512",code:19,encode:uy("SHA-512")});var $B=Object.freeze({__proto__:null,sha256:BB,sha512:AB});const ly=0,DB="identity",fy=Q1;var TB=Object.freeze({__proto__:null,identity:{code:ly,name:DB,encode:fy,digest:t=>Al(ly,fy(t))}});new TextEncoder,new TextDecoder;const hy=ft(ft(ft(ft(ft(ft(ft(ft(ft(ft({},SO),BO),$O),TO),NO),VO),GO),YO),tB),aB);ft(ft({},$B),TB);function dy(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function PB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?dy(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function py(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const gy=py("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),$l=py("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=PB(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),RB=ft({utf8:gy,"utf-8":gy,hex:hy.base16,latin1:$l,ascii:$l,binary:$l},hy);function NB(t,e="utf8"){const n=RB[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?dy(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var CB=Object.defineProperty,UB=(t,e,n)=>e in t?CB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>UB(t,typeof e!="symbol"?e+"":e,n);class FB{constructor(e,n){this.core=e,this.logger=n,dn(this,"keychain",new Map),dn(this,"name",F7),dn(this,"version",L7),dn(this,"initialized",!1),dn(this,"storagePrefix",fn),dn(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),dn(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),dn(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),dn(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=G("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),dn(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Cu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var LB=Object.defineProperty,kB=(t,e,n)=>e in t?LB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fe=(t,e,n)=>kB(t,typeof e!="symbol"?e+"":e,n);class qB{constructor(e,n,r){this.core=e,this.logger=n,Fe(this,"name",C7),Fe(this,"keychain"),Fe(this,"randomSessionIdentifier",pl()),Fe(this,"initialized",!1),Fe(this,"clientId"),Fe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Fe(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Fe(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=Rh(i),o=Ph(s.publicKey);return this.clientId=o,o}),Fe(this,"generateKeyPair",()=>{this.isInitialized();const i=ES();return this.setPrivateKey(i.publicKey,i.privateKey)}),Fe(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Rh(s),a=this.randomSessionIdentifier;return await hE(a,i,U7,o)}),Fe(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=xS(a,s);return this.setSymKey(c,o)}),Fe(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ba(i);return await this.keychain.set(o,i),o}),Fe(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"encode",async(i,s,o)=>{this.isInitialized();const a=h1(o),c=zi(s);if(p1(a))return SS(c,o?.encoding);if(d1(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;i=await this.generateSharedKey(d,h)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return _S({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Fe(this,"decode",async(i,s,o)=>{this.isInitialized();const a=BS(s,o);if(p1(a)){const c=OS(s,o?.encoding);return ri(c)}if(d1(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=IS({symKey:c,encoded:s,encoding:o?.encoding});return ri(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Fe(this,"getPayloadType",(i,s=xt)=>{const o=$s({encoded:i,encoding:s});return Yr(o.type)}),Fe(this,"getPayloadSenderPublicKey",(i,s=xt)=>{const o=$s({encoded:i,encoding:s});return o.senderPublicKey?mt(o.senderPublicKey,lt):void 0}),this.core=e,this.logger=Ot(n,this.name),this.keychain=r||new FB(this.core,this.logger)}get context(){return dt(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(W1)}catch{e=pl(),await this.keychain.set(W1,e)}return NB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MB=Object.defineProperty,jB=Object.defineProperties,zB=Object.getOwnPropertyDescriptors,yy=Object.getOwnPropertySymbols,VB=Object.prototype.hasOwnProperty,KB=Object.prototype.propertyIsEnumerable,Dl=(t,e,n)=>e in t?MB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,HB=(t,e)=>{for(var n in e||(e={}))VB.call(e,n)&&Dl(t,n,e[n]);if(yy)for(var n of yy(e))KB.call(e,n)&&Dl(t,n,e[n]);return t},GB=(t,e)=>jB(t,zB(e)),Nt=(t,e,n)=>Dl(t,typeof e!="symbol"?e+"":e,n);class WB extends fm{constructor(e,n){super(e,n),this.logger=e,this.core=n,Nt(this,"messages",new Map),Nt(this,"messagesWithoutClientAck",new Map),Nt(this,"name",k7),Nt(this,"version",q7),Nt(this,"initialized",!1),Nt(this,"storagePrefix",fn),Nt(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}}}),Nt(this,"set",async(r,i,s)=>{this.isInitialized();const o=Mt(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===_a.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,GB(HB({},c),{[o]:i}))}return await this.persist(),o}),Nt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),Nt(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}),Nt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Mt(i);return typeof s[o]<"u"}),Nt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Mt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),Nt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Ot(e,this.name),this.core=n}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Cu(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Cu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZB=Object.defineProperty,YB=Object.defineProperties,XB=Object.getOwnPropertyDescriptors,by=Object.getOwnPropertySymbols,JB=Object.prototype.hasOwnProperty,QB=Object.prototype.propertyIsEnumerable,Tl=(t,e,n)=>e in t?ZB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ui=(t,e)=>{for(var n in e||(e={}))JB.call(e,n)&&Tl(t,n,e[n]);if(by)for(var n of by(e))QB.call(e,n)&&Tl(t,n,e[n]);return t},wy=(t,e)=>YB(t,XB(e)),Kt=(t,e,n)=>Tl(t,typeof e!="symbol"?e+"":e,n);class eA extends hm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Kt(this,"events",new rt.exports.EventEmitter),Kt(this,"name",j7),Kt(this,"queue",new Map),Kt(this,"publishTimeout",H.toMiliseconds(H.ONE_MINUTE)),Kt(this,"initialPublishTimeout",H.toMiliseconds(H.ONE_SECOND*15)),Kt(this,"needsTransportRestart",!1),Kt(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const f=s?.ttl||M7,d=s?.prompt||!1,h=s?.tag||0,p=s?.id||Sr().toString(),b=Ri(wa().protocol),m={id:p,method:s?.publishMethod||b.publish,params:Ui({topic:r,message:i,ttl:f,prompt:d,tag:h,attestation:s?.attestation},s?.tvf)},B=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{Re((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Re((c=m.params)==null?void 0:c.tag)&&((u=m.params)==null||delete u.tag);const D=new Promise(async _=>{const x=({id:P})=>{var C;((C=m.id)==null?void 0:C.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Se.publish,x),_())};this.relayer.events.on(Se.publish,x);const T=cn(new Promise((P,C)=>{this.rpcPublish(m,s).then(P).catch(U=>{this.logger.warn(U,U?.message),C(U)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await T,this.events.removeListener(Se.publish,x)}catch(P){this.queue.set(p,{request:m,opts:s,attempt:1}),this.logger.warn(P,P?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await cn(D,this.publishTimeout,B)}catch(D){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(D),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw D}finally{this.queue.delete(p)}}),Kt(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:u,opts:l={}}=r,{attestation:f,tvf:d,publishMethod:h,prompt:p,tag:b,ttl:m=H.FIVE_MINUTES}=l,B=l.id||Sr().toString(),D=Ri(wa().protocol),_=h||D.publish,x={id:B,method:_,params:Ui(wy(Ui({},u),{ttl:m,prompt:p,tag:b,attestation:f}),d)},T=`Failed to publish custom payload, please try again. id:${B} tag:${b}`;try{Re((i=x.params)==null?void 0:i.prompt)&&((s=x.params)==null||delete s.prompt),Re((o=x.params)==null?void 0:o.tag)&&((a=x.params)==null||delete a.tag);const P=new Promise(async C=>{const U=({id:j})=>{var M;((M=x.id)==null?void 0:M.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(Se.publish,U),C())};this.relayer.events.on(Se.publish,U);const $=cn(new Promise((j,M)=>{this.rpcPublish(x,l).then(j).catch(E=>{this.logger.warn(E,E?.message),M(E)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${_} id:${B} tag:${b}`);try{await $,this.events.removeListener(Se.publish,U)}catch(j){this.queue.set(B,{request:x,opts:l,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:B,payload:u,opts:l}}),await cn(P,this.publishTimeout,T)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(B)}}),Kt(this,"on",(r,i)=>{this.events.on(r,i)}),Kt(this,"once",(r,i)=>{this.events.once(r,i)}),Kt(this,"off",(r,i)=>{this.events.off(r,i)}),Kt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=Ot(n,this.name),this.registerEventListeners()}get context(){return dt(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(Se.publish,Ui(Ui({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,wy(Ui({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on($r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Se.connection_stalled);return}this.checkQueue()}),this.relayer.on(Se.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var tA=Object.defineProperty,nA=(t,e,n)=>e in t?tA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fi=(t,e,n)=>nA(t,typeof e!="symbol"?e+"":e,n);class rA{constructor(){Fi(this,"map",new Map),Fi(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Fi(this,"get",e=>this.map.get(e)||[]),Fi(this,"exists",(e,n)=>this.get(e).includes(n)),Fi(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Fi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var iA=Object.defineProperty,sA=Object.defineProperties,oA=Object.getOwnPropertyDescriptors,my=Object.getOwnPropertySymbols,aA=Object.prototype.hasOwnProperty,cA=Object.prototype.propertyIsEnumerable,Pl=(t,e,n)=>e in t?iA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ks=(t,e)=>{for(var n in e||(e={}))aA.call(e,n)&&Pl(t,n,e[n]);if(my)for(var n of my(e))cA.call(e,n)&&Pl(t,n,e[n]);return t},Rl=(t,e)=>sA(t,oA(e)),be=(t,e,n)=>Pl(t,typeof e!="symbol"?e+"":e,n);class uA extends gm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,be(this,"subscriptions",new Map),be(this,"topicMap",new rA),be(this,"events",new rt.exports.EventEmitter),be(this,"name",Z7),be(this,"version",Y7),be(this,"pending",new Map),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",fn),be(this,"subscribeTimeout",H.toMiliseconds(H.ONE_MINUTE)),be(this,"initialSubscribeTimeout",H.toMiliseconds(H.ONE_SECOND*15)),be(this,"clientId"),be(this,"batchSubscribeTopicsLimit",500),be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),be(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=wa(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}}),be(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),be(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),be(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),be(this,"on",(r,i)=>{this.events.on(r,i)}),be(this,"once",(r,i)=>{this.events.once(r,i)}),be(this,"off",(r,i)=>{this.events.off(r,i)}),be(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),be(this,"start",async()=>{await this.onConnect()}),be(this,"stop",async()=>{await this.onDisconnect()}),be(this,"restart",async()=>{await this.restore(),await this.onRestart()}),be(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)}),be(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on($r.pulse,async()=>{await this.checkPending()}),this.events.on(Rt.created,async r=>{const i=Rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Rt.deleted,async r=>{const i=Rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=Ot(n,this.name),this.clientId=""}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,n){let r=!1;try{r=this.getSubscription(e).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(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=wa(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=xe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===ve.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Ri(n.protocol).subscribe,params:{topic:e}};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===ve.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},H.toMiliseconds(H.ONE_SECOND)),o;const u=new Promise(async f=>{const d=h=>{h.topic===e&&(this.events.removeListener(Rt.created,d),f(h.id))};this.events.on(Rt.created,d);try{const h=await cn(new Promise((p,b)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m?.message),b(m)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Rt.created,d),f(h)}catch{}}),l=await cn(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Se.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const n=e[0].relay,r={method:Ri(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await cn(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(Se.connection_stalled),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Ri(n.protocol).batchFetchMessages,params:{topics:e.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 cn(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(Se.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Ri(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,Rl(ks({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,ks({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,ks({},n)),this.topicMap.set(n.topic,e),this.events.emit(Rt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(Rt.deleted,Rl(ks({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Rt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e)){this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),e.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(e.map(async n=>Rl(ks({},n),{id:await this.getSubscriptionId(n.topic)}))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await M_(H.toMiliseconds(H.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Mt(e+await this.getClientId())}}var lA=Object.defineProperty,vy=Object.getOwnPropertySymbols,fA=Object.prototype.hasOwnProperty,hA=Object.prototype.propertyIsEnumerable,Nl=(t,e,n)=>e in t?lA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ey=(t,e)=>{for(var n in e||(e={}))fA.call(e,n)&&Nl(t,n,e[n]);if(vy)for(var n of vy(e))hA.call(e,n)&&Nl(t,n,e[n]);return t},re=(t,e,n)=>Nl(t,typeof e!="symbol"?e+"":e,n);class dA extends dm{constructor(e){var n;super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new rt.exports.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",V7),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",H.toMiliseconds(H.THIRTY_SECONDS+H.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",H.toMiliseconds(H.ONE_SECOND*15)),re(this,"stalledRestartInProgress",!1),re(this,"stalledRestartTimeout"),re(this,"stalledRestartBackoff",0),re(this,"stalledRestartBaseInterval",H.toMiliseconds(H.ONE_SECOND*2)),re(this,"stalledRestartMaxInterval",H.toMiliseconds(H.THIRTY_SECONDS)),re(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||Sr().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(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),re(this,"resetPingTimeout",()=>{Yo()&&(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))}),re(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Se.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Se.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))}),re(this,"registerProviderListeners",()=>{this.provider.on(zt.payload,this.onPayloadHandler),this.provider.on(zt.connect,this.onConnectHandler),this.provider.on(zt.disconnect,this.onDisconnectHandler),this.provider.on(zt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=P1({logger:(n=e.logger)!=null?n:z7,name:this.name}),this.messages=new WB(this.logger,e.core),this.subscriber=new uA(this,this.logger),this.publisher=new eA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Y1,S_()?this.packageName=N0():O_()&&(this.bundleId=N0()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return dt(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:ve.relay},_a.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,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(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(Rt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Rt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,Ey({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await cn(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(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(e).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(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||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 T1())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=e.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(e,n){const{topic:r}=e;if(!n.sessionExists){const i=Te(H.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(Se.message,e),await this.recordMessageEvent(e,_a.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,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(zt.disconnect,s),await cn(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(zt.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(zt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zt.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,H.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Yo())try{(n=(e=this.provider)==null?void 0:e.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 e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new S7(new $7(T_({sdkVersion:Ol,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;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(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sl(e)){if(!e.method.endsWith(K7))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:ve.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ey({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ea(e)&&this.events.emit(Se.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,_a.inbound),this.events.emit(Se.message,e))}async acknowledgePayload(e){const n=va(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zt.payload,this.onPayloadHandler),this.provider.off(zt.connect,this.onConnectHandler),this.provider.off(zt.disconnect,this.onDisconnectHandler),this.provider.off(zt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await T1();A9(async n=>{e!==n&&(e=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($r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&T9())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(Se.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(Se.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},H.toMiliseconds(H7)))))}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function pA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function xy(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function _y(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const gA="[object RegExp]",yA="[object String]",bA="[object Number]",wA="[object Boolean]",Iy="[object Arguments]",mA="[object Symbol]",vA="[object Date]",EA="[object Map]",xA="[object Set]",_A="[object Array]",IA="[object Function]",SA="[object ArrayBuffer]",Cl="[object Object]",OA="[object Error]",BA="[object DataView]",AA="[object Uint8Array]",$A="[object Uint8ClampedArray]",DA="[object Uint16Array]",TA="[object Uint32Array]",PA="[object BigUint64Array]",RA="[object Int8Array]",NA="[object Int16Array]",CA="[object Int32Array]",UA="[object BigInt64Array]",FA="[object Float32Array]",LA="[object Float64Array]";function Sy(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function kA(t,e,n){return qs(t,e,void 0,void 0,void 0,void 0,n)}function qs(t,e,n,r,i,s,o){const a=o(t,e,n,r,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Ms(t,e,s,o)}return Ms(t,e,s,o)}function Ms(t,e,n,r){if(Object.is(t,e))return!0;let i=_y(t),s=_y(e);if(i===Iy&&(i=Cl),s===Iy&&(s=Cl),i!==s)return!1;switch(i){case yA:return t.toString()===e.toString();case bA:{const c=t.valueOf(),u=e.valueOf();return pA(c,u)}case wA:case vA:case mA:return Object.is(t.valueOf(),e.valueOf());case gA:return t.source===e.source&&t.flags===e.flags;case IA:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case EA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!qs(u,e.get(c),c,t,e,n,r))return!1;return!0}case xA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const f=c[l],d=u.findIndex(h=>qs(f,h,void 0,t,e,n,r));if(d===-1)return!1;u.splice(d,1)}return!0}case _A:case AA:case $A:case DA:case TA:case PA:case RA:case NA:case CA:case UA:case FA:case LA:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!qs(t[c],e[c],c,t,e,n,r))return!1;return!0}case SA:return t.byteLength!==e.byteLength?!1:Ms(new Uint8Array(t),new Uint8Array(e),n,r);case BA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Ms(new Uint8Array(t),new Uint8Array(e),n,r);case OA:return t.name===e.name&&t.message===e.message;case Cl:{if(!(Ms(t.constructor,e.constructor,n,r)||Sy(t)&&Sy(e)))return!1;const c=[...Object.keys(t),...xy(t)],u=[...Object.keys(e),...xy(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],d=t[f];if(!Object.hasOwn(e,f))return!1;const h=e[f];if(!qs(d,h,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function qA(){}function MA(t,e){return kA(t,e,qA)}var jA=Object.defineProperty,Oy=Object.getOwnPropertySymbols,zA=Object.prototype.hasOwnProperty,VA=Object.prototype.propertyIsEnumerable,Ul=(t,e,n)=>e in t?jA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,By=(t,e)=>{for(var n in e||(e={}))zA.call(e,n)&&Ul(t,n,e[n]);if(Oy)for(var n of Oy(e))VA.call(e,n)&&Ul(t,n,e[n]);return t},It=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);class ei extends pm{constructor(e,n,r,i=fn,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,It(this,"map",new Map),It(this,"version",G7),It(this,"cached",[]),It(this,"initialized",!1),It(this,"getKey"),It(this,"storagePrefix",fn),It(this,"recentlyDeleted",[]),It(this,"recentlyDeletedLimit",200),It(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Re(o)?this.map.set(this.getKey(o),o):s9(o)?this.map.set(o.id,o):o9(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),It(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())}),It(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),It(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>MA(a[c],o[c]))):this.values)),It(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=By(By({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),It(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=Ot(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KA=Object.defineProperty,HA=(t,e,n)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>HA(t,typeof e!="symbol"?e+"":e,n);class GA{constructor(e,n){this.core=e,this.logger=n,oe(this,"name",X7),oe(this,"version",J7),oe(this,"events",new rt.exports),oe(this,"pairings"),oe(this,"initialized",!1),oe(this,"storagePrefix",fn),oe(this,"ignoredPayloadTypes",[Ln]),oe(this,"registeredMethods",[]),oe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),oe(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),oe(this,"create",async r=>{this.isInitialized();const i=pl(),s=await this.core.crypto.setSymKey(i),o=Te(H.FIVE_MINUTES),a={protocol:Z1},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=w1({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Xr.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:u}}),oe(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[hn.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=b1(r.uri);i.props.properties.topic=s,i.addTrace(hn.pairing_uri_validation_success),i.addTrace(hn.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(hn.existing_pairing),l.active)throw i.setError(jn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(hn.pairing_not_expired)}const f=c||Te(H.FIVE_MINUTES),d={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,d),i.addTrace(hn.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Xr.create,d),i.addTrace(hn.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(hn.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(jn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw i.setError(jn.subscribe_pairing_topic_failure),h}return i.addTrace(hn.subscribe_pairing_topic_success),d}),oe(this,"activate",async({topic:r})=>{this.isInitialized();const i=Te(H.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),oe(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}=zr();this.events.once(de("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),oe(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),oe(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),oe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),oe(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",xe("USER_DISCONNECTED")),await this.deletePairing(i))}),oe(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return w1({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),oe(this,"sendRequest",async(r,i,s)=>{const o=Mn(i,s),a=await this.core.crypto.encode(r,o),c=Cs[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),oe(this,"sendResult",async(r,i,s)=>{const o=va(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Cs[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),oe(this,"sendError",async(r,i,s)=>{const o=Il(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Cs[c]?Cs[c].res:Cs.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),oe(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,xe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),oe(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>lr(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),oe(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)}}),oe(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)}}),oe(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Xr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),oe(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{ln(i)?this.events.emit(de("pairing_ping",s),{}):jt(i)&&this.events.emit(de("pairing_ping",s),{error:i.error})},500)}),oe(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Xr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),oe(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=xe("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)}}),oe(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(xe("WC_METHOD_UNSUPPORTED",r))}),oe(this,"isValidPair",(r,i)=>{var s;if(!_t(r)){const{message:a}=G("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!i9(r.uri)){const{message:a}=G("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}const o=b1(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&H.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(jn.pairing_expired);const{message:a}=G("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),oe(this,"isValidPing",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),oe(this,"isValidDisconnect",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),oe(this,"isValidPairingTopic",async r=>{if(!Be(r,!1)){const{message:i}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(lr(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=G("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=Ot(n,this.name),this.pairings=new ei(this.core,this.logger,this.name,this.storagePrefix)}get context(){return dt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Se.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==ve.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Sl(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):Ea(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(Vt.expired,async e=>{const{topic:n}=L0(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Xr.expire,{topic:n}))})}}var WA=Object.defineProperty,ZA=(t,e,n)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ve=(t,e,n)=>ZA(t,typeof e!="symbol"?e+"":e,n);class YA extends lm{constructor(e,n){super(e,n),this.core=e,this.logger=n,Ve(this,"records",new Map),Ve(this,"events",new rt.exports.EventEmitter),Ve(this,"name",Q7),Ve(this,"version",eO),Ve(this,"cached",[]),Ve(this,"initialized",!1),Ve(this,"storagePrefix",fn),Ve(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)}),Ve(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:Te(H.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(en.created,o)}),Ve(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=jt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(en.updated,i))}),Ve(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))),Ve(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(en.deleted,s)}}),this.persist()}),Ve(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ve(this,"on",(r,i)=>{this.events.on(r,i)}),Ve(this,"once",(r,i)=>{this.events.once(r,i)}),Ve(this,"off",(r,i)=>{this.events.off(r,i)}),Ve(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:Mn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(en.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(en.created,e=>{const n=en.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.updated,e=>{const n=en.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.deleted,e=>{const n=en.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on($r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{H.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(en.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XA=Object.defineProperty,JA=(t,e,n)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nt=(t,e,n)=>JA(t,typeof e!="symbol"?e+"":e,n);class QA extends ym{constructor(e,n){super(e,n),this.core=e,this.logger=n,nt(this,"expirations",new Map),nt(this,"events",new rt.exports.EventEmitter),nt(this,"name",tO),nt(this,"version",nO),nt(this,"cached",[]),nt(this,"initialized",!1),nt(this,"storagePrefix",fn),nt(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)}),nt(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),nt(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(Vt.created,{target:s,expiration:o})}),nt(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),nt(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(Vt.deleted,{target:i,expiration:s})}}),nt(this,"on",(r,i)=>{this.events.on(r,i)}),nt(this,"once",(r,i)=>{this.events.once(r,i)}),nt(this,"off",(r,i)=>{this.events.off(r,i)}),nt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return P_(e);if(typeof e=="number")return R_(e);const{message:n}=G("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Vt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const n=this.expirations.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;H.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Vt.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on($r.pulse,()=>this.checkExpirations()),this.events.on(Vt.created,e=>{const n=Vt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.expired,e=>{const n=Vt.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.deleted,e=>{const n=Vt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var e$=Object.defineProperty,t$=(t,e,n)=>e in t?e$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ae=(t,e,n)=>t$(t,typeof e!="symbol"?e+"":e,n);class n$ extends bm{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,Ae(this,"name",rO),Ae(this,"abortController"),Ae(this,"isDevEnv"),Ae(this,"verifyUrlV3",sO),Ae(this,"storagePrefix",fn),Ae(this,"version",G1),Ae(this,"publicKey"),Ae(this,"fetchPromise"),Ae(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&H.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ae(this,"register",async i=>{if(!Si()||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 u=Nr(),l=this.startAbortTimer(H.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",m),u.body.removeChild(b),h("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const b=u.createElement("iframe");b.src=c,b.style.display="none",b.addEventListener("error",p,{signal:this.abortController.signal});const m=B=>{if(B.data&&typeof B.data=="string")try{const D=JSON.parse(B.data);if(D.type==="verify_attestation"){if(yc(D.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(b),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",m),d(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};u.body.appendChild(b),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Ae(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(yc(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),Ae(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(H.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}),Ae(this,"getVerifyUrl",i=>{let s=i||Us;return oO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Us}`),s=Us),s}),Ae(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(H.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)}}),Ae(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ae(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ae(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")}}),Ae(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ae(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}),Ae(this,"validateAttestation",(i,s)=>{const o=$S(i,s.publicKey),a={hasExpired:H.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=Ot(n,this.name),this.abortController=new AbortController,this.isDevEnv=Fu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return dt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),H.toMiliseconds(e))}}var r$=Object.defineProperty,i$=(t,e,n)=>e in t?r$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ay=(t,e,n)=>i$(t,typeof e!="symbol"?e+"":e,n);class s$ extends wm{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,Ay(this,"context",aO),Ay(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${cO}/${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=Ot(n,this.context)}}var o$=Object.defineProperty,$y=Object.getOwnPropertySymbols,a$=Object.prototype.hasOwnProperty,c$=Object.prototype.propertyIsEnumerable,Fl=(t,e,n)=>e in t?o$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,js=(t,e)=>{for(var n in e||(e={}))a$.call(e,n)&&Fl(t,n,e[n]);if($y)for(var n of $y(e))c$.call(e,n)&&Fl(t,n,e[n]);return t},Le=(t,e,n)=>Fl(t,typeof e!="symbol"?e+"":e,n);class u$ extends mm{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,Le(this,"context",lO),Le(this,"storagePrefix",fn),Le(this,"storageVersion",uO),Le(this,"events",new Map),Le(this,"shouldPersist",!1),Le(this,"init",async()=>{if(!Fu())try{const i={eventId:q0(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:U0(this.core.relayer.protocol,this.core.relayer.version,Ol)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Le(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=q0(),l=this.core.projectId||"",f=Date.now(),d=js({eventId:u,timestamp:f,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,d),this.shouldPersist=!0),d}),Le(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 js(js({},a),this.setMethods(a.eventId))}),Le(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Le(this,"setEventListeners",()=>{this.core.heartbeat.on($r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{H.fromMiliseconds(Date.now())-H.fromMiliseconds(i.timestamp)>fO&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Le(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Le(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)}),Le(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)}),Le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Le(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,js(js({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Le(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)}}),Le(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${hO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ol}${s}`,{method:"POST",body:JSON.stringify(i)})}),Le(this,"getAppDomain",()=>C0().url),this.logger=Ot(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 l$=Object.defineProperty,Dy=Object.getOwnPropertySymbols,f$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable,Ll=(t,e,n)=>e in t?l$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ty=(t,e)=>{for(var n in e||(e={}))f$.call(e,n)&&Ll(t,n,e[n]);if(Dy)for(var n of Dy(e))h$.call(e,n)&&Ll(t,n,e[n]);return t},me=(t,e,n)=>Ll(t,typeof e!="symbol"?e+"":e,n);class kl extends om{constructor(e){var n;super(e),me(this,"protocol",H1),me(this,"version",G1),me(this,"name",xa),me(this,"relayUrl"),me(this,"projectId"),me(this,"customStoragePrefix"),me(this,"events",new rt.exports.EventEmitter),me(this,"logger"),me(this,"heartbeat"),me(this,"relayer"),me(this,"crypto"),me(this,"storage"),me(this,"history"),me(this,"expirer"),me(this,"pairing"),me(this,"verify"),me(this,"echoClient"),me(this,"linkModeSupportedApps"),me(this,"eventClient"),me(this,"initialized",!1),me(this,"logChunkController"),me(this,"on",(a,c)=>this.events.on(a,c)),me(this,"once",(a,c)=>this.events.once(a,c)),me(this,"off",(a,c)=>this.events.off(a,c)),me(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),me(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ve.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.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=e?.projectId,this.relayUrl=e?.relayUrl||Y1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Qw({level:typeof e?.logger=="string"&&e.logger?e.logger:R7.logger,name:xa}),{logger:s,chunkLoggerController:o}=Ff({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.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=Ot(s,this.name),this.heartbeat=new qa,this.crypto=new qB(this,this.logger,e?.keychain),this.history=new YA(this,this.logger),this.expirer=new QA(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new dw(Ty(Ty({},N7),e?.storageOptions)),this.relayer=new dA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new GA(this,this.logger),this.verify=new n$(this,this.logger,this.storage),this.echoClient=new s$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new u$(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new kl(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(W7,r),n}get context(){return dt(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(X1,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(X1)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,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(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}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 d$=kl,Py="wc",Ry=2,Ny="client",ql=`${Py}@${Ry}:${Ny}:`,Ml={name:Ny,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Cy="WALLETCONNECT_DEEPLINK_CHOICE",p$="proposal",Uy="Proposal expired",g$="session",Li=H.SEVEN_DAYS,y$="engine",Ke={wc_sessionPropose:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1104},res:{ttl:H.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1106},res:{ttl:H.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1112},res:{ttl:H.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1114},res:{ttl:H.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:H.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:H.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1119}}},jl={min:H.FIVE_MINUTES,max:H.SEVEN_DAYS},pn={idle:"IDLE",active:"ACTIVE"},b$={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:""}},w$="request",m$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],v$="wc",E$="auth",x$="authKeys",_$="pairingTopics",I$="requests",Sa=`${v$}@${1.5}:${E$}:`,Oa=`${Sa}:PUB_KEY`;var S$=Object.defineProperty,O$=Object.defineProperties,B$=Object.getOwnPropertyDescriptors,Fy=Object.getOwnPropertySymbols,A$=Object.prototype.hasOwnProperty,$$=Object.prototype.propertyIsEnumerable,zl=(t,e,n)=>e in t?S$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fe=(t,e)=>{for(var n in e||(e={}))A$.call(e,n)&&zl(t,n,e[n]);if(Fy)for(var n of Fy(e))$$.call(e,n)&&zl(t,n,e[n]);return t},He=(t,e)=>O$(t,B$(e)),V=(t,e,n)=>zl(t,typeof e!="symbol"?e+"":e,n);class D$ extends _m{constructor(e){super(e),V(this,"name",y$),V(this,"events",new rt.exports),V(this,"initialized",!1),V(this,"requestQueue",{state:pn.idle,queue:[]}),V(this,"sessionRequestQueue",{state:pn.idle,queue:[]}),V(this,"emittedSessionRequests",new j_({limit:500})),V(this,"requestQueueDelay",H.ONE_SECOND),V(this,"expectedPairingMethodMap",new Map),V(this,"recentlyDeletedMap",new Map),V(this,"recentlyDeletedLimit",200),V(this,"relayMessageCache",[]),V(this,"pendingSessions",new Map),V(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Ke)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay)))}),V(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=He(fe({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=QS(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:f,walletPay:d}=i,h=((r=f?.[0])==null?void 0:r.ttl)||Ke.wc_sessionPropose.req.ttl||H.FIVE_MINUTES;this.validateRequestExpiry(h);let p=s,b,m=!1;try{if(p){const $=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."),m=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),$}if(!p||!m){const{topic:$,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=$,b=j}if(!p){const{message:$}=G("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error($)}const B=await this.client.core.crypto.generateKeyPair(),D=Te(h),_=fe(He(fe(fe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Z1}],proposer:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Pt()}),(f||d)&&{requests:{authentication:f?.map($=>{const{domain:j,chains:M,nonce:E,uri:y,exp:v,nbf:g,type:w,statement:I,requestId:O,resources:S,signatureTypes:A}=$;return{domain:j,chains:M,nonce:E,type:w??"caip122",aud:y,version:"1",iat:new Date().toISOString(),exp:v,nbf:g,statement:I,requestId:O,resources:S,signatureTypes:A}}),walletPay:d}}),x=de("session_connect",_.id),{reject:T,resolve:P,done:C}=zr(h,Uy),U=({id:$})=>{$===_.id&&(this.client.events.off("proposal_expire",U),this.pendingSessions.delete(_.id),this.events.emit(x,{error:{message:Uy,code:0}}))};return this.client.events.on("proposal_expire",U),this.events.once(x,({error:$,session:j})=>{this.client.events.off("proposal_expire",U),$?T($):j&&P(j)}),await this.setProposal(_.id,_),await this.sendProposeSession({proposal:_,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:_.id}}}).catch($=>{throw this.deleteProposal(_.id),$}),{uri:b,approval:C}}),V(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}}),V(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:[tn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Jr.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(Jr.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Jr.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:b,proposer:m,requiredNamespaces:B,optionalNamespaces:D}=p;let _=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:b});_||(_=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:tn.session_approve_started,properties:{topic:b,trace:[tn.session_approve_started,tn.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),T=m.publicKey,P=await this.client.core.crypto.generateSharedKey(x,T),C=He(fe(fe(fe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:x,metadata:this.client.metadata},expiry:Te(Li)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{proposalRequestsResponses:h}),U=ve.relay;_.addTrace(tn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:U,internal:{skipSubscribe:!0}})}catch(j){throw _.setError(Jr.subscribe_session_topic_failure),j}_.addTrace(tn.subscribe_session_topic_success);const $=He(fe({},C),{topic:P,requiredNamespaces:B,optionalNamespaces:D,pairingTopic:b,acknowledged:!1,self:C.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:x,transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(P,$),_.addTrace(tn.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:fe({correlationId:a},this.getTVFApproveParams($))}}),_.addTrace(tn.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(P,xe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),j}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:b,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:b}),await this.setExpiry(P,Te(Li)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),V(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:Ke.wc_sessionPropose.reject}),await this.deleteProposal(r)}),V(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=zr(H.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Pt(),u=Sr().toString(),l=this.client.session.get(r).namespaces;return this.events.once(de("session_update",c),({error:f})=>{f?a(f):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:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:l}),a(f)}),{acknowledged:s}}),V(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=Pt(),{done:s,resolve:o,reject:a}=zr(H.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(de("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Te(Li)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),V(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:r,request:i,topic:s,expiry:o=Ke.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const c=Pt(),u=Sr().toString(),{done:l,resolve:f,reject:d}=zr(o,"Request expired. Please try again.");this.events.once(de("session_request",c),({error:m,result:B})=>{m?d(m):f(B)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const b={request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:b,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,b)}).catch(B=>d(B)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),m()}),new Promise(async m=>{var B;if(!((B=a.sessionConfig)!=null&&B.disableDeepLink)){const D=await F_(this.client.core.storage,Cy);await N_({id:c,topic:s,wcDeepLink:D})}m()}),l()]).then(m=>m[2])}),V(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:[tn.session_request_response_started]}});try{await this.isValidRespond(n)}catch(f){throw s.addTrace(f?.message),s.setError(Jr.session_request_response_validation_failure),f}s.addTrace(tn.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,u=this.client.session.get(o);u.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(tn.session_request_response_publish_started),ln(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):jt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(n)}catch(f){throw s.addTrace(f?.message),s.setError(Jr.session_request_response_publish_failure),f}}),V(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=Pt(),s=Sr().toString(),{done:o,resolve:a,reject:c}=zr(H.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(de("session_ping",i),({error:u})=>{u?c(u):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}))}),V(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=Sr().toString(),a=Pt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),V(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:xe("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}=G("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),V(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>n9(r,n)))),V(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),V(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?ve.link_mode:ve.relay;o===ve.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:d,exp:h,nbf:p,methods:b=[],expiry:m}=n,B=[...n.resources||[]],{topic:D,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:_}});const x=await this.client.core.crypto.generateKeyPair(),T=ba(x);if(await Promise.all([this.client.auth.authKeys.set(Oa,{responseTopic:T,publicKey:x}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:D})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${D}`),b.length>0){const{namespace:S}=Pn(a[0]);let A=eI(S,"request",b);sa(B)&&(A=nI(A,B.pop())),B.push(A)}const P=m&&m>Ke.wc_sessionAuthenticate.req.ttl?m:Ke.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:B},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:Te(P)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...b])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:Te(Ke.wc_sessionPropose.req.ttl),id:Pt()},{done:j,resolve:M,reject:E}=zr(P,"Request expired"),y=Pt(),v=de("session_connect",$.id),g=de("session_request",y),w=async({error:S,session:A})=>{this.events.off(g,I),S?E(S):A&&M({session:A})},I=async S=>{var A,R,L;if(await this.deletePendingAuthRequest(y,{message:"fulfilled",code:0}),S.error){const K=xe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===K.code?void 0:(this.events.off(v,w),E(S.error.message))}await this.deleteProposal($.id),this.events.off(v,w);const{cacaos:F,responder:k}=S.result,N=[],q=[];for(const K of F){await hg({cacao:K,projectId:this.client.core.projectId})||(this.client.logger.error(K,"Signature verification failed"),E(xe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Z}=K,Q=sa(Z.resources),ee=[Ku(Z.iss)],se=ia(Z.iss);if(Q){const he=gg(Q),Ee=yg(Q);N.push(...he),ee.push(...Ee)}for(const he of ee)q.push(`${he}:${se}`)}const z=await this.client.core.crypto.generateSharedKey(x,k.publicKey);let W;N.length>0&&(W={topic:z,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:k,controller:k.publicKey,expiry:Te(Li),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:I1([...new Set(N)],[...new Set(q)]),transportType:o},await this.client.core.relayer.subscribe(z,{transportType:o}),await this.client.session.set(z,W),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:k.metadata}),W=this.client.session.get(z)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(R=k.metadata.redirect)!=null&&R.linkMode&&(L=k.metadata.redirect)!=null&&L.universal&&r&&(this.client.core.addLinkModeSupportedApp(k.metadata.redirect.universal),this.client.session.update(z,{transportType:ve.link_mode})),M({auths:F,session:W})};this.events.once(v,w),this.events.once(g,I);let O;try{if(s){const S=Mn("wc_sessionAuthenticate",C,y);this.client.core.history.set(D,S);const A=await this.client.core.crypto.encode("",S,{type:Bs,encoding:Ir});O=ma(r,D,A)}else await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:C,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:y}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:$,expiry:Ke.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(S){throw this.events.off(v,w),this.events.off(g,I),S}return await this.setProposal($.id,$),await this.setAuthRequest(y,{request:He(fe({},C),{verifyContext:{}}),pairingTopic:D,transportType:o}),{uri:O??_,response:j}}),V(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Qr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw s.setError(Fs.no_internet_connection),m}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Fs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ve.relay;a===ve.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ba(c),f={type:Ln,receiverPublicKey:c,senderPublicKey:u},d=[],h=[];for(const m of i){if(!await hg({cacao:m,projectId:this.client.core.projectId})){s.setError(Fs.invalid_cacao);const T=xe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:T,encodeOpts:f}),new Error(T.message)}s.addTrace(Qr.cacaos_verified);const{p:B}=m,D=sa(B.resources),_=[Ku(B.iss)],x=ia(B.iss);if(D){const T=gg(D),P=yg(D);d.push(...T),_.push(...P)}for(const T of _)h.push(`${T}:${x}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Qr.create_authenticated_session_topic);let b;if(d?.length>0){b={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Te(Li),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:I1([...new Set(d)],[...new Set(h)]),transportType:a},s.addTrace(Qr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(m){throw s.setError(Fs.subscribe_authenticated_session_topic_failure),m}s.addTrace(Qr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,b),s.addTrace(Qr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Qr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw s.setError(Fs.authenticated_session_approve_publish_failure),m}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:b}}),V(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===ve.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ba(o),u={type:Ln,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Ke.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)}),V(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return dg(r,i)}),V(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)}),V(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)}}),V(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,xe("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(Cy).catch(u=>this.client.logger.warn(u)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=pn.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===i).map(u=>this.deletePendingSessionRequest(u.id,xe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),V(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(Jr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,xe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),V(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=pn.idle,this.client.events.emit("session_request_expire",{id:n}))}),V(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)])}),V(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}))}),V(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,Te(Ke.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),V(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=ve.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})}),V(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||Te(Ke.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})}),V(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:d={}}=n,h=Mn(i,s,c);let p;const b=!!l;try{const D=b?Ir:xt;p=await this.client.core.crypto.encode(r,h,{encoding:D})}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),D}let m;if(m$.includes(i)){const D=Mt(JSON.stringify(h)),_=Mt(p);m=await this.client.core.verify.register({id:_,decryptedId:D})}const B=fe(fe({},Ke[i].req),d);if(B.attestation=m,o&&(B.ttl=o),a&&(B.id=a),this.client.core.history.set(r,h),b){const D=ma(l,r,p);await global.Linking.openURL(D,this.client.name)}else B.tvf=He(fe({},f),{correlationId:h.id}),u?(B.internal=He(fe({},B.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,B)):this.client.core.relayer.publish(r,p,B).catch(D=>this.client.logger.error(D));return h.id}),V(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=Mn("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:xt}),a=Mt(JSON.stringify(s)),c=Mt(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:He(fe({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),V(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=va(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:xt}),l=Mn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:xt});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:He(fe({},a),{publishMethod:"wc_approveSession"})})}),V(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=va(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?Ir:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let d,h;try{d=await this.client.core.history.get(i,r);const p=d.request;try{h=this.getTVFParams(r,p.params,s)}catch(b){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${b?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(f){const p=ma(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,b=Ke[p].res;b.tvf=He(fe({},h),{correlationId:r}),o?(b.internal=He(fe({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,b)):this.client.core.relayer.publish(i,l,b).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(u)}),V(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=Il(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?Ir:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),h}let d;try{d=await this.client.core.history.get(i,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),h}if(f){const h=ma(c,i,l);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||Ke[h].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),V(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;lr(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=>{lr(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),V(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),V(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),V(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===pn.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=pn.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=pn.idle}),V(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}`)}}),V(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}`)}}),V(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=G("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),V(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)}),V(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(jn.proposal_listener_not_found)),this.isValidConnect(fe({},i.params));const l=a.expiryTimestamp||Te(Ke.wc_sessionPropose.req.ttl),f=fe({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:s,hash:Mt(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(hn.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Ke.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),V(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(ln(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 u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:n,proposalId:s,publicKey:c});const f=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:n})}else if(jt(r)){await this.deleteProposal(s);const o=de("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})}}),V(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=r.params,p=[...this.pendingSessions.values()].find(B=>B.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const b=this.client.proposal.get(p.proposalId),m=He(fe(fe(fe({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(de("session_connect",p.proposalId),{session:m})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;ln(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(de("session_approve",i),{})):jt(r)&&(await this.client.session.delete(n,xe("USER_DISCONNECTED")),this.events.emit(de("session_approve",i),{error:r.error}))}),V(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=Ps.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:xe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fe({topic:n},i));try{Ps.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw Ps.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)}}),V(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),V(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=de("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_update",i),{}):jt(r)&&this.events.emit(de("session_update",i),{error:r.error})}),V(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,Te(Li)),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)}}),V(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=de("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_extend",i),{}):jt(r)&&this.events.emit(de("session_extend",i),{error:r.error})}),V(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)}}),V(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=de("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);ln(r)?this.events.emit(de("session_ping",i),{}):jt(r)&&this.events.emit(de("session_ping",i),{error:r.error})},500)}),V(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:xe("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),V(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:d}=a;try{await this.isValidRequest(fe({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Mt(JSON.stringify(Mn("wc_sessionRequest",d,f))),encryptedId:u,metadata:h.peer.metadata,transportType:l}),b={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(b),l===ve.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=h.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(b):(this.addSessionRequestToSessionRequestQueue(b),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),V(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=de("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=Ps.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(fe({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),Ps.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:f}=s.params,d=await this.getVerifyContext({attestationId:o,hash:Mt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:i,transportType:c}),c===ve.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:Ln,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:h,rpcOpts:Ke.wc_sessionAuthenticate.autoReject,appLink:d})}}),V(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),V(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=pn.idle,this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay))}),V(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(de("session_request",s.request.id),{error:r})})}),V(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===pn.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)}}),V(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=pn.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),V(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:Mn("wc_sessionPropose",He(fe({},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})}),V(this,"isValidConnect",async n=>{if(!_t(n)){const{message:u}=G("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(Re(r)||await this.isValidPairingTopic(r),!p9(c,!0)){const{message:u}=G("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(i&&!Re(i)&&Ds(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!Re(s)&&Ds(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),V(this,"validateNamespaces",(n,r)=>{const i=d9(n,"connect()",r);if(i)throw new Error(i.message)}),V(this,"isValidApprove",async n=>{if(!_t(n))throw new Error(G("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),u=bl(i,"approve()");if(u)throw new Error(u.message);const l=$1(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Be(s,!0)){const{message:f}=G("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),V(this,"isValidReject",async n=>{if(!_t(n)){const{message:s}=G("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!y9(i)){const{message:s}=G("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),V(this,"isValidSessionSettleRequest",n=>{if(!_t(n)){const{message:u}=G("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!B1(r)){const{message:u}=G("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=a9(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=bl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(lr(o)){const{message:u}=G("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),V(this,"isValidUpdate",async n=>{if(!_t(n)){const{message:c}=G("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=bl(i,"update()");if(o)throw new Error(o.message);const a=$1(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),V(this,"isValidExtend",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),V(this,"isValidRequest",async n=>{if(!_t(n)){const{message:c}=G("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(!A1(a,s)){const{message:c}=G("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!b9(i)){const{message:c}=G("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!v9(a,s,i.method)){const{message:c}=G("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),V(this,"isValidRespond",async n=>{var r;if(!_t(n)){const{message:a}=G("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(!w9(s)){const{message:a}=G("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}=G("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),V(this,"isValidPing",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(this,"isValidEmit",async n=>{if(!_t(n)){const{message:a}=G("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(!A1(o,s)){const{message:a}=G("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!m9(i)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!E9(o,s,i.name)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),V(this,"isValidDisconnect",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(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(!Be(i,!1))throw new Error("uri is required parameter");if(!Be(s,!1))throw new Error("domain is required parameter");if(!Be(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Pn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Pn(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),V(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Us,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ve.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),V(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=G("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),V(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),V(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)}}}),V(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),V(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,d;return!n||r!==ve.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&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=n?.redirect)==null?void 0:l.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),V(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),V(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=k0(n,"topic")||"",i=decodeURIComponent(k0(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:ve.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),V(this,"registerLinkModeListeners",async()=>{var n;if(Fu()||ur()&&(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)}}}),V(this,"getTVFApproveParams",n=>{try{const r=E1(n.namespaces),i=GS(n.namespaces),s=WS(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"),{}}}),V(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 u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),V(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}),V(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=b$[s];if(s==="sui_signTransaction")return[C5(r.transactionBytes)];if(s==="near_signTransaction")return[ag(r)];if(s==="near_signTransactions")return r.map(c=>ag(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[k9({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Ci(r)?r.map(c=>cg(c)):[cg(r)];if(s==="cosmos_signDirect")return[F5(r)];if(s==="wallet_sendCalls")return L5(r);if(typeof r=="string")return[r];const a=r[o.key];if(Ci(a))return s==="solana_signAllTransactions"?a.map(c=>N5(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 e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);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(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Se.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Oa)?this.client.auth.authKeys.get(Oa):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===ve.link_mode?Ir:xt});Sl(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Mt(r)})):Ea(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(Vt.expired,async e=>{const{topic:n,id:r}=L0(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,G("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,G("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(Xr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Be(e,!1)){const{message:n}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=G("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!Be(e,!1)){const{message:n}=G("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=G("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=G("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Be(e,!1)){const{message:n}=G("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=G("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!g9(e)){const{message:n}=G("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=G("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}validateRequestExpiry(e){if(e&&!I9(e,jl)){const{message:n}=G("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${jl.min} and ${jl.max}`);throw new Error(n)}}}class T$ extends ei{constructor(e,n){super(e,n,p$,ql),this.core=e,this.logger=n}}class P$ extends ei{constructor(e,n){super(e,n,g$,ql),this.core=e,this.logger=n}}class R$ extends ei{constructor(e,n){super(e,n,w$,ql,r=>r.id),this.core=e,this.logger=n}}class N$ extends ei{constructor(e,n){super(e,n,x$,Sa,()=>Oa),this.core=e,this.logger=n}}class C$ extends ei{constructor(e,n){super(e,n,_$,Sa),this.core=e,this.logger=n}}class U$ extends ei{constructor(e,n){super(e,n,I$,Sa,r=>r.id),this.core=e,this.logger=n}}var F$=Object.defineProperty,L$=(t,e,n)=>e in t?F$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vl=(t,e,n)=>L$(t,typeof e!="symbol"?e+"":e,n);class k${constructor(e,n){this.core=e,this.logger=n,Vl(this,"authKeys"),Vl(this,"pairingTopics"),Vl(this,"requests"),this.authKeys=new N$(this.core,this.logger),this.pairingTopics=new C$(this.core,this.logger),this.requests=new U$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var q$=Object.defineProperty,M$=(t,e,n)=>e in t?q$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ae=(t,e,n)=>M$(t,typeof e!="symbol"?e+"":e,n);class Kl extends xm{constructor(e){super(e),ae(this,"protocol",Py),ae(this,"version",Ry),ae(this,"name",Ml.name),ae(this,"metadata"),ae(this,"core"),ae(this,"logger"),ae(this,"events",new rt.exports.EventEmitter),ae(this,"engine"),ae(this,"session"),ae(this,"proposal"),ae(this,"pendingRequest"),ae(this,"auth"),ae(this,"signConfig"),ae(this,"on",(r,i)=>this.events.on(r,i)),ae(this,"once",(r,i)=>this.events.once(r,i)),ae(this,"off",(r,i)=>this.events.off(r,i)),ae(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),ae(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),ae(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),ae(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),ae(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ml.name,this.metadata=A_(e?.metadata),this.signConfig=e?.signConfig;const n=P1({logger:e?.logger||Ml.logger,name:this.name});this.logger=n,this.core=e?.core||new d$(e),this.session=new P$(this.core,this.logger),this.proposal=new T$(this.core,this.logger),this.pendingRequest=new R$(this.core,this.logger),this.engine=new D$(this),this.auth=new k$(this.core,this.logger)}static async init(e){const n=new Kl(e);return await n.initialize(),n}get context(){return dt(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const j$=Kl;class Ly{constructor(e){this.opts=e}}class ky{constructor(e){this.client=e}}const qy=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Ts(r?.chainId))return!1;const{namespace:a}=Pn(r.chainId),c=e.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(u=>u.toLowerCase()).includes(s?.toLowerCase()))throw new Error(`Unsupported token standard: ${s} for namespace: ${a}`);return!0},z$=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!qy({supportedNamespaces:e,token:r}))},My=t=>{let e,n;return async()=>e!==void 0?e:n||(n=t(),e=await n,e)};var V$=Object.defineProperty,K$=(t,e,n)=>e in t?V$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,le=(t,e,n)=>K$(t,typeof e!="symbol"?e+"":e,n);class H$ extends ky{constructor(e){var n;super(e),le(this,"signClient"),le(this,"logger"),le(this,"tokens",[]),le(this,"supportedNamespaces",cf),le(this,"paymentIntents",{}),le(this,"transactions",{}),le(this,"paymentsSendingInProgress",{}),le(this,"manualControl",{}),le(this,"init",async()=>{var r,i;this.signClient=await j$.init({projectId:this.client.opts.projectId,metadata:{name:this.client.metadata.merchantName,description:this.client.metadata.description,url:this.client.metadata.url,icons:[this.client.metadata.logoIcon]},storageOptions:{database:((r=this.client.opts.storageOptions)==null?void 0:r.databaseName)||Da.database},customStoragePrefix:Da.customStoragePrefix,logger:((i=this.client.opts.loggerOptions)==null?void 0:i.signLevel)||Ta}),this.signClient.events.on("session_delete",({topic:s})=>{this.cleanup({sessionTopic:s}),this.emit("disconnected",{sessionTopic:s})});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest({payload:JSON.stringify({id:Pt(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:s.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error(s,"Failed to fetch supported namespaces/networks")}}),le(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug({tokens:i},"Setting tokens"),i.forEach(s=>{if(!qy({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=i,s()}),this.logger.debug({tokens:i},"Tokens set")}),le(this,"createPaymentIntent",async r=>{const{paymentIntents:i,sessionTopic:s,userId:o}=r;this.logger.debug({paymentIntents:i,userId:o},"Creating payment intent");const a=r.manualControl||!1;if(i.length===0)throw new Error("No payment intents provided");for(const d of i)if(!z$({paymentIntent:d,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(d)}`);if(this.logger.debug({paymentIntents:i,userId:o},"Payment intent validation success"),s){this.manualControl[s]=a;try{this.setPaymentIntents({sessionTopic:s,paymentIntents:i,userId:o}),this.validateApprovedNamespacesWithPaymentIntents(s),a||await this.sendPaymentsToWallet({sessionTopic:s,userId:o});return}catch(d){this.logger.error(d),await this.disconnect({sessionTopic:s})}}const c=this.composeNamespacesFromPaymentIntents(i),{uri:u,approval:l}=await this.signClient.connect({optionalNamespaces:c});if(this.logger.debug({uri:u,userId:o},"Connected to the WalletConnect network"),!u)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:o}),new Error("Failed to connect to the WalletConnect network");const f=My(l);if(this.emit("await_approval",{approval:f,paymentIntents:i,userId:o,manualControl:a}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:u,userId:o}),this.logger.debug({uri:u,userId:o},"Emitted qr_ready event"),a){const d=await f();this.manualControl[d.topic]=a}}),le(this,"restart",async r=>{this.logger.debug({params:r},"Restarting");const{reinit:i,sessionTopic:s,userId:o}=r||{};if(i){this.tokens=[],await this.disconnect({sessionTopic:s}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const a=this.getSessionTopic(s),c=this.manualControl[a],u=this.paymentIntents[a];if(!u||!(u!=null&&u.length))throw new Error("No payment intents found for session topic: "+a);await this.createPaymentIntent({paymentIntents:u,manualControl:c,userId:o,sessionTopic:a}),this.logger.debug({paymentIntents:u,userId:o},"Restarted: Created payment intent flow from the beginning")}),le(this,"connect",async r=>{const{userId:i}=r,s=!0,o=this.composeNamespacesFromTokens(),{uri:a,approval:c}=await this.signClient.connect({optionalNamespaces:o});if(this.logger.debug({uri:a},"Connected to the WalletConnect network"),!a)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:i}),new Error("Failed to connect to the WalletConnect network");const u=My(c);this.emit("await_approval",{approval:u,manualControl:s,paymentIntents:[],userId:i}),this.logger.debug({userId:i},"Emitted await_approval event"),this.emit("qr_ready",{uri:a,userId:i}),this.logger.debug({uri:a,userId:i},"Emitted qr_ready event");const l=await u();return this.manualControl[l.topic]=s,l}),le(this,"emit",(r,i)=>(this.logger.debug({event:r,args:i},"Emit"),this.client.events.emit(r,i))),le(this,"on",(r,i)=>(this.logger.debug({event:r,listener:i},"On"),this.client.events.on(r,i))),le(this,"once",(r,i)=>(this.logger.debug({event:r,listener:i},"Once"),this.client.events.once(r,i))),le(this,"off",(r,i)=>(this.logger.debug({event:r,listener:i},"Off"),this.client.events.off(r,i))),le(this,"removeListener",(r,i)=>(this.logger.debug({event:r,listener:i},"Remove listener"),this.client.events.removeListener(r,i))),le(this,"prepareTransactionsFromPaymentIntents",async r=>{var i,s,o,a,c,u;const{sessionTopic:l,userId:f}=r,d=this.getSessionTopic(l),h=this.paymentIntents[d];if(!h)throw new Error("No payment intents found for session topic: "+d);const p=this.signClient.session.get(d);this.logger.debug({sessionTopic:d,userId:f},"Preparing transactions from payment intents");const b=[];for(const D of h){const{token:_,amount:x,recipient:T}=D,{namespace:P}=Pn(_.network.chainId),C=(o=(s=(i=p.namespaces)==null?void 0:i[P])==null?void 0:s.accounts)==null?void 0:o.find(U=>U.includes(`${_.network.chainId}:`));if(!C)throw new Error(`Address not found in session for chain id: ${_.network.chainId}, approved addresses: ${(u=(c=(a=p.namespaces)==null?void 0:a[P])==null?void 0:c.accounts)==null?void 0:u.join(", ")}`);b.push({asset:`${_.network.chainId}/${_.standard.toLowerCase()}:${_.address}`,recipient:T,amount:x,sender:C})}this.logger.debug({sessionTopic:p.topic,transactions:b,userId:f},"Prepared transactions from payment intents");const m={id:Pt(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:b}};this.logger.debug({payload:m,userId:f},"Fetching wc_pos_buildTransactions");const B=await this.fetchRpcRequest({payload:JSON.stringify(m),userId:f});this.logger.debug({response:B,userId:f},"Received wc_pos_buildTransactions"),this.transactions[p.topic]=B.result.transactions,this.logger.debug({transactions:this.transactions[p.topic],userId:f},"Payment intent to transactions map set")}),le(this,"sendPaymentsToWallet",async(r={})=>{const{sessionTopic:i,userId:s}=r,o=this.getSessionTopic(i);if(!o)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[o])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[o]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:o,userId:s}),await this.sendTransactionsToWallet({sessionTopic:o,userId:s})}catch(a){throw this.logger.error(a,"Error while sending payments to wallet"),this.paymentsSendingInProgress[o]=!1,a}this.paymentsSendingInProgress[o]=!1}),le(this,"sendTransactionsToWallet",async r=>{const{sessionTopic:i,userId:s}=r,o=this.transactions[i],a=this.paymentIntents[i];if(!o||!a)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(o.length!==a.length)throw new Error(`Mismatch between transactions (${o.length}) and payment intents (${a.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:o,sessionTopic:i,userId:s},"Sending transactions to wallet");for(let c=0;c<o.length;c++){const u=o[c],l=a[c];try{this.emit("payment_requested",{paymentIntent:l,transaction:u,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_requested event");let f;try{f=await this.signClient.request({topic:i,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug({transactionId:u.id,result:f,userId:s},"Wallet responded to payment request")}catch(d){throw this.logger.error(d,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:d?.message,code:4001},paymentIntent:l,sessionTopic:i,userId:s}),d}this.emit("payment_broadcasted",{paymentIntent:l,transaction:u,result:f,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:u,result:f,sessionTopic:i,userId:s}),await new Promise(d=>setTimeout(d,1e3))}catch(f){this.logger.error(f,"Error while awaiting payment confirmed")}}this.manualControl[i]!==!0&&await this.disconnect({sessionTopic:i})}),le(this,"awaitPaymentConfirmed",async r=>{const{transaction:i,result:s,sessionTopic:o,userId:a}=r;try{this.logger.debug({transactionId:i.id,result:s},"Awaiting payment confirmed");const c={id:Pt(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let u=0,l;for(;!l;){if(u>=af)throw new Error(`Transaction status not found for id: ${i.id}`);u++;const f=await this.fetchRpcRequest({payload:JSON.stringify(c),userId:a});if(this.logger.debug({transactionId:i.id,response:f},"Received wc_pos_checkTransaction"),f.result.status==="CONFIRMED"){this.logger.debug({response:f,userId:a},"Transaction status confirmed"),this.emit("payment_successful",{transaction:i,result:s,sessionTopic:o,userId:a}),l=f.result;break}else if(f.result.status==="FAILED"){this.logger.debug({response:f},"Transaction failed"),this.emit("payment_failed",{error:{message:f.result.error,code:4001},transaction:s,sessionTopic:o,userId:a}),l=f.result;break}else f.result.status==="PENDING"&&(this.logger.debug({response:f,userId:a},"Transaction pending"),await new Promise(d=>setTimeout(d,f.result.checkIn||1e3)))}}catch(c){this.logger.error(c,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:c?.message,code:4001},transaction:i,sessionTopic:o,userId:a})}}),le(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,paymentIntents:i,userId:s,manualControl:o})=>{try{this.logger.debug("On await_approval");const a=await r();this.setPaymentIntents({sessionTopic:a.topic,paymentIntents:i}),await this.onSessionConnected({session:a,userId:s,manualControl:o})}catch(a){this.logger.error(a,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:a?.message,code:4001},userId:s})}})}),le(this,"onSessionConnected",async r=>{const{session:i,userId:s,manualControl:o}=r;this.logger.debug({sessionTopic:i.topic,userId:s},"On session connected"),this.emit("connected",{session:i,userId:s}),await this.signClient.session.update(i.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:i.topic,userId:s},"Disabled deep links for session"),this.logger.debug({sessionTopic:i.topic,userId:s},"Emitted connected event"),o!==!0&&await this.sendPaymentsToWallet({sessionTopic:i.topic,userId:s})}),le(this,"disconnect",async(r={})=>{try{const{sessionTopic:i}=r,s=this.getSessionTopic(i);if(!s)return;this.cleanup({sessionTopic:s}),await this.signClient.disconnect({topic:s,reason:{code:4001,message:"User disconnected"}})}catch(i){this.logger.error(i,"Error while disconnecting")}}),le(this,"fetchRpcRequest",async r=>{var i,s,o,a,c,u;const{payload:l,userId:f}=r;this.logger.debug({url:this.getRpcUrl(),payload:l,userId:f},"Fetching RPC request");const d=await fetch(this.getRpcUrl(),{method:"POST",body:l});let h;try{h=await d.json()}catch(p){this.logger.error(p,"Error while getting json data from RPC response")}if(this.logger.debug({data:h},"Received RPC request response"),!d.ok||!h||h!=null&&h.error){const p=((i=h?.error)==null?void 0:i.code)||-18900,b=(s=Pa)!=null&&s[p]?`${(o=Pa)==null?void 0:o[p]}: ${(a=h?.error)==null?void 0:a.message}`:((c=h?.error)==null?void 0:c.message)||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:b,code:p},transaction:"",sessionTopic:((u=this.client.session)==null?void 0:u.topic)||"",userId:f}),new Error(b)}return h}),le(this,"validateApprovedNamespacesWithPaymentIntents",r=>{var i,s,o,a,c,u,l;this.validateSessionTopic(r);const f=this.signClient.session.get(r),d=(i=this.paymentIntents)==null?void 0:i[r];if(!f||!d)throw new Error("No session or payment intents found");for(const h of d){const{token:p}=h,{namespace:b}=Pn(p.network.chainId);if(!((a=(o=(s=f.namespaces)==null?void 0:s[b])==null?void 0:o.accounts)!=null&&a.find(m=>m.includes(`${p.network.chainId}:`))))throw new Error(`Address not found in session for chain id: ${p.network.chainId}, approved addresses: ${(l=(u=(c=f.namespaces)==null?void 0:c[b])==null?void 0:u.accounts)==null?void 0:l.join(", ")}`)}}),le(this,"setPaymentIntents",r=>{const{sessionTopic:i,paymentIntents:s,userId:o}=r;this.paymentIntents[i]=s,this.logger.debug({paymentIntents:s,userId:o},"Payment intents set")}),le(this,"cleanup",(r={})=>{const{sessionTopic:i}=r;i&&(delete this.paymentIntents[i],delete this.transactions[i],delete this.manualControl[i],delete this.paymentsSendingInProgress[i],this.logger.debug({sessionTopic:i},"Cleaned up payment intents and transactions"))}),le(this,"getRpcUrl",()=>uf({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId})),le(this,"validateSessionTopic",r=>{if(r)try{this.signClient.session.get(r)}catch(i){throw this.logger.error(i,`No session found for topic: ${r}`),new Error(`No session found for topic: ${r}`)}}),le(this,"getSessionTopic",r=>{var i;if(!r&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const s=r||((i=this.client.session)==null?void 0:i.topic);if(!s)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(s),s}),this.signClient={},this.logger=Pw({name:this.client.name,level:((n=this.client.opts.loggerOptions)==null?void 0:n.posLevel)||Ta}),this.setupEventHandlers()}composeNamespacesFromTokens(){const e=this.tokens;if(this.logger.debug({tokens:e},"Composing namespaces from tokens"),e.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const n={};return e.forEach(r=>{var i;const{network:s}=r,{namespace:o}=Pn(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}composeNamespacesFromPaymentIntents(e){this.logger.debug({paymentIntents:e},"Composing namespaces");const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=Pn(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}}var G$=Object.defineProperty,W$=(t,e,n)=>e in t?G$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,St=(t,e,n)=>W$(t,typeof e!="symbol"?e+"":e,n);class Ba extends Ly{constructor(e){super(e),St(this,"name"),St(this,"events",new rt.exports),St(this,"engine"),St(this,"metadata"),St(this,"on",(n,r)=>this.engine.on(n,r)),St(this,"once",(n,r)=>this.engine.once(n,r)),St(this,"off",(n,r)=>this.engine.off(n,r)),St(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),St(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"sendPaymentsToWallet",async n=>{try{return await this.engine.sendPaymentsToWallet(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=$a,this.engine=new H$(this)}static async init(e){const n=new Ba(e);return await n.initialize(),n}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(e.message),e}}}const Z$=Ba;Oe.CLIENT_CONTEXT=$a,Oe.CLIENT_STORAGE_OPTIONS=Da,Oe.CLIENT_STORAGE_PREFIX=nb,Oe.DEFAULT_LOGGER_LEVEL=Ta,Oe.DEFAULT_NAMESPACES=cf,Oe.IPOSClient=Ly,Oe.IPOSClientEngine=ky,Oe.MAX_TRANSACTION_STATUS_CHECKS=af,Oe.POSClient=Z$,Oe.POS_CLIENT_VERSION=of,Oe.PROTOCOL=sf,Oe.PROTOCOL_VERSION=tb,Oe.RPC_ERROR_CODES=Pa,Oe.RPC_URL=uf,Oe.default=Ba,Object.defineProperty(Oe,"__esModule",{value:!0})});
40
+ ***************************************************************************** */var El=function(t,e){return El=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])},El(t,e)};function W9(t,e){El(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var xl=function(){return xl=Object.assign||function(e){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)&&(e[s]=n[s])}return e},xl.apply(this,arguments)};function Z9(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function Y9(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function X9(t,e){return function(n,r){e(n,r,t)}}function J9(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Q9(t,e,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(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function e7(t,e){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(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function t7(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function n7(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function _l(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function F1(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >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 r7(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F1(arguments[e]));return t}function i7(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ns(t){return this instanceof Ns?(this.v=t,this):new Ns(t)}function s7(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){r[d]&&(i[d]=function(h){return new Promise(function(p,b){s.push([d,h,p,b])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Ns?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function o7(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Ns(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function a7(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof _l=="function"?_l(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function c7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function u7(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function l7(t){return t&&t.__esModule?t:{default:t}}function f7(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h7(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var d7=Object.freeze({__proto__:null,__extends:W9,get __assign(){return xl},__rest:Z9,__decorate:Y9,__param:X9,__metadata:J9,__awaiter:Q9,__generator:e7,__createBinding:t7,__exportStar:n7,__values:_l,__read:F1,__spread:r7,__spreadArrays:i7,__await:Ns,__asyncGenerator:s7,__asyncDelegator:o7,__asyncValues:a7,__makeTemplateObject:c7,__importStar:u7,__importDefault:l7,__classPrivateFieldGet:f7,__classPrivateFieldSet:h7}),p7=Gl(d7),kn={},L1;function g7(){if(L1)return kn;L1=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.isBrowserCryptoAvailable=kn.getSubtleCrypto=kn.getBrowerCrypto=void 0;function t(){return nn?.crypto||nn?.msCrypto||{}}kn.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}kn.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return kn.isBrowserCryptoAvailable=n,kn}var qn={},k1;function y7(){if(k1)return qn;k1=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function n(){return!t()&&!e()}return qn.isBrowser=n,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=p7;e.__exportStar(g7(),t),e.__exportStar(y7(),t)})(U1);function Pt(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Sr(t=6){return BigInt(Pt(t))}function Mn(t,e,n){return{id:n||Pt(),jsonrpc:"2.0",method:t,params:e}}function va(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Il(t,e,n){return{id:t,jsonrpc:"2.0",error:b7(e,n)}}function b7(t,e){return typeof t>"u"?C1(R1):(typeof t=="string"&&(t=Object.assign(Object.assign({},C1(vl)),{message:t})),typeof e<"u"&&(t.data=e),K9(t.code)&&(t=H9(t.code)),t)}class w7{}class m7 extends w7{constructor(){super()}}class v7 extends m7{constructor(e){super()}}const E7="^wss?:";function x7(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function _7(t,e){const n=x7(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function q1(t){return _7(t,E7)}function I7(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function M1(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Sl(t){return M1(t)&&"method"in t}function Ea(t){return M1(t)&&(ln(t)||jt(t))}function ln(t){return"result"in t}function jt(t){return"error"in t}class S7 extends v7{constructor(e){super(e),this.events=new rt.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(Mn(e.method,e.params||[],e.id||Sr().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{jt(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Ea(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const O7=()=>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"),B7=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",j1=t=>t.split("?")[0],z1=10,A7=O7();class $7{constructor(e){if(this.url=e,this.events=new rt.exports.EventEmitter,this.registering=!1,!q1(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(zi(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!q1(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);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=e,this.registering=!0,new Promise((n,r)=>{const i=U1.isReactNative()?void 0:{rejectUnauthorized:!I7(e)},s=new A7(e,[],i);B7()?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(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?ri(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=Il(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return G9(e,j1(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>z1&&this.events.setMaxListeners(z1)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${j1(this.url)}`));return this.events.emit("register_error",n),n}}var D7=Object.defineProperty,V1=Object.getOwnPropertySymbols,T7=Object.prototype.hasOwnProperty,P7=Object.prototype.propertyIsEnumerable,K1=(t,e,n)=>e in t?D7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ft=(t,e)=>{for(var n in e||(e={}))T7.call(e,n)&&K1(t,n,e[n]);if(V1)for(var n of V1(e))P7.call(e,n)&&K1(t,n,e[n]);return t};const H1="wc",G1=2,xa="core",fn=`${H1}@2:${xa}:`,R7={name:xa,logger:"error"},N7={database:":memory:"},C7="crypto",W1="client_ed25519_seed",U7=H.ONE_DAY,F7="keychain",L7="0.3",k7="messages",q7="0.3",M7=H.SIX_HOURS,j7="publisher",Z1="irn",z7="error",Y1="wss://relay.walletconnect.org",V7="relayer",Se={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"},K7="_subscription",zt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},H7=.1,Ol="2.23.6",ve={link_mode:"link_mode",relay:"relay"},_a={inbound:"inbound",outbound:"outbound"},G7="0.3",W7="WALLETCONNECT_CLIENT_ID",X1="WALLETCONNECT_LINK_MODE_APPS",Rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Z7="subscription",Y7="0.3",X7="pairing",J7="0.3",Cs={wc_pairingDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:H.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:H.ONE_DAY,prompt:!1,tag:0},res:{ttl:H.ONE_DAY,prompt:!1,tag:0}}},Xr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},en={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Q7="history",eO="0.3",tO="expirer",Vt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},nO="0.3",rO="verify-api",iO="https://verify.walletconnect.com",J1="https://verify.walletconnect.org",Us=J1,sO=`${Us}/v3`,oO=[iO,J1],aO="echo",cO="https://echo.walletconnect.com",hn={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"},jn={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"},tn={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"},Jr={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"},Qr={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"},Fs={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},uO=.1,lO="event-client",fO=86400,hO="https://pulse.walletconnect.org/batch";function dO(t,e){if(t.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<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,m=0,B=0,D=p.length;B!==D&&p[B]===0;)B++,b++;for(var _=(D-B)*l+1>>>0,x=new Uint8Array(_);B!==D;){for(var T=p[B],P=0,C=_-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*x[C]>>>0,x[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=_-m;U!==_&&x[U]===0;)U++;for(var $=c.repeat(b);U<_;++U)$+=t.charAt(x[U]);return $}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var m=0,B=0;p[b]===c;)m++,b++;for(var D=(p.length-b)*u+1>>>0,_=new Uint8Array(D);p[b];){var x=n[p.charCodeAt(b)];if(x===255)return;for(var T=0,P=D-1;(x!==0||T<B)&&P!==-1;P--,T++)x+=a*_[P]>>>0,_[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");B=T,b++}if(p[b]!==" "){for(var C=D-B;C!==D&&_[C]===0;)C++;for(var U=new Uint8Array(m+(D-C)),$=m;C!==D;)U[$++]=_[C++];return U}}}function h(p){var b=d(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var pO=dO,gO=pO;const Q1=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},yO=t=>new TextEncoder().encode(t),bO=t=>new TextDecoder().decode(t);class wO{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class mO{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ey(this,e)}}class vO{constructor(e){this.decoders=e}or(e){return ey(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ey=(t,e)=>new vO(ft(ft({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class EO{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new wO(e,n,r),this.decoder=new mO(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ia=({name:t,prefix:e,encode:n,decode:r})=>new EO(t,e,n,r),Ls=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=gO(n,e);return Ia({prefix:t,name:e,encode:r,decode:s=>Q1(i(s))})},xO=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},_O=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},ze=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ia({prefix:e,name:t,encode(i){return _O(i,r,n)},decode(i){return xO(i,r,n,t)}}),IO=Ia({prefix:"\0",name:"identity",encode:t=>bO(t),decode:t=>yO(t)});var SO=Object.freeze({__proto__:null,identity:IO});const OO=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var BO=Object.freeze({__proto__:null,base2:OO});const AO=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $O=Object.freeze({__proto__:null,base8:AO});const DO=Ls({prefix:"9",name:"base10",alphabet:"0123456789"});var TO=Object.freeze({__proto__:null,base10:DO});const PO=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),RO=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var NO=Object.freeze({__proto__:null,base16:PO,base16upper:RO});const CO=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),UO=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),FO=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LO=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kO=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qO=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),MO=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jO=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zO=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var VO=Object.freeze({__proto__:null,base32:CO,base32upper:UO,base32pad:FO,base32padupper:LO,base32hex:kO,base32hexupper:qO,base32hexpad:MO,base32hexpadupper:jO,base32z:zO});const KO=Ls({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),HO=Ls({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var GO=Object.freeze({__proto__:null,base36:KO,base36upper:HO});const WO=Ls({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ZO=Ls({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var YO=Object.freeze({__proto__:null,base58btc:WO,base58flickr:ZO});const XO=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),JO=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QO=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eB=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tB=Object.freeze({__proto__:null,base64:XO,base64pad:JO,base64url:QO,base64urlpad:eB});const ty=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}"),nB=ty.reduce((t,e,n)=>(t[n]=e,t),[]),rB=ty.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function iB(t){return t.reduce((e,n)=>(e+=nB[n],e),"")}function sB(t){const e=[];for(const n of t){const r=rB[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const oB=Ia({prefix:"\u{1F680}",name:"base256emoji",encode:iB,decode:sB});var aB=Object.freeze({__proto__:null,base256emoji:oB}),cB=ry,ny=128,uB=127,lB=~uB,fB=Math.pow(2,31);function ry(t,e,n){e=e||[],n=n||0;for(var r=n;t>=fB;)e[n++]=t&255|ny,t/=128;for(;t&lB;)e[n++]=t&255|ny,t>>>=7;return e[n]=t|0,ry.bytes=n-r+1,e}var hB=Bl,dB=128,iy=127;function Bl(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Bl.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&iy)<<i:(o&iy)*Math.pow(2,i),i+=7}while(o>=dB);return Bl.bytes=s-r,n}var pB=Math.pow(2,7),gB=Math.pow(2,14),yB=Math.pow(2,21),bB=Math.pow(2,28),wB=Math.pow(2,35),mB=Math.pow(2,42),vB=Math.pow(2,49),EB=Math.pow(2,56),xB=Math.pow(2,63),_B=function(t){return t<pB?1:t<gB?2:t<yB?3:t<bB?4:t<wB?5:t<mB?6:t<vB?7:t<EB?8:t<xB?9:10},IB={encode:cB,decode:hB,encodingLength:_B},sy=IB;const oy=(t,e,n=0)=>(sy.encode(t,e,n),e),ay=t=>sy.encodingLength(t),Al=(t,e)=>{const n=e.byteLength,r=ay(t),i=r+ay(n),s=new Uint8Array(i+n);return oy(t,s,0),oy(n,s,r),s.set(e,i),new SB(t,n,e,s)};class SB{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const cy=({name:t,code:e,encode:n})=>new OB(t,e,n);class OB{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Al(this.code,n):n.then(r=>Al(this.code,r))}else throw Error("Unknown type, must be binary type")}}const uy=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),BB=cy({name:"sha2-256",code:18,encode:uy("SHA-256")}),AB=cy({name:"sha2-512",code:19,encode:uy("SHA-512")});var $B=Object.freeze({__proto__:null,sha256:BB,sha512:AB});const ly=0,DB="identity",fy=Q1;var TB=Object.freeze({__proto__:null,identity:{code:ly,name:DB,encode:fy,digest:t=>Al(ly,fy(t))}});new TextEncoder,new TextDecoder;const hy=ft(ft(ft(ft(ft(ft(ft(ft(ft(ft({},SO),BO),$O),TO),NO),VO),GO),YO),tB),aB);ft(ft({},$B),TB);function dy(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function PB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?dy(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function py(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const gy=py("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),$l=py("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=PB(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),RB=ft({utf8:gy,"utf-8":gy,hex:hy.base16,latin1:$l,ascii:$l,binary:$l},hy);function NB(t,e="utf8"){const n=RB[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?dy(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var CB=Object.defineProperty,UB=(t,e,n)=>e in t?CB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>UB(t,typeof e!="symbol"?e+"":e,n);class FB{constructor(e,n){this.core=e,this.logger=n,dn(this,"keychain",new Map),dn(this,"name",F7),dn(this,"version",L7),dn(this,"initialized",!1),dn(this,"storagePrefix",fn),dn(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),dn(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),dn(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),dn(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=G("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),dn(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Cu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var LB=Object.defineProperty,kB=(t,e,n)=>e in t?LB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fe=(t,e,n)=>kB(t,typeof e!="symbol"?e+"":e,n);class qB{constructor(e,n,r){this.core=e,this.logger=n,Fe(this,"name",C7),Fe(this,"keychain"),Fe(this,"randomSessionIdentifier",pl()),Fe(this,"initialized",!1),Fe(this,"clientId"),Fe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Fe(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Fe(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=Rh(i),o=Ph(s.publicKey);return this.clientId=o,o}),Fe(this,"generateKeyPair",()=>{this.isInitialized();const i=ES();return this.setPrivateKey(i.publicKey,i.privateKey)}),Fe(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Rh(s),a=this.randomSessionIdentifier;return await hE(a,i,U7,o)}),Fe(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=xS(a,s);return this.setSymKey(c,o)}),Fe(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ba(i);return await this.keychain.set(o,i),o}),Fe(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"encode",async(i,s,o)=>{this.isInitialized();const a=h1(o),c=zi(s);if(p1(a))return SS(c,o?.encoding);if(d1(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;i=await this.generateSharedKey(d,h)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return _S({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Fe(this,"decode",async(i,s,o)=>{this.isInitialized();const a=BS(s,o);if(p1(a)){const c=OS(s,o?.encoding);return ri(c)}if(d1(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=IS({symKey:c,encoded:s,encoding:o?.encoding});return ri(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Fe(this,"getPayloadType",(i,s=xt)=>{const o=$s({encoded:i,encoding:s});return Yr(o.type)}),Fe(this,"getPayloadSenderPublicKey",(i,s=xt)=>{const o=$s({encoded:i,encoding:s});return o.senderPublicKey?mt(o.senderPublicKey,lt):void 0}),this.core=e,this.logger=Ot(n,this.name),this.keychain=r||new FB(this.core,this.logger)}get context(){return dt(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(W1)}catch{e=pl(),await this.keychain.set(W1,e)}return NB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MB=Object.defineProperty,jB=Object.defineProperties,zB=Object.getOwnPropertyDescriptors,yy=Object.getOwnPropertySymbols,VB=Object.prototype.hasOwnProperty,KB=Object.prototype.propertyIsEnumerable,Dl=(t,e,n)=>e in t?MB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,HB=(t,e)=>{for(var n in e||(e={}))VB.call(e,n)&&Dl(t,n,e[n]);if(yy)for(var n of yy(e))KB.call(e,n)&&Dl(t,n,e[n]);return t},GB=(t,e)=>jB(t,zB(e)),Nt=(t,e,n)=>Dl(t,typeof e!="symbol"?e+"":e,n);class WB extends fm{constructor(e,n){super(e,n),this.logger=e,this.core=n,Nt(this,"messages",new Map),Nt(this,"messagesWithoutClientAck",new Map),Nt(this,"name",k7),Nt(this,"version",q7),Nt(this,"initialized",!1),Nt(this,"storagePrefix",fn),Nt(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}}}),Nt(this,"set",async(r,i,s)=>{this.isInitialized();const o=Mt(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===_a.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,GB(HB({},c),{[o]:i}))}return await this.persist(),o}),Nt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),Nt(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}),Nt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Mt(i);return typeof s[o]<"u"}),Nt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Mt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),Nt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Ot(e,this.name),this.core=n}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Cu(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Cu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZB=Object.defineProperty,YB=Object.defineProperties,XB=Object.getOwnPropertyDescriptors,by=Object.getOwnPropertySymbols,JB=Object.prototype.hasOwnProperty,QB=Object.prototype.propertyIsEnumerable,Tl=(t,e,n)=>e in t?ZB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ui=(t,e)=>{for(var n in e||(e={}))JB.call(e,n)&&Tl(t,n,e[n]);if(by)for(var n of by(e))QB.call(e,n)&&Tl(t,n,e[n]);return t},wy=(t,e)=>YB(t,XB(e)),Kt=(t,e,n)=>Tl(t,typeof e!="symbol"?e+"":e,n);class eA extends hm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Kt(this,"events",new rt.exports.EventEmitter),Kt(this,"name",j7),Kt(this,"queue",new Map),Kt(this,"publishTimeout",H.toMiliseconds(H.ONE_MINUTE)),Kt(this,"initialPublishTimeout",H.toMiliseconds(H.ONE_SECOND*15)),Kt(this,"needsTransportRestart",!1),Kt(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const f=s?.ttl||M7,d=s?.prompt||!1,h=s?.tag||0,p=s?.id||Sr().toString(),b=Ri(wa().protocol),m={id:p,method:s?.publishMethod||b.publish,params:Ui({topic:r,message:i,ttl:f,prompt:d,tag:h,attestation:s?.attestation},s?.tvf)},B=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{Re((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Re((c=m.params)==null?void 0:c.tag)&&((u=m.params)==null||delete u.tag);const D=new Promise(async _=>{const x=({id:P})=>{var C;((C=m.id)==null?void 0:C.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Se.publish,x),_())};this.relayer.events.on(Se.publish,x);const T=cn(new Promise((P,C)=>{this.rpcPublish(m,s).then(P).catch(U=>{this.logger.warn(U,U?.message),C(U)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await T,this.events.removeListener(Se.publish,x)}catch(P){this.queue.set(p,{request:m,opts:s,attempt:1}),this.logger.warn(P,P?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await cn(D,this.publishTimeout,B)}catch(D){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(D),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw D}finally{this.queue.delete(p)}}),Kt(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:u,opts:l={}}=r,{attestation:f,tvf:d,publishMethod:h,prompt:p,tag:b,ttl:m=H.FIVE_MINUTES}=l,B=l.id||Sr().toString(),D=Ri(wa().protocol),_=h||D.publish,x={id:B,method:_,params:Ui(wy(Ui({},u),{ttl:m,prompt:p,tag:b,attestation:f}),d)},T=`Failed to publish custom payload, please try again. id:${B} tag:${b}`;try{Re((i=x.params)==null?void 0:i.prompt)&&((s=x.params)==null||delete s.prompt),Re((o=x.params)==null?void 0:o.tag)&&((a=x.params)==null||delete a.tag);const P=new Promise(async C=>{const U=({id:j})=>{var M;((M=x.id)==null?void 0:M.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(Se.publish,U),C())};this.relayer.events.on(Se.publish,U);const $=cn(new Promise((j,M)=>{this.rpcPublish(x,l).then(j).catch(E=>{this.logger.warn(E,E?.message),M(E)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${_} id:${B} tag:${b}`);try{await $,this.events.removeListener(Se.publish,U)}catch(j){this.queue.set(B,{request:x,opts:l,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:B,payload:u,opts:l}}),await cn(P,this.publishTimeout,T)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(B)}}),Kt(this,"on",(r,i)=>{this.events.on(r,i)}),Kt(this,"once",(r,i)=>{this.events.once(r,i)}),Kt(this,"off",(r,i)=>{this.events.off(r,i)}),Kt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=Ot(n,this.name),this.registerEventListeners()}get context(){return dt(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(Se.publish,Ui(Ui({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,wy(Ui({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on($r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Se.connection_stalled);return}this.checkQueue()}),this.relayer.on(Se.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var tA=Object.defineProperty,nA=(t,e,n)=>e in t?tA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fi=(t,e,n)=>nA(t,typeof e!="symbol"?e+"":e,n);class rA{constructor(){Fi(this,"map",new Map),Fi(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Fi(this,"get",e=>this.map.get(e)||[]),Fi(this,"exists",(e,n)=>this.get(e).includes(n)),Fi(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Fi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var iA=Object.defineProperty,sA=Object.defineProperties,oA=Object.getOwnPropertyDescriptors,my=Object.getOwnPropertySymbols,aA=Object.prototype.hasOwnProperty,cA=Object.prototype.propertyIsEnumerable,Pl=(t,e,n)=>e in t?iA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ks=(t,e)=>{for(var n in e||(e={}))aA.call(e,n)&&Pl(t,n,e[n]);if(my)for(var n of my(e))cA.call(e,n)&&Pl(t,n,e[n]);return t},Rl=(t,e)=>sA(t,oA(e)),be=(t,e,n)=>Pl(t,typeof e!="symbol"?e+"":e,n);class uA extends gm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,be(this,"subscriptions",new Map),be(this,"topicMap",new rA),be(this,"events",new rt.exports.EventEmitter),be(this,"name",Z7),be(this,"version",Y7),be(this,"pending",new Map),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",fn),be(this,"subscribeTimeout",H.toMiliseconds(H.ONE_MINUTE)),be(this,"initialSubscribeTimeout",H.toMiliseconds(H.ONE_SECOND*15)),be(this,"clientId"),be(this,"batchSubscribeTopicsLimit",500),be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),be(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=wa(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}}),be(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),be(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),be(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),be(this,"on",(r,i)=>{this.events.on(r,i)}),be(this,"once",(r,i)=>{this.events.once(r,i)}),be(this,"off",(r,i)=>{this.events.off(r,i)}),be(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),be(this,"start",async()=>{await this.onConnect()}),be(this,"stop",async()=>{await this.onDisconnect()}),be(this,"restart",async()=>{await this.restore(),await this.onRestart()}),be(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)}),be(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on($r.pulse,async()=>{await this.checkPending()}),this.events.on(Rt.created,async r=>{const i=Rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Rt.deleted,async r=>{const i=Rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=Ot(n,this.name),this.clientId=""}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,n){let r=!1;try{r=this.getSubscription(e).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(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=wa(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=xe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===ve.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Ri(n.protocol).subscribe,params:{topic:e}};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===ve.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},H.toMiliseconds(H.ONE_SECOND)),o;const u=new Promise(async f=>{const d=h=>{h.topic===e&&(this.events.removeListener(Rt.created,d),f(h.id))};this.events.on(Rt.created,d);try{const h=await cn(new Promise((p,b)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m?.message),b(m)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Rt.created,d),f(h)}catch{}}),l=await cn(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Se.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const n=e[0].relay,r={method:Ri(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await cn(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(Se.connection_stalled),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Ri(n.protocol).batchFetchMessages,params:{topics:e.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 cn(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(Se.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Ri(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,Rl(ks({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,ks({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,ks({},n)),this.topicMap.set(n.topic,e),this.events.emit(Rt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(Rt.deleted,Rl(ks({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Rt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e)){this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),e.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(e.map(async n=>Rl(ks({},n),{id:await this.getSubscriptionId(n.topic)}))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await M_(H.toMiliseconds(H.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Mt(e+await this.getClientId())}}var lA=Object.defineProperty,vy=Object.getOwnPropertySymbols,fA=Object.prototype.hasOwnProperty,hA=Object.prototype.propertyIsEnumerable,Nl=(t,e,n)=>e in t?lA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ey=(t,e)=>{for(var n in e||(e={}))fA.call(e,n)&&Nl(t,n,e[n]);if(vy)for(var n of vy(e))hA.call(e,n)&&Nl(t,n,e[n]);return t},re=(t,e,n)=>Nl(t,typeof e!="symbol"?e+"":e,n);class dA extends dm{constructor(e){var n;super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new rt.exports.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",V7),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",H.toMiliseconds(H.THIRTY_SECONDS+H.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",H.toMiliseconds(H.ONE_SECOND*15)),re(this,"stalledRestartInProgress",!1),re(this,"stalledRestartTimeout"),re(this,"stalledRestartBackoff",0),re(this,"stalledRestartBaseInterval",H.toMiliseconds(H.ONE_SECOND*2)),re(this,"stalledRestartMaxInterval",H.toMiliseconds(H.THIRTY_SECONDS)),re(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||Sr().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(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),re(this,"resetPingTimeout",()=>{Yo()&&(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))}),re(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Se.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Se.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))}),re(this,"registerProviderListeners",()=>{this.provider.on(zt.payload,this.onPayloadHandler),this.provider.on(zt.connect,this.onConnectHandler),this.provider.on(zt.disconnect,this.onDisconnectHandler),this.provider.on(zt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=P1({logger:(n=e.logger)!=null?n:z7,name:this.name}),this.messages=new WB(this.logger,e.core),this.subscriber=new uA(this,this.logger),this.publisher=new eA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Y1,S_()?this.packageName=N0():O_()&&(this.bundleId=N0()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return dt(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:ve.relay},_a.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,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(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(Rt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Rt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,Ey({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await cn(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(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(e).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(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||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 T1())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=e.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(e,n){const{topic:r}=e;if(!n.sessionExists){const i=Te(H.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(Se.message,e),await this.recordMessageEvent(e,_a.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,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(zt.disconnect,s),await cn(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(zt.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(zt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zt.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,H.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Yo())try{(n=(e=this.provider)==null?void 0:e.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 e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new S7(new $7(T_({sdkVersion:Ol,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;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(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sl(e)){if(!e.method.endsWith(K7))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:ve.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ey({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ea(e)&&this.events.emit(Se.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,_a.inbound),this.events.emit(Se.message,e))}async acknowledgePayload(e){const n=va(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zt.payload,this.onPayloadHandler),this.provider.off(zt.connect,this.onConnectHandler),this.provider.off(zt.disconnect,this.onDisconnectHandler),this.provider.off(zt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await T1();A9(async n=>{e!==n&&(e=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($r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&T9())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(Se.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(Se.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},H.toMiliseconds(H7)))))}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function pA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function xy(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function _y(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const gA="[object RegExp]",yA="[object String]",bA="[object Number]",wA="[object Boolean]",Iy="[object Arguments]",mA="[object Symbol]",vA="[object Date]",EA="[object Map]",xA="[object Set]",_A="[object Array]",IA="[object Function]",SA="[object ArrayBuffer]",Cl="[object Object]",OA="[object Error]",BA="[object DataView]",AA="[object Uint8Array]",$A="[object Uint8ClampedArray]",DA="[object Uint16Array]",TA="[object Uint32Array]",PA="[object BigUint64Array]",RA="[object Int8Array]",NA="[object Int16Array]",CA="[object Int32Array]",UA="[object BigInt64Array]",FA="[object Float32Array]",LA="[object Float64Array]";function Sy(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function kA(t,e,n){return qs(t,e,void 0,void 0,void 0,void 0,n)}function qs(t,e,n,r,i,s,o){const a=o(t,e,n,r,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Ms(t,e,s,o)}return Ms(t,e,s,o)}function Ms(t,e,n,r){if(Object.is(t,e))return!0;let i=_y(t),s=_y(e);if(i===Iy&&(i=Cl),s===Iy&&(s=Cl),i!==s)return!1;switch(i){case yA:return t.toString()===e.toString();case bA:{const c=t.valueOf(),u=e.valueOf();return pA(c,u)}case wA:case vA:case mA:return Object.is(t.valueOf(),e.valueOf());case gA:return t.source===e.source&&t.flags===e.flags;case IA:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case EA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!qs(u,e.get(c),c,t,e,n,r))return!1;return!0}case xA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const f=c[l],d=u.findIndex(h=>qs(f,h,void 0,t,e,n,r));if(d===-1)return!1;u.splice(d,1)}return!0}case _A:case AA:case $A:case DA:case TA:case PA:case RA:case NA:case CA:case UA:case FA:case LA:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!qs(t[c],e[c],c,t,e,n,r))return!1;return!0}case SA:return t.byteLength!==e.byteLength?!1:Ms(new Uint8Array(t),new Uint8Array(e),n,r);case BA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Ms(new Uint8Array(t),new Uint8Array(e),n,r);case OA:return t.name===e.name&&t.message===e.message;case Cl:{if(!(Ms(t.constructor,e.constructor,n,r)||Sy(t)&&Sy(e)))return!1;const c=[...Object.keys(t),...xy(t)],u=[...Object.keys(e),...xy(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],d=t[f];if(!Object.hasOwn(e,f))return!1;const h=e[f];if(!qs(d,h,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function qA(){}function MA(t,e){return kA(t,e,qA)}var jA=Object.defineProperty,Oy=Object.getOwnPropertySymbols,zA=Object.prototype.hasOwnProperty,VA=Object.prototype.propertyIsEnumerable,Ul=(t,e,n)=>e in t?jA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,By=(t,e)=>{for(var n in e||(e={}))zA.call(e,n)&&Ul(t,n,e[n]);if(Oy)for(var n of Oy(e))VA.call(e,n)&&Ul(t,n,e[n]);return t},It=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);class ei extends pm{constructor(e,n,r,i=fn,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,It(this,"map",new Map),It(this,"version",G7),It(this,"cached",[]),It(this,"initialized",!1),It(this,"getKey"),It(this,"storagePrefix",fn),It(this,"recentlyDeleted",[]),It(this,"recentlyDeletedLimit",200),It(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Re(o)?this.map.set(this.getKey(o),o):s9(o)?this.map.set(o.id,o):o9(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),It(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())}),It(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),It(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>MA(a[c],o[c]))):this.values)),It(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=By(By({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),It(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=Ot(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KA=Object.defineProperty,HA=(t,e,n)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>HA(t,typeof e!="symbol"?e+"":e,n);class GA{constructor(e,n){this.core=e,this.logger=n,oe(this,"name",X7),oe(this,"version",J7),oe(this,"events",new rt.exports),oe(this,"pairings"),oe(this,"initialized",!1),oe(this,"storagePrefix",fn),oe(this,"ignoredPayloadTypes",[Ln]),oe(this,"registeredMethods",[]),oe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),oe(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),oe(this,"create",async r=>{this.isInitialized();const i=pl(),s=await this.core.crypto.setSymKey(i),o=Te(H.FIVE_MINUTES),a={protocol:Z1},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=w1({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Xr.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:u}}),oe(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[hn.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=b1(r.uri);i.props.properties.topic=s,i.addTrace(hn.pairing_uri_validation_success),i.addTrace(hn.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(hn.existing_pairing),l.active)throw i.setError(jn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(hn.pairing_not_expired)}const f=c||Te(H.FIVE_MINUTES),d={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,d),i.addTrace(hn.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Xr.create,d),i.addTrace(hn.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(hn.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(jn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw i.setError(jn.subscribe_pairing_topic_failure),h}return i.addTrace(hn.subscribe_pairing_topic_success),d}),oe(this,"activate",async({topic:r})=>{this.isInitialized();const i=Te(H.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),oe(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}=zr();this.events.once(de("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),oe(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),oe(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),oe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),oe(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",xe("USER_DISCONNECTED")),await this.deletePairing(i))}),oe(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return w1({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),oe(this,"sendRequest",async(r,i,s)=>{const o=Mn(i,s),a=await this.core.crypto.encode(r,o),c=Cs[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),oe(this,"sendResult",async(r,i,s)=>{const o=va(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Cs[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),oe(this,"sendError",async(r,i,s)=>{const o=Il(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Cs[c]?Cs[c].res:Cs.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),oe(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,xe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),oe(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>lr(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),oe(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)}}),oe(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)}}),oe(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Xr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),oe(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{ln(i)?this.events.emit(de("pairing_ping",s),{}):jt(i)&&this.events.emit(de("pairing_ping",s),{error:i.error})},500)}),oe(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Xr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),oe(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=xe("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)}}),oe(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(xe("WC_METHOD_UNSUPPORTED",r))}),oe(this,"isValidPair",(r,i)=>{var s;if(!_t(r)){const{message:a}=G("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!i9(r.uri)){const{message:a}=G("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}const o=b1(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&H.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(jn.pairing_expired);const{message:a}=G("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),oe(this,"isValidPing",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),oe(this,"isValidDisconnect",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),oe(this,"isValidPairingTopic",async r=>{if(!Be(r,!1)){const{message:i}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(lr(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=G("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=Ot(n,this.name),this.pairings=new ei(this.core,this.logger,this.name,this.storagePrefix)}get context(){return dt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Se.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==ve.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Sl(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):Ea(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(Vt.expired,async e=>{const{topic:n}=L0(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Xr.expire,{topic:n}))})}}var WA=Object.defineProperty,ZA=(t,e,n)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ve=(t,e,n)=>ZA(t,typeof e!="symbol"?e+"":e,n);class YA extends lm{constructor(e,n){super(e,n),this.core=e,this.logger=n,Ve(this,"records",new Map),Ve(this,"events",new rt.exports.EventEmitter),Ve(this,"name",Q7),Ve(this,"version",eO),Ve(this,"cached",[]),Ve(this,"initialized",!1),Ve(this,"storagePrefix",fn),Ve(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)}),Ve(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:Te(H.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(en.created,o)}),Ve(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=jt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(en.updated,i))}),Ve(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))),Ve(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(en.deleted,s)}}),this.persist()}),Ve(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ve(this,"on",(r,i)=>{this.events.on(r,i)}),Ve(this,"once",(r,i)=>{this.events.once(r,i)}),Ve(this,"off",(r,i)=>{this.events.off(r,i)}),Ve(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:Mn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(en.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(en.created,e=>{const n=en.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.updated,e=>{const n=en.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.deleted,e=>{const n=en.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on($r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{H.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(en.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XA=Object.defineProperty,JA=(t,e,n)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nt=(t,e,n)=>JA(t,typeof e!="symbol"?e+"":e,n);class QA extends ym{constructor(e,n){super(e,n),this.core=e,this.logger=n,nt(this,"expirations",new Map),nt(this,"events",new rt.exports.EventEmitter),nt(this,"name",tO),nt(this,"version",nO),nt(this,"cached",[]),nt(this,"initialized",!1),nt(this,"storagePrefix",fn),nt(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)}),nt(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),nt(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(Vt.created,{target:s,expiration:o})}),nt(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),nt(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(Vt.deleted,{target:i,expiration:s})}}),nt(this,"on",(r,i)=>{this.events.on(r,i)}),nt(this,"once",(r,i)=>{this.events.once(r,i)}),nt(this,"off",(r,i)=>{this.events.off(r,i)}),nt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return P_(e);if(typeof e=="number")return R_(e);const{message:n}=G("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Vt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const n=this.expirations.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;H.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Vt.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on($r.pulse,()=>this.checkExpirations()),this.events.on(Vt.created,e=>{const n=Vt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.expired,e=>{const n=Vt.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.deleted,e=>{const n=Vt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var e$=Object.defineProperty,t$=(t,e,n)=>e in t?e$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ae=(t,e,n)=>t$(t,typeof e!="symbol"?e+"":e,n);class n$ extends bm{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,Ae(this,"name",rO),Ae(this,"abortController"),Ae(this,"isDevEnv"),Ae(this,"verifyUrlV3",sO),Ae(this,"storagePrefix",fn),Ae(this,"version",G1),Ae(this,"publicKey"),Ae(this,"fetchPromise"),Ae(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&H.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ae(this,"register",async i=>{if(!Si()||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 u=Nr(),l=this.startAbortTimer(H.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",m),u.body.removeChild(b),h("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const b=u.createElement("iframe");b.src=c,b.style.display="none",b.addEventListener("error",p,{signal:this.abortController.signal});const m=B=>{if(B.data&&typeof B.data=="string")try{const D=JSON.parse(B.data);if(D.type==="verify_attestation"){if(yc(D.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(b),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",m),d(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};u.body.appendChild(b),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Ae(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(yc(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),Ae(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(H.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}),Ae(this,"getVerifyUrl",i=>{let s=i||Us;return oO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Us}`),s=Us),s}),Ae(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(H.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)}}),Ae(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ae(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ae(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")}}),Ae(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ae(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}),Ae(this,"validateAttestation",(i,s)=>{const o=$S(i,s.publicKey),a={hasExpired:H.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=Ot(n,this.name),this.abortController=new AbortController,this.isDevEnv=Fu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return dt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),H.toMiliseconds(e))}}var r$=Object.defineProperty,i$=(t,e,n)=>e in t?r$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ay=(t,e,n)=>i$(t,typeof e!="symbol"?e+"":e,n);class s$ extends wm{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,Ay(this,"context",aO),Ay(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${cO}/${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=Ot(n,this.context)}}var o$=Object.defineProperty,$y=Object.getOwnPropertySymbols,a$=Object.prototype.hasOwnProperty,c$=Object.prototype.propertyIsEnumerable,Fl=(t,e,n)=>e in t?o$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,js=(t,e)=>{for(var n in e||(e={}))a$.call(e,n)&&Fl(t,n,e[n]);if($y)for(var n of $y(e))c$.call(e,n)&&Fl(t,n,e[n]);return t},Le=(t,e,n)=>Fl(t,typeof e!="symbol"?e+"":e,n);class u$ extends mm{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,Le(this,"context",lO),Le(this,"storagePrefix",fn),Le(this,"storageVersion",uO),Le(this,"events",new Map),Le(this,"shouldPersist",!1),Le(this,"init",async()=>{if(!Fu())try{const i={eventId:q0(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:U0(this.core.relayer.protocol,this.core.relayer.version,Ol)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Le(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=q0(),l=this.core.projectId||"",f=Date.now(),d=js({eventId:u,timestamp:f,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,d),this.shouldPersist=!0),d}),Le(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 js(js({},a),this.setMethods(a.eventId))}),Le(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Le(this,"setEventListeners",()=>{this.core.heartbeat.on($r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{H.fromMiliseconds(Date.now())-H.fromMiliseconds(i.timestamp)>fO&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Le(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Le(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)}),Le(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)}),Le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Le(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,js(js({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Le(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)}}),Le(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${hO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ol}${s}`,{method:"POST",body:JSON.stringify(i)})}),Le(this,"getAppDomain",()=>C0().url),this.logger=Ot(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 l$=Object.defineProperty,Dy=Object.getOwnPropertySymbols,f$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable,Ll=(t,e,n)=>e in t?l$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ty=(t,e)=>{for(var n in e||(e={}))f$.call(e,n)&&Ll(t,n,e[n]);if(Dy)for(var n of Dy(e))h$.call(e,n)&&Ll(t,n,e[n]);return t},me=(t,e,n)=>Ll(t,typeof e!="symbol"?e+"":e,n);class kl extends om{constructor(e){var n;super(e),me(this,"protocol",H1),me(this,"version",G1),me(this,"name",xa),me(this,"relayUrl"),me(this,"projectId"),me(this,"customStoragePrefix"),me(this,"events",new rt.exports.EventEmitter),me(this,"logger"),me(this,"heartbeat"),me(this,"relayer"),me(this,"crypto"),me(this,"storage"),me(this,"history"),me(this,"expirer"),me(this,"pairing"),me(this,"verify"),me(this,"echoClient"),me(this,"linkModeSupportedApps"),me(this,"eventClient"),me(this,"initialized",!1),me(this,"logChunkController"),me(this,"on",(a,c)=>this.events.on(a,c)),me(this,"once",(a,c)=>this.events.once(a,c)),me(this,"off",(a,c)=>this.events.off(a,c)),me(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),me(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ve.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.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=e?.projectId,this.relayUrl=e?.relayUrl||Y1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Qw({level:typeof e?.logger=="string"&&e.logger?e.logger:R7.logger,name:xa}),{logger:s,chunkLoggerController:o}=Ff({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.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=Ot(s,this.name),this.heartbeat=new qa,this.crypto=new qB(this,this.logger,e?.keychain),this.history=new YA(this,this.logger),this.expirer=new QA(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new dw(Ty(Ty({},N7),e?.storageOptions)),this.relayer=new dA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new GA(this,this.logger),this.verify=new n$(this,this.logger,this.storage),this.echoClient=new s$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new u$(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new kl(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(W7,r),n}get context(){return dt(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(X1,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(X1)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,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(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}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 d$=kl,Py="wc",Ry=2,Ny="client",ql=`${Py}@${Ry}:${Ny}:`,Ml={name:Ny,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Cy="WALLETCONNECT_DEEPLINK_CHOICE",p$="proposal",Uy="Proposal expired",g$="session",Li=H.SEVEN_DAYS,y$="engine",Ke={wc_sessionPropose:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1104},res:{ttl:H.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1106},res:{ttl:H.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1112},res:{ttl:H.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1114},res:{ttl:H.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:H.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:H.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1119}}},jl={min:H.FIVE_MINUTES,max:H.SEVEN_DAYS},pn={idle:"IDLE",active:"ACTIVE"},b$={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:""}},w$="request",m$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],v$="wc",E$="auth",x$="authKeys",_$="pairingTopics",I$="requests",Sa=`${v$}@${1.5}:${E$}:`,Oa=`${Sa}:PUB_KEY`;var S$=Object.defineProperty,O$=Object.defineProperties,B$=Object.getOwnPropertyDescriptors,Fy=Object.getOwnPropertySymbols,A$=Object.prototype.hasOwnProperty,$$=Object.prototype.propertyIsEnumerable,zl=(t,e,n)=>e in t?S$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fe=(t,e)=>{for(var n in e||(e={}))A$.call(e,n)&&zl(t,n,e[n]);if(Fy)for(var n of Fy(e))$$.call(e,n)&&zl(t,n,e[n]);return t},He=(t,e)=>O$(t,B$(e)),V=(t,e,n)=>zl(t,typeof e!="symbol"?e+"":e,n);class D$ extends _m{constructor(e){super(e),V(this,"name",y$),V(this,"events",new rt.exports),V(this,"initialized",!1),V(this,"requestQueue",{state:pn.idle,queue:[]}),V(this,"sessionRequestQueue",{state:pn.idle,queue:[]}),V(this,"emittedSessionRequests",new j_({limit:500})),V(this,"requestQueueDelay",H.ONE_SECOND),V(this,"expectedPairingMethodMap",new Map),V(this,"recentlyDeletedMap",new Map),V(this,"recentlyDeletedLimit",200),V(this,"relayMessageCache",[]),V(this,"pendingSessions",new Map),V(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Ke)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay)))}),V(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=He(fe({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=QS(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:f,walletPay:d}=i,h=((r=f?.[0])==null?void 0:r.ttl)||Ke.wc_sessionPropose.req.ttl||H.FIVE_MINUTES;this.validateRequestExpiry(h);let p=s,b,m=!1;try{if(p){const $=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."),m=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),$}if(!p||!m){const{topic:$,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=$,b=j}if(!p){const{message:$}=G("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error($)}const B=await this.client.core.crypto.generateKeyPair(),D=Te(h),_=fe(He(fe(fe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Z1}],proposer:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Pt()}),(f||d)&&{requests:{authentication:f?.map($=>{const{domain:j,chains:M,nonce:E,uri:y,exp:v,nbf:g,type:w,statement:I,requestId:O,resources:S,signatureTypes:A}=$;return{domain:j,chains:M,nonce:E,type:w??"caip122",aud:y,version:"1",iat:new Date().toISOString(),exp:v,nbf:g,statement:I,requestId:O,resources:S,signatureTypes:A}}),walletPay:d}}),x=de("session_connect",_.id),{reject:T,resolve:P,done:C}=zr(h,Uy),U=({id:$})=>{$===_.id&&(this.client.events.off("proposal_expire",U),this.pendingSessions.delete(_.id),this.events.emit(x,{error:{message:Uy,code:0}}))};return this.client.events.on("proposal_expire",U),this.events.once(x,({error:$,session:j})=>{this.client.events.off("proposal_expire",U),$?T($):j&&P(j)}),await this.setProposal(_.id,_),await this.sendProposeSession({proposal:_,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:_.id}}}).catch($=>{throw this.deleteProposal(_.id),$}),{uri:b,approval:C}}),V(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}}),V(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:[tn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Jr.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(Jr.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Jr.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:b,proposer:m,requiredNamespaces:B,optionalNamespaces:D}=p;let _=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:b});_||(_=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:tn.session_approve_started,properties:{topic:b,trace:[tn.session_approve_started,tn.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),T=m.publicKey,P=await this.client.core.crypto.generateSharedKey(x,T),C=He(fe(fe(fe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:x,metadata:this.client.metadata},expiry:Te(Li)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{proposalRequestsResponses:h}),U=ve.relay;_.addTrace(tn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:U,internal:{skipSubscribe:!0}})}catch(j){throw _.setError(Jr.subscribe_session_topic_failure),j}_.addTrace(tn.subscribe_session_topic_success);const $=He(fe({},C),{topic:P,requiredNamespaces:B,optionalNamespaces:D,pairingTopic:b,acknowledged:!1,self:C.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:x,transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(P,$),_.addTrace(tn.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:fe({correlationId:a},this.getTVFApproveParams($))}}),_.addTrace(tn.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(P,xe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),j}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:b,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:b}),await this.setExpiry(P,Te(Li)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),V(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:Ke.wc_sessionPropose.reject}),await this.deleteProposal(r)}),V(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=zr(H.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Pt(),u=Sr().toString(),l=this.client.session.get(r).namespaces;return this.events.once(de("session_update",c),({error:f})=>{f?a(f):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:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:l}),a(f)}),{acknowledged:s}}),V(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=Pt(),{done:s,resolve:o,reject:a}=zr(H.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(de("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Te(Li)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),V(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:r,request:i,topic:s,expiry:o=Ke.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const c=Pt(),u=Sr().toString(),{done:l,resolve:f,reject:d}=zr(o,"Request expired. Please try again.");this.events.once(de("session_request",c),({error:m,result:B})=>{m?d(m):f(B)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const b={request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:b,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,b)}).catch(B=>d(B)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),m()}),new Promise(async m=>{var B;if(!((B=a.sessionConfig)!=null&&B.disableDeepLink)){const D=await F_(this.client.core.storage,Cy);await N_({id:c,topic:s,wcDeepLink:D})}m()}),l()]).then(m=>m[2])}),V(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:[tn.session_request_response_started]}});try{await this.isValidRespond(n)}catch(f){throw s.addTrace(f?.message),s.setError(Jr.session_request_response_validation_failure),f}s.addTrace(tn.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,u=this.client.session.get(o);u.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(tn.session_request_response_publish_started),ln(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):jt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(n)}catch(f){throw s.addTrace(f?.message),s.setError(Jr.session_request_response_publish_failure),f}}),V(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=Pt(),s=Sr().toString(),{done:o,resolve:a,reject:c}=zr(H.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(de("session_ping",i),({error:u})=>{u?c(u):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}))}),V(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=Sr().toString(),a=Pt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),V(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:xe("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}=G("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),V(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>n9(r,n)))),V(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),V(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?ve.link_mode:ve.relay;o===ve.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:d,exp:h,nbf:p,methods:b=[],expiry:m}=n,B=[...n.resources||[]],{topic:D,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:_}});const x=await this.client.core.crypto.generateKeyPair(),T=ba(x);if(await Promise.all([this.client.auth.authKeys.set(Oa,{responseTopic:T,publicKey:x}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:D})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${D}`),b.length>0){const{namespace:S}=Pn(a[0]);let A=eI(S,"request",b);sa(B)&&(A=nI(A,B.pop())),B.push(A)}const P=m&&m>Ke.wc_sessionAuthenticate.req.ttl?m:Ke.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:B},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:Te(P)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...b])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:Te(Ke.wc_sessionPropose.req.ttl),id:Pt()},{done:j,resolve:M,reject:E}=zr(P,"Request expired"),y=Pt(),v=de("session_connect",$.id),g=de("session_request",y),w=async({error:S,session:A})=>{this.events.off(g,I),S?E(S):A&&M({session:A})},I=async S=>{var A,R,L;if(await this.deletePendingAuthRequest(y,{message:"fulfilled",code:0}),S.error){const K=xe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===K.code?void 0:(this.events.off(v,w),E(S.error.message))}await this.deleteProposal($.id),this.events.off(v,w);const{cacaos:F,responder:k}=S.result,N=[],q=[];for(const K of F){await hg({cacao:K,projectId:this.client.core.projectId})||(this.client.logger.error(K,"Signature verification failed"),E(xe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Z}=K,Q=sa(Z.resources),ee=[Ku(Z.iss)],se=ia(Z.iss);if(Q){const he=gg(Q),Ee=yg(Q);N.push(...he),ee.push(...Ee)}for(const he of ee)q.push(`${he}:${se}`)}const z=await this.client.core.crypto.generateSharedKey(x,k.publicKey);let W;N.length>0&&(W={topic:z,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:k,controller:k.publicKey,expiry:Te(Li),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:I1([...new Set(N)],[...new Set(q)]),transportType:o},await this.client.core.relayer.subscribe(z,{transportType:o}),await this.client.session.set(z,W),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:k.metadata}),W=this.client.session.get(z)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(R=k.metadata.redirect)!=null&&R.linkMode&&(L=k.metadata.redirect)!=null&&L.universal&&r&&(this.client.core.addLinkModeSupportedApp(k.metadata.redirect.universal),this.client.session.update(z,{transportType:ve.link_mode})),M({auths:F,session:W})};this.events.once(v,w),this.events.once(g,I);let O;try{if(s){const S=Mn("wc_sessionAuthenticate",C,y);this.client.core.history.set(D,S);const A=await this.client.core.crypto.encode("",S,{type:Bs,encoding:Ir});O=ma(r,D,A)}else await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:C,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:y}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:$,expiry:Ke.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(S){throw this.events.off(v,w),this.events.off(g,I),S}return await this.setProposal($.id,$),await this.setAuthRequest(y,{request:He(fe({},C),{verifyContext:{}}),pairingTopic:D,transportType:o}),{uri:O??_,response:j}}),V(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Qr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw s.setError(Fs.no_internet_connection),m}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Fs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ve.relay;a===ve.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ba(c),f={type:Ln,receiverPublicKey:c,senderPublicKey:u},d=[],h=[];for(const m of i){if(!await hg({cacao:m,projectId:this.client.core.projectId})){s.setError(Fs.invalid_cacao);const T=xe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:T,encodeOpts:f}),new Error(T.message)}s.addTrace(Qr.cacaos_verified);const{p:B}=m,D=sa(B.resources),_=[Ku(B.iss)],x=ia(B.iss);if(D){const T=gg(D),P=yg(D);d.push(...T),_.push(...P)}for(const T of _)h.push(`${T}:${x}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Qr.create_authenticated_session_topic);let b;if(d?.length>0){b={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Te(Li),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:I1([...new Set(d)],[...new Set(h)]),transportType:a},s.addTrace(Qr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(m){throw s.setError(Fs.subscribe_authenticated_session_topic_failure),m}s.addTrace(Qr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,b),s.addTrace(Qr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Qr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw s.setError(Fs.authenticated_session_approve_publish_failure),m}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:b}}),V(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===ve.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ba(o),u={type:Ln,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Ke.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)}),V(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return dg(r,i)}),V(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)}),V(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)}}),V(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,xe("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(Cy).catch(u=>this.client.logger.warn(u)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=pn.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===i).map(u=>this.deletePendingSessionRequest(u.id,xe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),V(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(Jr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,xe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),V(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=pn.idle,this.client.events.emit("session_request_expire",{id:n}))}),V(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)])}),V(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}))}),V(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,Te(Ke.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),V(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=ve.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})}),V(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||Te(Ke.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})}),V(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:d={}}=n,h=Mn(i,s,c);let p;const b=!!l;try{const D=b?Ir:xt;p=await this.client.core.crypto.encode(r,h,{encoding:D})}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),D}let m;if(m$.includes(i)){const D=Mt(JSON.stringify(h)),_=Mt(p);m=await this.client.core.verify.register({id:_,decryptedId:D})}const B=fe(fe({},Ke[i].req),d);if(B.attestation=m,o&&(B.ttl=o),a&&(B.id=a),this.client.core.history.set(r,h),b){const D=ma(l,r,p);await global.Linking.openURL(D,this.client.name)}else B.tvf=He(fe({},f),{correlationId:h.id}),u?(B.internal=He(fe({},B.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,B)):this.client.core.relayer.publish(r,p,B).catch(D=>this.client.logger.error(D));return h.id}),V(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=Mn("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:xt}),a=Mt(JSON.stringify(s)),c=Mt(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:He(fe({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),V(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=va(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:xt}),l=Mn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:xt});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:He(fe({},a),{publishMethod:"wc_approveSession"})})}),V(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=va(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?Ir:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let d,h;try{d=await this.client.core.history.get(i,r);const p=d.request;try{h=this.getTVFParams(r,p.params,s)}catch(b){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${b?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(f){const p=ma(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,b=Ke[p].res;b.tvf=He(fe({},h),{correlationId:r}),o?(b.internal=He(fe({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,b)):this.client.core.relayer.publish(i,l,b).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(u)}),V(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=Il(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?Ir:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),h}let d;try{d=await this.client.core.history.get(i,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),h}if(f){const h=ma(c,i,l);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||Ke[h].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),V(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;lr(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=>{lr(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),V(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),V(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),V(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===pn.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=pn.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=pn.idle}),V(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}`)}}),V(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}`)}}),V(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=G("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),V(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)}),V(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(jn.proposal_listener_not_found)),this.isValidConnect(fe({},i.params));const l=a.expiryTimestamp||Te(Ke.wc_sessionPropose.req.ttl),f=fe({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:s,hash:Mt(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(hn.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Ke.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),V(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(ln(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 u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:n,proposalId:s,publicKey:c});const f=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:n})}else if(jt(r)){await this.deleteProposal(s);const o=de("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})}}),V(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=r.params,p=[...this.pendingSessions.values()].find(B=>B.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const b=this.client.proposal.get(p.proposalId),m=He(fe(fe(fe({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(de("session_connect",p.proposalId),{session:m})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;ln(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(de("session_approve",i),{})):jt(r)&&(await this.client.session.delete(n,xe("USER_DISCONNECTED")),this.events.emit(de("session_approve",i),{error:r.error}))}),V(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=Ps.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:xe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fe({topic:n},i));try{Ps.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw Ps.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)}}),V(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),V(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=de("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_update",i),{}):jt(r)&&this.events.emit(de("session_update",i),{error:r.error})}),V(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,Te(Li)),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)}}),V(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=de("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_extend",i),{}):jt(r)&&this.events.emit(de("session_extend",i),{error:r.error})}),V(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)}}),V(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=de("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);ln(r)?this.events.emit(de("session_ping",i),{}):jt(r)&&this.events.emit(de("session_ping",i),{error:r.error})},500)}),V(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:xe("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),V(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:d}=a;try{await this.isValidRequest(fe({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Mt(JSON.stringify(Mn("wc_sessionRequest",d,f))),encryptedId:u,metadata:h.peer.metadata,transportType:l}),b={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(b),l===ve.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=h.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(b):(this.addSessionRequestToSessionRequestQueue(b),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),V(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=de("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=Ps.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(fe({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),Ps.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:f}=s.params,d=await this.getVerifyContext({attestationId:o,hash:Mt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:i,transportType:c}),c===ve.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:Ln,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:h,rpcOpts:Ke.wc_sessionAuthenticate.autoReject,appLink:d})}}),V(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),V(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=pn.idle,this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay))}),V(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(de("session_request",s.request.id),{error:r})})}),V(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===pn.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)}}),V(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=pn.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),V(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:Mn("wc_sessionPropose",He(fe({},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})}),V(this,"isValidConnect",async n=>{if(!_t(n)){const{message:u}=G("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(Re(r)||await this.isValidPairingTopic(r),!p9(c,!0)){const{message:u}=G("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(i&&!Re(i)&&Ds(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!Re(s)&&Ds(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),V(this,"validateNamespaces",(n,r)=>{const i=d9(n,"connect()",r);if(i)throw new Error(i.message)}),V(this,"isValidApprove",async n=>{if(!_t(n))throw new Error(G("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),u=bl(i,"approve()");if(u)throw new Error(u.message);const l=$1(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Be(s,!0)){const{message:f}=G("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),V(this,"isValidReject",async n=>{if(!_t(n)){const{message:s}=G("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!y9(i)){const{message:s}=G("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),V(this,"isValidSessionSettleRequest",n=>{if(!_t(n)){const{message:u}=G("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!B1(r)){const{message:u}=G("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=a9(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=bl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(lr(o)){const{message:u}=G("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),V(this,"isValidUpdate",async n=>{if(!_t(n)){const{message:c}=G("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=bl(i,"update()");if(o)throw new Error(o.message);const a=$1(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),V(this,"isValidExtend",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),V(this,"isValidRequest",async n=>{if(!_t(n)){const{message:c}=G("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(!A1(a,s)){const{message:c}=G("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!b9(i)){const{message:c}=G("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!v9(a,s,i.method)){const{message:c}=G("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),V(this,"isValidRespond",async n=>{var r;if(!_t(n)){const{message:a}=G("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(!w9(s)){const{message:a}=G("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}=G("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),V(this,"isValidPing",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(this,"isValidEmit",async n=>{if(!_t(n)){const{message:a}=G("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(!A1(o,s)){const{message:a}=G("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!m9(i)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!E9(o,s,i.name)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),V(this,"isValidDisconnect",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(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(!Be(i,!1))throw new Error("uri is required parameter");if(!Be(s,!1))throw new Error("domain is required parameter");if(!Be(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Pn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Pn(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),V(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Us,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ve.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),V(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=G("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),V(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),V(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)}}}),V(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),V(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,d;return!n||r!==ve.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&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=n?.redirect)==null?void 0:l.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),V(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),V(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=k0(n,"topic")||"",i=decodeURIComponent(k0(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:ve.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),V(this,"registerLinkModeListeners",async()=>{var n;if(Fu()||ur()&&(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)}}}),V(this,"getTVFApproveParams",n=>{try{const r=E1(n.namespaces),i=GS(n.namespaces),s=WS(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"),{}}}),V(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 u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),V(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}),V(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=b$[s];if(s==="sui_signTransaction")return[C5(r.transactionBytes)];if(s==="near_signTransaction")return[ag(r)];if(s==="near_signTransactions")return r.map(c=>ag(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[k9({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Ci(r)?r.map(c=>cg(c)):[cg(r)];if(s==="cosmos_signDirect")return[F5(r)];if(s==="wallet_sendCalls")return L5(r);if(typeof r=="string")return[r];const a=r[o.key];if(Ci(a))return s==="solana_signAllTransactions"?a.map(c=>N5(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 e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);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(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Se.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Oa)?this.client.auth.authKeys.get(Oa):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===ve.link_mode?Ir:xt});Sl(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Mt(r)})):Ea(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(Vt.expired,async e=>{const{topic:n,id:r}=L0(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,G("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,G("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(Xr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Be(e,!1)){const{message:n}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=G("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!Be(e,!1)){const{message:n}=G("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=G("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=G("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Be(e,!1)){const{message:n}=G("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=G("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!g9(e)){const{message:n}=G("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=G("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}validateRequestExpiry(e){if(e&&!I9(e,jl)){const{message:n}=G("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${jl.min} and ${jl.max}`);throw new Error(n)}}}class T$ extends ei{constructor(e,n){super(e,n,p$,ql),this.core=e,this.logger=n}}class P$ extends ei{constructor(e,n){super(e,n,g$,ql),this.core=e,this.logger=n}}class R$ extends ei{constructor(e,n){super(e,n,w$,ql,r=>r.id),this.core=e,this.logger=n}}class N$ extends ei{constructor(e,n){super(e,n,x$,Sa,()=>Oa),this.core=e,this.logger=n}}class C$ extends ei{constructor(e,n){super(e,n,_$,Sa),this.core=e,this.logger=n}}class U$ extends ei{constructor(e,n){super(e,n,I$,Sa,r=>r.id),this.core=e,this.logger=n}}var F$=Object.defineProperty,L$=(t,e,n)=>e in t?F$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vl=(t,e,n)=>L$(t,typeof e!="symbol"?e+"":e,n);class k${constructor(e,n){this.core=e,this.logger=n,Vl(this,"authKeys"),Vl(this,"pairingTopics"),Vl(this,"requests"),this.authKeys=new N$(this.core,this.logger),this.pairingTopics=new C$(this.core,this.logger),this.requests=new U$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var q$=Object.defineProperty,M$=(t,e,n)=>e in t?q$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ae=(t,e,n)=>M$(t,typeof e!="symbol"?e+"":e,n);class Kl extends xm{constructor(e){super(e),ae(this,"protocol",Py),ae(this,"version",Ry),ae(this,"name",Ml.name),ae(this,"metadata"),ae(this,"core"),ae(this,"logger"),ae(this,"events",new rt.exports.EventEmitter),ae(this,"engine"),ae(this,"session"),ae(this,"proposal"),ae(this,"pendingRequest"),ae(this,"auth"),ae(this,"signConfig"),ae(this,"on",(r,i)=>this.events.on(r,i)),ae(this,"once",(r,i)=>this.events.once(r,i)),ae(this,"off",(r,i)=>this.events.off(r,i)),ae(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),ae(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),ae(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),ae(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),ae(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ml.name,this.metadata=A_(e?.metadata),this.signConfig=e?.signConfig;const n=P1({logger:e?.logger||Ml.logger,name:this.name});this.logger=n,this.core=e?.core||new d$(e),this.session=new P$(this.core,this.logger),this.proposal=new T$(this.core,this.logger),this.pendingRequest=new R$(this.core,this.logger),this.engine=new D$(this),this.auth=new k$(this.core,this.logger)}static async init(e){const n=new Kl(e);return await n.initialize(),n}get context(){return dt(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const j$=Kl;class Ly{constructor(e){this.opts=e}}class ky{constructor(e){this.client=e}}const qy=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Ts(r?.chainId))return!1;const{namespace:a}=Pn(r.chainId),c=e.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(u=>u.toLowerCase()).includes(s?.toLowerCase()))throw new Error(`Unsupported token standard: ${s} for namespace: ${a}`);return!0},z$=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!qy({supportedNamespaces:e,token:r}))},My=t=>{let e,n;return async()=>e!==void 0?e:n||(n=t(),e=await n,e)};var V$=Object.defineProperty,K$=(t,e,n)=>e in t?V$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,le=(t,e,n)=>K$(t,typeof e!="symbol"?e+"":e,n);class H$ extends ky{constructor(e){var n;super(e),le(this,"signClient"),le(this,"logger"),le(this,"tokens",[]),le(this,"supportedNamespaces",cf),le(this,"paymentIntents",{}),le(this,"transactions",{}),le(this,"paymentsSendingInProgress",{}),le(this,"manualControl",{}),le(this,"init",async()=>{var r,i;this.signClient=await j$.init({projectId:this.client.opts.projectId,metadata:{name:this.client.metadata.merchantName,description:this.client.metadata.description,url:this.client.metadata.url,icons:[this.client.metadata.logoIcon]},storageOptions:{database:((r=this.client.opts.storageOptions)==null?void 0:r.databaseName)||Da.database},customStoragePrefix:Da.customStoragePrefix,logger:((i=this.client.opts.loggerOptions)==null?void 0:i.signLevel)||Ta}),this.signClient.events.on("session_delete",({topic:s})=>{this.cleanup({sessionTopic:s}),this.emit("disconnected",{sessionTopic:s})});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest({payload:JSON.stringify({id:Pt(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:s.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error(s,"Failed to fetch supported namespaces/networks")}}),le(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug({tokens:i},"Setting tokens"),i.forEach(s=>{if(!qy({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=i,s()}),this.logger.debug({tokens:i},"Tokens set")}),le(this,"createPaymentIntent",async r=>{const{paymentIntents:i,sessionTopic:s,userId:o}=r;this.logger.debug({paymentIntents:i,userId:o},"Creating payment intent");const a=r.manualControl||!1;if(i.length===0)throw new Error("No payment intents provided");for(const d of i)if(!z$({paymentIntent:d,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(d)}`);if(this.logger.debug({paymentIntents:i,userId:o},"Payment intent validation success"),s){this.manualControl[s]=a;try{this.setPaymentIntents({sessionTopic:s,paymentIntents:i,userId:o}),this.validateApprovedNamespacesWithPaymentIntents(s),a||await this.sendPaymentsToWallet({sessionTopic:s,userId:o});return}catch(d){this.logger.error(d),await this.disconnect({sessionTopic:s})}}const c=this.composeNamespacesFromPaymentIntents(i),{uri:u,approval:l}=await this.signClient.connect({optionalNamespaces:c});if(this.logger.debug({uri:u,userId:o},"Connected to the WalletConnect network"),!u)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:o}),new Error("Failed to connect to the WalletConnect network");const f=My(l);if(this.emit("await_approval",{approval:f,paymentIntents:i,userId:o,manualControl:a}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:u,userId:o}),this.logger.debug({uri:u,userId:o},"Emitted qr_ready event"),a){const d=await f();this.manualControl[d.topic]=a}}),le(this,"restart",async r=>{this.logger.debug({params:r},"Restarting");const{reinit:i,sessionTopic:s,userId:o}=r||{};if(i){this.tokens=[],await this.disconnect({sessionTopic:s}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const a=this.getSessionTopic(s),c=this.manualControl[a],u=this.paymentIntents[a];if(!u||!(u!=null&&u.length))throw new Error("No payment intents found for session topic: "+a);await this.createPaymentIntent({paymentIntents:u,manualControl:c,userId:o,sessionTopic:a}),this.logger.debug({paymentIntents:u,userId:o},"Restarted: Created payment intent flow from the beginning")}),le(this,"connect",async r=>{const{userId:i}=r,s=!0,o=this.composeNamespacesFromTokens(),{uri:a,approval:c}=await this.signClient.connect({optionalNamespaces:o});if(this.logger.debug({uri:a},"Connected to the WalletConnect network"),!a)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:i}),new Error("Failed to connect to the WalletConnect network");const u=My(c);this.emit("await_approval",{approval:u,manualControl:s,paymentIntents:[],userId:i}),this.logger.debug({userId:i},"Emitted await_approval event"),this.emit("qr_ready",{uri:a,userId:i}),this.logger.debug({uri:a,userId:i},"Emitted qr_ready event");const l=await u();return this.manualControl[l.topic]=s,l}),le(this,"emit",(r,i)=>(this.logger.debug({event:r,args:i},"Emit"),this.client.events.emit(r,i))),le(this,"on",(r,i)=>(this.logger.debug({event:r,listener:i},"On"),this.client.events.on(r,i))),le(this,"once",(r,i)=>(this.logger.debug({event:r,listener:i},"Once"),this.client.events.once(r,i))),le(this,"off",(r,i)=>(this.logger.debug({event:r,listener:i},"Off"),this.client.events.off(r,i))),le(this,"removeListener",(r,i)=>(this.logger.debug({event:r,listener:i},"Remove listener"),this.client.events.removeListener(r,i))),le(this,"prepareTransactionsFromPaymentIntents",async r=>{var i,s,o,a,c,u;const{sessionTopic:l,userId:f}=r,d=this.getSessionTopic(l),h=this.paymentIntents[d];if(!h)throw new Error("No payment intents found for session topic: "+d);const p=this.signClient.session.get(d);this.logger.debug({sessionTopic:d,userId:f},"Preparing transactions from payment intents");const b=[];for(const D of h){const{token:_,amount:x,recipient:T}=D,{namespace:P}=Pn(_.network.chainId),C=(o=(s=(i=p.namespaces)==null?void 0:i[P])==null?void 0:s.accounts)==null?void 0:o.find(U=>U.includes(`${_.network.chainId}:`));if(!C)throw new Error(`Address not found in session for chain id: ${_.network.chainId}, approved addresses: ${(u=(c=(a=p.namespaces)==null?void 0:a[P])==null?void 0:c.accounts)==null?void 0:u.join(", ")}`);b.push({asset:`${_.network.chainId}/${_.standard.toLowerCase()}:${_.address}`,recipient:T,amount:x,sender:C})}this.logger.debug({sessionTopic:p.topic,transactions:b,userId:f},"Prepared transactions from payment intents");const m={id:Pt(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:b}};this.logger.debug({payload:m,userId:f},"Fetching wc_pos_buildTransactions");const B=await this.fetchRpcRequest({payload:JSON.stringify(m),userId:f});this.logger.debug({response:B,userId:f},"Received wc_pos_buildTransactions"),this.transactions[p.topic]=B.result.transactions,this.logger.debug({transactions:this.transactions[p.topic],userId:f},"Payment intent to transactions map set")}),le(this,"sendPaymentsToWallet",async(r={})=>{const{sessionTopic:i,userId:s}=r,o=this.getSessionTopic(i);if(!o)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[o])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[o]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:o,userId:s}),await this.sendTransactionsToWallet({sessionTopic:o,userId:s})}catch(a){throw this.logger.error(a,"Error while sending payments to wallet"),this.paymentsSendingInProgress[o]=!1,a}this.paymentsSendingInProgress[o]=!1}),le(this,"sendTransactionsToWallet",async r=>{const{sessionTopic:i,userId:s}=r,o=this.transactions[i],a=this.paymentIntents[i];if(!o||!a)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(o.length!==a.length)throw new Error(`Mismatch between transactions (${o.length}) and payment intents (${a.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:o,sessionTopic:i,userId:s},"Sending transactions to wallet");for(let c=0;c<o.length;c++){const u=o[c],l=a[c];try{this.emit("payment_requested",{paymentIntent:l,transaction:u,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_requested event");let f;try{f=await this.signClient.request({topic:i,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug({transactionId:u.id,result:f,userId:s},"Wallet responded to payment request")}catch(d){throw this.logger.error(d,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:d?.message,code:4001},paymentIntent:l,sessionTopic:i,userId:s}),d}this.emit("payment_broadcasted",{paymentIntent:l,transaction:u,result:f,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:u,result:f,sessionTopic:i,userId:s}),await new Promise(d=>setTimeout(d,1e3))}catch(f){this.logger.error(f,"Error while awaiting payment confirmed")}}this.manualControl[i]!==!0&&await this.disconnect({sessionTopic:i})}),le(this,"awaitPaymentConfirmed",async r=>{const{transaction:i,result:s,sessionTopic:o,userId:a}=r;try{this.logger.debug({transactionId:i.id,result:s},"Awaiting payment confirmed");const c={id:Pt(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let u=0,l;for(;!l;){if(u>=af)throw new Error(`Transaction status not found for id: ${i.id}`);u++;const f=await this.fetchRpcRequest({payload:JSON.stringify(c),userId:a});if(this.logger.debug({transactionId:i.id,response:f},"Received wc_pos_checkTransaction"),f.result.status==="CONFIRMED"){this.logger.debug({response:f,userId:a},"Transaction status confirmed"),this.emit("payment_successful",{transaction:i,result:s,sessionTopic:o,userId:a}),l=f.result;break}else if(f.result.status==="FAILED"){this.logger.debug({response:f},"Transaction failed"),this.emit("payment_failed",{error:{message:f.result.error,code:4001},transaction:s,sessionTopic:o,userId:a}),l=f.result;break}else f.result.status==="PENDING"&&(this.logger.debug({response:f,userId:a},"Transaction pending"),await new Promise(d=>setTimeout(d,f.result.checkIn||1e3)))}}catch(c){this.logger.error(c,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:c?.message,code:4001},transaction:i,sessionTopic:o,userId:a})}}),le(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,paymentIntents:i,userId:s,manualControl:o})=>{try{this.logger.debug("On await_approval");const a=await r();this.setPaymentIntents({sessionTopic:a.topic,paymentIntents:i}),await this.onSessionConnected({session:a,userId:s,manualControl:o})}catch(a){this.logger.error(a,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:a?.message,code:4001},userId:s})}})}),le(this,"onSessionConnected",async r=>{const{session:i,userId:s,manualControl:o}=r;this.logger.debug({sessionTopic:i.topic,userId:s},"On session connected"),this.emit("connected",{session:i,userId:s}),await this.signClient.session.update(i.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:i.topic,userId:s},"Disabled deep links for session"),this.logger.debug({sessionTopic:i.topic,userId:s},"Emitted connected event"),o!==!0&&await this.sendPaymentsToWallet({sessionTopic:i.topic,userId:s})}),le(this,"disconnect",async(r={})=>{try{const{sessionTopic:i}=r,s=this.getSessionTopic(i);if(!s)return;this.cleanup({sessionTopic:s}),await this.signClient.disconnect({topic:s,reason:{code:4001,message:"User disconnected"}})}catch(i){this.logger.error(i,"Error while disconnecting")}}),le(this,"fetchRpcRequest",async r=>{var i,s,o,a,c,u;const{payload:l,userId:f}=r;this.logger.debug({url:this.getRpcUrl(),payload:l,userId:f},"Fetching RPC request");const d=await fetch(this.getRpcUrl(),{method:"POST",body:l});let h;try{h=await d.json()}catch(p){this.logger.error(p,"Error while getting json data from RPC response")}if(this.logger.debug({data:h},"Received RPC request response"),!d.ok||!h||h!=null&&h.error){const p=((i=h?.error)==null?void 0:i.code)||-18900,b=(s=Pa)!=null&&s[p]?`${(o=Pa)==null?void 0:o[p]}: ${(a=h?.error)==null?void 0:a.message}`:((c=h?.error)==null?void 0:c.message)||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:b,code:p},transaction:"",sessionTopic:((u=this.client.session)==null?void 0:u.topic)||"",userId:f}),new Error(b)}return h}),le(this,"validateApprovedNamespacesWithPaymentIntents",r=>{var i,s,o,a,c,u,l;this.validateSessionTopic(r);const f=this.signClient.session.get(r),d=(i=this.paymentIntents)==null?void 0:i[r];if(!f||!d)throw new Error("No session or payment intents found");for(const h of d){const{token:p}=h,{namespace:b}=Pn(p.network.chainId);if(!((a=(o=(s=f.namespaces)==null?void 0:s[b])==null?void 0:o.accounts)!=null&&a.find(m=>m.includes(`${p.network.chainId}:`))))throw new Error(`Address not found in session for chain id: ${p.network.chainId}, approved addresses: ${(l=(u=(c=f.namespaces)==null?void 0:c[b])==null?void 0:u.accounts)==null?void 0:l.join(", ")}`)}}),le(this,"setPaymentIntents",r=>{const{sessionTopic:i,paymentIntents:s,userId:o}=r;this.paymentIntents[i]=s,this.logger.debug({paymentIntents:s,userId:o},"Payment intents set")}),le(this,"cleanup",(r={})=>{const{sessionTopic:i}=r;i&&(delete this.paymentIntents[i],delete this.transactions[i],delete this.manualControl[i],delete this.paymentsSendingInProgress[i],this.logger.debug({sessionTopic:i},"Cleaned up payment intents and transactions"))}),le(this,"getRpcUrl",()=>uf({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId})),le(this,"validateSessionTopic",r=>{if(r)try{this.signClient.session.get(r)}catch(i){throw this.logger.error(i,`No session found for topic: ${r}`),new Error(`No session found for topic: ${r}`)}}),le(this,"getSessionTopic",r=>{var i;if(!r&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const s=r||((i=this.client.session)==null?void 0:i.topic);if(!s)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(s),s}),this.signClient={},this.logger=Pw({name:this.client.name,level:((n=this.client.opts.loggerOptions)==null?void 0:n.posLevel)||Ta}),this.setupEventHandlers()}composeNamespacesFromTokens(){const e=this.tokens;if(this.logger.debug({tokens:e},"Composing namespaces from tokens"),e.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const n={};return e.forEach(r=>{var i;const{network:s}=r,{namespace:o}=Pn(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}composeNamespacesFromPaymentIntents(e){this.logger.debug({paymentIntents:e},"Composing namespaces");const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=Pn(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}}var G$=Object.defineProperty,W$=(t,e,n)=>e in t?G$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,St=(t,e,n)=>W$(t,typeof e!="symbol"?e+"":e,n);class Ba extends Ly{constructor(e){super(e),St(this,"name"),St(this,"events",new rt.exports),St(this,"engine"),St(this,"metadata"),St(this,"on",(n,r)=>this.engine.on(n,r)),St(this,"once",(n,r)=>this.engine.once(n,r)),St(this,"off",(n,r)=>this.engine.off(n,r)),St(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),St(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"sendPaymentsToWallet",async n=>{try{return await this.engine.sendPaymentsToWallet(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=$a,this.engine=new H$(this)}static async init(e){const n=new Ba(e);return await n.initialize(),n}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(e.message),e}}}const Z$=Ba;Oe.CLIENT_CONTEXT=$a,Oe.CLIENT_STORAGE_OPTIONS=Da,Oe.CLIENT_STORAGE_PREFIX=nb,Oe.DEFAULT_LOGGER_LEVEL=Ta,Oe.DEFAULT_NAMESPACES=cf,Oe.IPOSClient=Ly,Oe.IPOSClientEngine=ky,Oe.MAX_TRANSACTION_STATUS_CHECKS=af,Oe.POSClient=Z$,Oe.POS_CLIENT_VERSION=of,Oe.PROTOCOL=sf,Oe.PROTOCOL_VERSION=tb,Oe.RPC_ERROR_CODES=Pa,Oe.RPC_URL=uf,Oe.default=Ba,Object.defineProperty(Oe,"__esModule",{value:!0})});
41
41
  //# sourceMappingURL=index.umd.js.map