@reown/walletkit 1.2.3 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -36,5 +36,5 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(zE(r)).toStr
|
|
|
36
36
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
37
37
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
38
38
|
PERFORMANCE OF THIS SOFTWARE.
|
|
39
|
-
***************************************************************************** */var ua=function(t,e){return ua=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},ua(t,e)};function BS(t,e){ua(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var la=function(){return la=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},la.apply(this,arguments)};function FS(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function LS(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function US(t,e){return function(r,n){e(r,n,t)}}function kS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function MS(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function jS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=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 r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function qS(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function zS(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ha(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function $d(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function VS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($d(arguments[e]));return t}function KS(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Jn(t){return this instanceof Jn?(this.v=t,this):new Jn(t)}function HS(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){n[d]&&(i[d]=function(p){return new Promise(function(f,y){s.push([d,p,f,y])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof Jn?Promise.resolve(d.value.v).then(u,l):h(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function WS(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Jn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function GS(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof ha=="function"?ha(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function YS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ZS(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function JS(t){return t&&t.__esModule?t:{default:t}}function XS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function QS(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var ex=Object.freeze({__proto__:null,__extends:BS,get __assign(){return la},__rest:FS,__decorate:LS,__param:US,__metadata:kS,__awaiter:MS,__generator:jS,__createBinding:qS,__exportStar:zS,__values:ha,__read:$d,__spread:VS,__spreadArrays:KS,__await:Jn,__asyncGenerator:HS,__asyncDelegator:WS,__asyncValues:GS,__makeTemplateObject:YS,__importStar:ZS,__importDefault:JS,__classPrivateFieldGet:XS,__classPrivateFieldSet:QS}),tx=ka(ex),qt={},Ad;function rx(){if(Ad)return qt;Ad=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.isBrowserCryptoAvailable=qt.getSubtleCrypto=qt.getBrowerCrypto=void 0;function t(){return yt?.crypto||yt?.msCrypto||{}}qt.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qt.isBrowserCryptoAvailable=r,qt}var zt={},Pd;function nx(){if(Pd)return zt;Pd=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.isBrowser=zt.isNode=zt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zt.isNode=e;function r(){return!t()&&!e()}return zt.isBrowser=r,zt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=tx;e.__exportStar(rx(),t),e.__exportStar(nx(),t)})(Od);function xt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ir(t=6){return BigInt(xt(t))}function Dr(t,e,r){return{id:r||xt(),jsonrpc:"2.0",method:t,params:e}}function da(t,e){return{id:t,jsonrpc:"2.0",result:e}}function fa(t,e,r){return{id:t,jsonrpc:"2.0",error:ix(e,r)}}function ix(t,e){return typeof t>"u"?Dd(xd):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dd(ca)),{message:t})),typeof e<"u"&&(t.data=e),RS(t.code)&&(t=CS(t.code)),t)}class sx{}class ox extends sx{constructor(){super()}}class ax extends ox{constructor(e){super()}}const cx="^wss?:";function ux(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function lx(t,e){const r=ux(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Td(t){return lx(t,cx)}function hx(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Rd(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function pa(t){return Rd(t)&&"method"in t}function ns(t){return Rd(t)&&(It(t)||ot(t))}function It(t){return"result"in t}function ot(t){return"error"in t}class dx extends ax{constructor(e){super(e),this.events=new Le.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Dr(e.method,e.params||[],e.id||Ir().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{ot(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ns(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 fx=()=>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"),px=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Cd=t=>t.split("?")[0],Nd=10,gx=fx();class yx{constructor(e){if(this.url=e,this.events=new Le.exports.EventEmitter,this.registering=!1,!Td(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(dr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Td(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Od.isReactNative()?void 0:{rejectUnauthorized:!hx(e)},s=new gx(e,[],i);px()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Nr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=fa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return NS(e,Cd(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Nd&&this.events.setMaxListeners(Nd)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Cd(this.url)}`));return this.events.emit("register_error",r),r}}const Bd="wc",Fd=2,is="core",Dt=`${Bd}@2:${is}:`,wx={name:is,logger:"error"},mx={database:":memory:"},bx="crypto",Ld="client_ed25519_seed",vx=L.ONE_DAY,Ex="keychain",_x="0.3",Sx="messages",xx="0.3",Ud=L.SIX_HOURS,Ix="publisher",kd="irn",Dx="error",Md="wss://relay.walletconnect.org",Ox="relayer",Ie={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"},$x="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ax=.1,ga="2.19.2",ce={link_mode:"link_mode",relay:"relay"},ss={inbound:"inbound",outbound:"outbound"},Px="0.3",Tx="WALLETCONNECT_CLIENT_ID",jd="WALLETCONNECT_LINK_MODE_APPS",rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Rx="subscription",Cx="0.3",Nx="pairing",Bx="0.3",Xn={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Or={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ft={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Fx="history",Lx="0.3",Ux="expirer",ct={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},kx="0.3",Mx="verify-api",jx="https://verify.walletconnect.com",qd="https://verify.walletconnect.org",Qn=qd,qx=`${Qn}/v3`,zx=[jx,qd],Vx="echo",Kx="https://echo.walletconnect.com",Ot={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"},Vt={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"},pt={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"},$r={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"},Ar={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"},ei={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"},Hx=.1,Wx="event-client",Gx=86400,Yx="https://pulse.walletconnect.org/batch";function Zx(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var Jx=Zx,Xx=Jx;const zd=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")},Qx=t=>new TextEncoder().encode(t),e3=t=>new TextDecoder().decode(t);class t3{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class r3{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Vd(this,e)}}class n3{constructor(e){this.decoders=e}or(e){return Vd(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Vd=(t,e)=>new n3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class i3{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new t3(e,r,n),this.decoder=new r3(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const os=({name:t,prefix:e,encode:r,decode:n})=>new i3(t,e,r,n),ti=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Xx(r,e);return os({prefix:t,name:e,encode:n,decode:s=>zd(i(s))})},s3=(t,e,r,n)=>{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*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},o3=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Ce=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>os({prefix:e,name:t,encode(i){return o3(i,n,r)},decode(i){return s3(i,n,r,t)}}),a3=os({prefix:"\0",name:"identity",encode:t=>e3(t),decode:t=>Qx(t)});var c3=Object.freeze({__proto__:null,identity:a3});const u3=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var l3=Object.freeze({__proto__:null,base2:u3});const h3=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var d3=Object.freeze({__proto__:null,base8:h3});const f3=ti({prefix:"9",name:"base10",alphabet:"0123456789"});var p3=Object.freeze({__proto__:null,base10:f3});const g3=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),y3=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var w3=Object.freeze({__proto__:null,base16:g3,base16upper:y3});const m3=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),b3=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),v3=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),E3=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_3=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),S3=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),x3=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),I3=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),D3=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var O3=Object.freeze({__proto__:null,base32:m3,base32upper:b3,base32pad:v3,base32padupper:E3,base32hex:_3,base32hexupper:S3,base32hexpad:x3,base32hexpadupper:I3,base32z:D3});const $3=ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),A3=ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var P3=Object.freeze({__proto__:null,base36:$3,base36upper:A3});const T3=ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),R3=ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var C3=Object.freeze({__proto__:null,base58btc:T3,base58flickr:R3});const N3=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),B3=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),F3=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),L3=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var U3=Object.freeze({__proto__:null,base64:N3,base64pad:B3,base64url:F3,base64urlpad:L3});const Kd=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}"),k3=Kd.reduce((t,e,r)=>(t[r]=e,t),[]),M3=Kd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function j3(t){return t.reduce((e,r)=>(e+=k3[r],e),"")}function q3(t){const e=[];for(const r of t){const n=M3[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const z3=os({prefix:"\u{1F680}",name:"base256emoji",encode:j3,decode:q3});var V3=Object.freeze({__proto__:null,base256emoji:z3}),K3=Wd,Hd=128,H3=127,W3=~H3,G3=Math.pow(2,31);function Wd(t,e,r){e=e||[],r=r||0;for(var n=r;t>=G3;)e[r++]=t&255|Hd,t/=128;for(;t&W3;)e[r++]=t&255|Hd,t>>>=7;return e[r]=t|0,Wd.bytes=r-n+1,e}var Y3=ya,Z3=128,Gd=127;function ya(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Gd)<<i:(o&Gd)*Math.pow(2,i),i+=7}while(o>=Z3);return ya.bytes=s-n,r}var J3=Math.pow(2,7),X3=Math.pow(2,14),Q3=Math.pow(2,21),eI=Math.pow(2,28),tI=Math.pow(2,35),rI=Math.pow(2,42),nI=Math.pow(2,49),iI=Math.pow(2,56),sI=Math.pow(2,63),oI=function(t){return t<J3?1:t<X3?2:t<Q3?3:t<eI?4:t<tI?5:t<rI?6:t<nI?7:t<iI?8:t<sI?9:10},aI={encode:K3,decode:Y3,encodingLength:oI},Yd=aI;const Zd=(t,e,r=0)=>(Yd.encode(t,e,r),e),Jd=t=>Yd.encodingLength(t),wa=(t,e)=>{const r=e.byteLength,n=Jd(t),i=n+Jd(r),s=new Uint8Array(i+r);return Zd(t,s,0),Zd(r,s,n),s.set(e,i),new cI(t,r,e,s)};class cI{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Xd=({name:t,code:e,encode:r})=>new uI(t,e,r);class uI{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?wa(this.code,r):r.then(n=>wa(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Qd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),lI=Xd({name:"sha2-256",code:18,encode:Qd("SHA-256")}),hI=Xd({name:"sha2-512",code:19,encode:Qd("SHA-512")});var dI=Object.freeze({__proto__:null,sha256:lI,sha512:hI});const ef=0,fI="identity",tf=zd;var pI=Object.freeze({__proto__:null,identity:{code:ef,name:fI,encode:tf,digest:t=>wa(ef,tf(t))}});new TextEncoder,new TextDecoder;const rf={...c3,...l3,...d3,...p3,...w3,...O3,...P3,...C3,...U3,...V3};({...dI,...pI});function gI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function nf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const sf=nf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ma=nf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=gI(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yI={utf8:sf,"utf-8":sf,hex:rf.base16,latin1:ma,ascii:ma,binary:ma,...rf};function wI(t,e="utf8"){const r=yI[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var mI=Object.defineProperty,bI=(t,e,r)=>e in t?mI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$t=(t,e,r)=>bI(t,typeof e!="symbol"?e+"":e,r);class vI{constructor(e,r){this.core=e,this.logger=r,$t(this,"keychain",new Map),$t(this,"name",Ex),$t(this,"version",_x),$t(this,"initialized",!1),$t(this,"storagePrefix",Dt),$t(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),$t(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),$t(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),$t(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=U("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),$t(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=je(r,this.name)}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ao(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EI=Object.defineProperty,_I=(t,e,r)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>_I(t,typeof e!="symbol"?e+"":e,r);class SI{constructor(e,r,n){this.core=e,this.logger=r,Ne(this,"name",bx),Ne(this,"keychain"),Ne(this,"randomSessionIdentifier",ia()),Ne(this,"initialized",!1),Ne(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ne(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ne(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=wu(i);return yu(s.publicKey)}),Ne(this,"generateKeyPair",()=>{this.isInitialized();const i=C_();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ne(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=wu(s),a=this.randomSessionIdentifier;return await Mm(a,i,vx,o)}),Ne(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=N_(a,s);return this.setSymKey(c,o)}),Ne(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Xi(i);return await this.keychain.set(o,i),o}),Ne(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"encode",async(i,s,o)=>{this.isInitialized();const a=hd(o),c=dr(s);if(fd(a))return L_(c,o?.encoding);if(dd(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return B_({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ne(this,"decode",async(i,s,o)=>{this.isInitialized();const a=k_(s,o);if(fd(a)){const c=U_(s,o?.encoding);return Nr(c)}if(dd(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=F_({symKey:c,encoded:s,encoding:o?.encoding});return Nr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ne(this,"getPayloadType",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return xr(o.type)}),Ne(this,"getPayloadSenderPublicKey",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return o.senderPublicKey?Ge(o.senderPublicKey,ze):void 0}),this.core=e,this.logger=je(r,this.name),this.keychain=n||new vI(this.core,this.logger)}get context(){return He(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ld)}catch{e=ia(),await this.keychain.set(Ld,e)}return wI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xI=Object.defineProperty,II=Object.defineProperties,DI=Object.getOwnPropertyDescriptors,of=Object.getOwnPropertySymbols,OI=Object.prototype.hasOwnProperty,$I=Object.prototype.propertyIsEnumerable,ba=(t,e,r)=>e in t?xI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,AI=(t,e)=>{for(var r in e||(e={}))OI.call(e,r)&&ba(t,r,e[r]);if(of)for(var r of of(e))$I.call(e,r)&&ba(t,r,e[r]);return t},PI=(t,e)=>II(t,DI(e)),nt=(t,e,r)=>ba(t,typeof e!="symbol"?e+"":e,r);class TI extends kg{constructor(e,r){super(e,r),this.logger=e,this.core=r,nt(this,"messages",new Map),nt(this,"messagesWithoutClientAck",new Map),nt(this,"name",Sx),nt(this,"version",xx),nt(this,"initialized",!1),nt(this,"storagePrefix",Dt),nt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),nt(this,"set",async(n,i,s)=>{this.isInitialized();const o=St(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===ss.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,PI(AI({},c),{[o]:i}))}return await this.persist(),o}),nt(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),nt(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),nt(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=St(i);return typeof s[o]<"u"}),nt(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=St(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),nt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=je(e,this.name),this.core=r}get context(){return He(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,Ao(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ao(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Po(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var RI=Object.defineProperty,CI=Object.defineProperties,NI=Object.getOwnPropertyDescriptors,af=Object.getOwnPropertySymbols,BI=Object.prototype.hasOwnProperty,FI=Object.prototype.propertyIsEnumerable,va=(t,e,r)=>e in t?RI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,as=(t,e)=>{for(var r in e||(e={}))BI.call(e,r)&&va(t,r,e[r]);if(af)for(var r of af(e))FI.call(e,r)&&va(t,r,e[r]);return t},Ea=(t,e)=>CI(t,NI(e)),gt=(t,e,r)=>va(t,typeof e!="symbol"?e+"":e,r);class LI extends Mg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,gt(this,"events",new Le.exports.EventEmitter),gt(this,"name",Ix),gt(this,"queue",new Map),gt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),gt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),gt(this,"needsTransportRestart",!1),gt(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||Ud,c=Qi(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||Ir().toString(),d={topic:n,message:i,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const f=new Promise(async y=>{const g=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Ie.publish,g),y(d))};this.relayer.events.on(Ie.publish,g);const w=rr(new Promise((m,b)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(m).catch(E=>{this.logger.warn(E,E?.message),b(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await w,this.events.removeListener(Ie.publish,g)}catch(m){this.queue.set(h,Ea(as({},d),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await rr(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),gt(this,"on",(n,i)=>{this.events.on(n,i)}),gt(this,"once",(n,i)=>{this.events.once(n,i)}),gt(this,"off",(n,i)=>{this.events.off(n,i)}),gt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=je(r,this.name),this.registerEventListeners()}get context(){return He(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=Ud,prompt:u,tag:l,id:h,attestation:d,tvf:p}=e,f={method:Wn(Qi().protocol).publish,params:as({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},p),id:h};Re((r=f.params)==null?void 0:r.prompt)&&((n=f.params)==null||delete n.prompt),Re((i=f.params)==null?void 0:i.tag)&&((s=f.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const y=await this.relayer.request(f);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,Ea(as({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(Ea(as({},e),{topic:i,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Cr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var UI=Object.defineProperty,kI=(t,e,r)=>e in t?UI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hn=(t,e,r)=>kI(t,typeof e!="symbol"?e+"":e,r);class MI{constructor(){hn(this,"map",new Map),hn(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),hn(this,"get",e=>this.map.get(e)||[]),hn(this,"exists",(e,r)=>this.get(e).includes(r)),hn(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),hn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var jI=Object.defineProperty,qI=Object.defineProperties,zI=Object.getOwnPropertyDescriptors,cf=Object.getOwnPropertySymbols,VI=Object.prototype.hasOwnProperty,KI=Object.prototype.propertyIsEnumerable,_a=(t,e,r)=>e in t?jI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ri=(t,e)=>{for(var r in e||(e={}))VI.call(e,r)&&_a(t,r,e[r]);if(cf)for(var r of cf(e))KI.call(e,r)&&_a(t,r,e[r]);return t},Sa=(t,e)=>qI(t,zI(e)),ne=(t,e,r)=>_a(t,typeof e!="symbol"?e+"":e,r);class HI extends zg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ne(this,"subscriptions",new Map),ne(this,"topicMap",new MI),ne(this,"events",new Le.exports.EventEmitter),ne(this,"name",Rx),ne(this,"version",Cx),ne(this,"pending",new Map),ne(this,"cached",[]),ne(this,"initialized",!1),ne(this,"storagePrefix",Dt),ne(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ne(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"clientId"),ne(this,"batchSubscribeTopicsLimit",500),ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ne(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Qi(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),ne(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),ne(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),ne(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),ne(this,"on",(n,i)=>{this.events.on(n,i)}),ne(this,"once",(n,i)=>{this.events.once(n,i)}),ne(this,"off",(n,i)=>{this.events.off(n,i)}),ne(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),ne(this,"start",async()=>{await this.onConnect()}),ne(this,"stop",async()=>{await this.onDisconnect()}),ne(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ne(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),ne(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Cr.pulse,async()=>{await this.checkPending()}),this.events.on(rt.created,async n=>{const i=rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(rt.deleted,async n=>{const i=rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=je(r,this.name),this.clientId=""}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Qi(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=oe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i;(!n||n?.transportType===ce.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Wn(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===ce.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(l=>this.logger.warn(l))},L.toMiliseconds(L.ONE_SECOND)),a;const c=new Promise(async l=>{const h=d=>{d.topic===e&&(this.events.removeListener(rt.created,h),l(d.id))};this.events.on(rt.created,h);try{const d=await rr(new Promise((p,f)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),f(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(rt.created,h),l(d)}catch{}}),u=await rr(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await rr(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await rr(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Wn(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Sa(ri({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ri({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,ri({},r)),this.topicMap.set(r.topic,e),this.events.emit(rt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(rt.deleted,Sa(ri({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Sa(ri({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await _E(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=U("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 St(e+await this.getClientId())}}var WI=Object.defineProperty,uf=Object.getOwnPropertySymbols,GI=Object.prototype.hasOwnProperty,YI=Object.prototype.propertyIsEnumerable,xa=(t,e,r)=>e in t?WI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lf=(t,e)=>{for(var r in e||(e={}))GI.call(e,r)&&xa(t,r,e[r]);if(uf)for(var r of uf(e))YI.call(e,r)&&xa(t,r,e[r]);return t},X=(t,e,r)=>xa(t,typeof e!="symbol"?e+"":e,r);class ZI extends jg{constructor(e){super(e),X(this,"protocol","wc"),X(this,"version",2),X(this,"core"),X(this,"logger"),X(this,"events",new Le.exports.EventEmitter),X(this,"provider"),X(this,"messages"),X(this,"subscriber"),X(this,"publisher"),X(this,"name",Ox),X(this,"transportExplicitlyClosed",!1),X(this,"initialized",!1),X(this,"connectionAttemptInProgress",!1),X(this,"relayUrl"),X(this,"projectId"),X(this,"packageName"),X(this,"bundleId"),X(this,"hasExperiencedNetworkDisruption",!1),X(this,"pingTimeout"),X(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),X(this,"reconnectTimeout"),X(this,"connectPromise"),X(this,"reconnectInProgress",!1),X(this,"requestsInFlight",[]),X(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),X(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Ir().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),X(this,"resetPingTimeout",()=>{ji()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),X(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),X(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Ie.connect)}),X(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),X(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Ie.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),X(this,"registerProviderListeners",()=>{this.provider.on(at.payload,this.onPayloadHandler),this.provider.on(at.connect,this.onConnectHandler),this.provider.on(at.disconnect,this.onDisconnectHandler),this.provider.on(at.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je(e.logger,this.name):Pt(Is({level:e.logger||Dx})),this.messages=new TI(this.logger,e.core),this.subscriber=new HI(this,this.logger),this.publisher=new LI(this,this.logger),this.relayUrl=e?.relayUrl||Md,this.projectId=e.projectId,sE()?this.packageName=eh():oE()&&(this.bundleId=eh()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return He(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:ce.relay},ss.outbound)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const 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,h)=>{a=await this.subscriber.subscribe(e,lf({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await rr(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(e).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Sd())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=me(L.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,ss.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,s),await rr(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(at.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(at.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(ji())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dx(new yx(hE({sdkVersion:ga,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),pa(e)){if(!e.method.endsWith($x))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:ce.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(lf({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ns(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ss.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const r=da(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(at.payload,this.onPayloadHandler),this.provider.off(at.connect,this.onConnectHandler),this.provider.off(at.disconnect,this.onDisconnectHandler),this.provider.off(at.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Sd();xS(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.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},L.toMiliseconds(Ax)))))}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function JI(){}function hf(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 df(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ff(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XI="[object RegExp]",QI="[object String]",e8="[object Number]",t8="[object Boolean]",pf="[object Arguments]",r8="[object Symbol]",n8="[object Date]",i8="[object Map]",s8="[object Set]",o8="[object Array]",a8="[object Function]",c8="[object ArrayBuffer]",Ia="[object Object]",u8="[object Error]",l8="[object DataView]",h8="[object Uint8Array]",d8="[object Uint8ClampedArray]",f8="[object Uint16Array]",p8="[object Uint32Array]",g8="[object BigUint64Array]",y8="[object Int8Array]",w8="[object Int16Array]",m8="[object Int32Array]",b8="[object BigInt64Array]",v8="[object Float32Array]",E8="[object Float64Array]";function _8(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function S8(t,e,r){return ni(t,e,void 0,void 0,void 0,void 0,r)}function ni(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return ii(t,e,s,o)}return ii(t,e,s,o)}function ii(t,e,r,n){if(Object.is(t,e))return!0;let i=ff(t),s=ff(e);if(i===pf&&(i=Ia),s===pf&&(s=Ia),i!==s)return!1;switch(i){case QI:return t.toString()===e.toString();case e8:{const c=t.valueOf(),u=e.valueOf();return _8(c,u)}case t8:case n8:case r8:return Object.is(t.valueOf(),e.valueOf());case XI:return t.source===e.source&&t.flags===e.flags;case a8:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case i8:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ni(u,e.get(c),c,t,e,r,n))return!1;return!0}case s8:{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 h=c[l],d=u.findIndex(p=>ni(h,p,void 0,t,e,r,n));if(d===-1)return!1;u.splice(d,1)}return!0}case o8:case h8:case d8:case f8:case p8:case g8:case y8:case w8:case m8:case b8:case v8:case E8:{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(!ni(t[c],e[c],c,t,e,r,n))return!1;return!0}case c8:return t.byteLength!==e.byteLength?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case l8:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case u8:return t.name===e.name&&t.message===e.message;case Ia:{if(!(ii(t.constructor,e.constructor,r,n)||hf(t)&&hf(e)))return!1;const c=[...Object.keys(t),...df(t)],u=[...Object.keys(e),...df(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!ni(d,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function x8(t,e){return S8(t,e,JI)}var I8=Object.defineProperty,gf=Object.getOwnPropertySymbols,D8=Object.prototype.hasOwnProperty,O8=Object.prototype.propertyIsEnumerable,Da=(t,e,r)=>e in t?I8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yf=(t,e)=>{for(var r in e||(e={}))D8.call(e,r)&&Da(t,r,e[r]);if(gf)for(var r of gf(e))O8.call(e,r)&&Da(t,r,e[r]);return t},Je=(t,e,r)=>Da(t,typeof e!="symbol"?e+"":e,r);class Pr extends qg{constructor(e,r,n,i=Dt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,Je(this,"map",new Map),Je(this,"version",Px),Je(this,"cached",[]),Je(this,"initialized",!1),Je(this,"getKey"),Je(this,"storagePrefix",Dt),Je(this,"recentlyDeleted",[]),Je(this,"recentlyDeletedLimit",200),Je(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):tS(o)?this.map.set(o.id,o):rS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Je(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())}),Je(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Je(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>x8(a[c],o[c]))):this.values)),Je(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=yf(yf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Je(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=je(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $8=Object.defineProperty,A8=(t,e,r)=>e in t?$8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y=(t,e,r)=>A8(t,typeof e!="symbol"?e+"":e,r);class P8{constructor(e,r){this.core=e,this.logger=r,Y(this,"name",Nx),Y(this,"version",Bx),Y(this,"events",new Le.exports),Y(this,"pairings"),Y(this,"initialized",!1),Y(this,"storagePrefix",Dt),Y(this,"ignoredPayloadTypes",[jt]),Y(this,"registeredMethods",[]),Y(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Y(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Y(this,"create",async n=>{this.isInitialized();const i=ia(),s=await this.core.crypto.setSymKey(i),o=me(L.FIVE_MINUTES),a={protocol:kd},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=gd({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(Or.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:u}}),Y(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Ot.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=pd(n.uri);i.props.properties.topic=s,i.addTrace(Ot.pairing_uri_validation_success),i.addTrace(Ot.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Ot.existing_pairing),l.active)throw i.setError(Vt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Ot.pairing_not_expired)}const h=c||me(L.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,d),i.addTrace(Ot.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Or.create,d),i.addTrace(Ot.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Ot.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Vt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(Vt.subscribe_pairing_topic_failure),p}return i.addTrace(Ot.subscribe_pairing_topic_success),d}),Y(this,"activate",async({topic:n})=>{this.isInitialized();const i=me(L.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Y(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=br();this.events.once(Q("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Y(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Y(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Y(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Y(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",oe("USER_DISCONNECTED")),await this.deletePairing(i))}),Y(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return gd({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Y(this,"sendRequest",async(n,i,s)=>{const o=Dr(i,s),a=await this.core.crypto.encode(n,o),c=Xn[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Y(this,"sendResult",async(n,i,s)=>{const o=da(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"sendError",async(n,i,s)=>{const o=fa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c]?Xn[c].res:Xn.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,oe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Y(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>nr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Y(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Y(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Y(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Or.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{It(i)?this.events.emit(Q("pairing_ping",s),{}):ot(i)&&this.events.emit(Q("pairing_ping",s),{error:i.error})},500)}),Y(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Or.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=oe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Y(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(oe("WC_METHOD_UNSUPPORTED",n))}),Y(this,"isValidPair",(n,i)=>{var s;if(!Ze(n)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!eS(n.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}const o=pd(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Vt.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Y(this,"isValidPing",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidDisconnect",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidPairingTopic",async n=>{if(!pe(n,!1)){const{message:i}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(nr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=U("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=je(r,this.name),this.pairings=new Pr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return He(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==ce.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);pa(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ns(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(ct.expired,async e=>{const{topic:r}=ih(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Or.expire,{topic:r}))})}}var T8=Object.defineProperty,R8=(t,e,r)=>e in t?T8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>R8(t,typeof e!="symbol"?e+"":e,r);class C8 extends Ug{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new Le.exports.EventEmitter),Be(this,"name",Fx),Be(this,"version",Lx),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Dt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:me(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ft.created,o)}),Be(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=ot(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(ft.updated,i))}),Be(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),Be(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(ft.deleted,s)}}),this.persist()}),Be(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Be(this,"on",(n,i)=>{this.events.on(n,i)}),Be(this,"once",(n,i)=>{this.events.once(n,i)}),Be(this,"off",(n,i)=>{this.events.off(n,i)}),Be(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:Dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ft.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ft.created,e=>{const r=ft.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.updated,e=>{const r=ft.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.deleted,e=>{const r=ft.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Cr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ft.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var N8=Object.defineProperty,B8=(t,e,r)=>e in t?N8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ke=(t,e,r)=>B8(t,typeof e!="symbol"?e+"":e,r);class F8 extends Vg{constructor(e,r){super(e,r),this.core=e,this.logger=r,ke(this,"expirations",new Map),ke(this,"events",new Le.exports.EventEmitter),ke(this,"name",Ux),ke(this,"version",kx),ke(this,"cached",[]),ke(this,"initialized",!1),ke(this,"storagePrefix",Dt),ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ke(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),ke(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(ct.created,{target:s,expiration:o})}),ke(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),ke(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(ct.deleted,{target:i,expiration:s})}}),ke(this,"on",(n,i)=>{this.events.on(n,i)}),ke(this,"once",(n,i)=>{this.events.once(n,i)}),ke(this,"off",(n,i)=>{this.events.off(n,i)}),ke(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(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 dE(e);if(typeof e=="number")return fE(e);const{message:r}=U("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(ct.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;L.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ct.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Cr.pulse,()=>this.checkExpirations()),this.events.on(ct.created,e=>{const r=ct.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.expired,e=>{const r=ct.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.deleted,e=>{const r=ct.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var L8=Object.defineProperty,U8=(t,e,r)=>e in t?L8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e,r)=>U8(t,typeof e!="symbol"?e+"":e,r);class k8 extends Kg{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,ge(this,"name",Mx),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",qx),ge(this,"storagePrefix",Dt),ge(this,"version",Fd),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async i=>{if(!Cn()||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=_n(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",g),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",f,{signal:this.abortController.signal});const g=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(Hs(m.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",g),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};u.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),ge(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(Hs(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)}),ge(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(L.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}),ge(this,"getVerifyUrl",i=>{let s=i||Qn;return zx.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Qn}`),s=Qn),s}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(L.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)}}),ge(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(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")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(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}),ge(this,"validateAttestation",(i,s)=>{const o=j_(i,s.publicKey),a={hasExpired:L.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=je(r,this.name),this.abortController=new AbortController,this.isDevEnv=To(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return He(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var M8=Object.defineProperty,j8=(t,e,r)=>e in t?M8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wf=(t,e,r)=>j8(t,typeof e!="symbol"?e+"":e,r);class q8 extends Hg{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,wf(this,"context",Vx),wf(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${Kx}/${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=je(r,this.context)}}var z8=Object.defineProperty,mf=Object.getOwnPropertySymbols,V8=Object.prototype.hasOwnProperty,K8=Object.prototype.propertyIsEnumerable,Oa=(t,e,r)=>e in t?z8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,si=(t,e)=>{for(var r in e||(e={}))V8.call(e,r)&&Oa(t,r,e[r]);if(mf)for(var r of mf(e))K8.call(e,r)&&Oa(t,r,e[r]);return t},De=(t,e,r)=>Oa(t,typeof e!="symbol"?e+"":e,r);class H8 extends Wg{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,De(this,"context",Wx),De(this,"storagePrefix",Dt),De(this,"storageVersion",Hx),De(this,"events",new Map),De(this,"shouldPersist",!1),De(this,"init",async()=>{if(!To())try{const i={eventId:oh(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rh(this.core.relayer.protocol,this.core.relayer.version,ga)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),De(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=oh(),l=this.core.projectId||"",h=Date.now(),d=si({eventId:u,timestamp:h,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}),De(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 si(si({},a),this.setMethods(a.eventId))}),De(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),De(this,"setEventListeners",()=>{this.core.heartbeat.on(Cr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(i.timestamp)>Gx&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),De(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),De(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)}),De(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)}),De(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),De(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,si(si({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),De(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)}}),De(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Yx}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ga}${s}`,{method:"POST",body:JSON.stringify(i)})}),De(this,"getAppDomain",()=>th().url),this.logger=je(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var W8=Object.defineProperty,bf=Object.getOwnPropertySymbols,G8=Object.prototype.hasOwnProperty,Y8=Object.prototype.propertyIsEnumerable,$a=(t,e,r)=>e in t?W8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vf=(t,e)=>{for(var r in e||(e={}))G8.call(e,r)&&$a(t,r,e[r]);if(bf)for(var r of bf(e))Y8.call(e,r)&&$a(t,r,e[r]);return t},ae=(t,e,r)=>$a(t,typeof e!="symbol"?e+"":e,r);class Aa extends Ng{constructor(e){var r;super(e),ae(this,"protocol",Bd),ae(this,"version",Fd),ae(this,"name",is),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new Le.exports.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ce.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Md,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Is({level:typeof e?.logger=="string"&&e.logger?e.logger:wx.logger,name:is}),{logger:s,chunkLoggerController:o}=Tg({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=je(s,this.name),this.heartbeat=new ms,this.crypto=new SI(this,this.logger,e?.keychain),this.history=new C8(this,this.logger),this.expirer=new F8(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ng(vf(vf({},mx),e?.storageOptions)),this.relayer=new ZI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new P8(this,this.logger),this.verify=new k8(this,this.logger,this.storage),this.echoClient=new q8(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new H8(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Aa(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(Tx,n),r}get context(){return He(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(jd,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(jd)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Pa=Aa,Ef="wc",_f=2,Sf="client",Ta=`${Ef}@${_f}:${Sf}:`,Ra={name:Sf,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},xf="WALLETCONNECT_DEEPLINK_CHOICE",Z8="proposal",If="Proposal expired",J8="session",dn=L.SEVEN_DAYS,X8="engine",Oe={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},Ca={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},At={idle:"IDLE",active:"ACTIVE"},Df={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Q8="request",eD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tD="wc",rD="auth",nD="authKeys",iD="pairingTopics",sD="requests",cs=`${tD}@${1.5}:${rD}:`,us=`${cs}:PUB_KEY`;var oD=Object.defineProperty,aD=Object.defineProperties,cD=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,Na=(t,e,r)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ie=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&Na(t,r,e[r]);if(Of)for(var r of Of(e))lD.call(e,r)&&Na(t,r,e[r]);return t},Ve=(t,e)=>aD(t,cD(e)),R=(t,e,r)=>Na(t,typeof e!="symbol"?e+"":e,r);class hD extends Jg{constructor(e){super(e),R(this,"name",X8),R(this,"events",new Le.exports),R(this,"initialized",!1),R(this,"requestQueue",{state:At.idle,queue:[]}),R(this,"sessionRequestQueue",{state:At.idle,queue:[]}),R(this,"requestQueueDelay",L.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(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(Oe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Ve(ie({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,d=!1;try{if(l){const D=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),D}if(!l||!d){const{topic:D,uri:S}=await this.client.core.pairing.create();l=D,h=S}if(!l){const{message:D}=U("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const p=await this.client.core.crypto.generateKeyPair(),f=Oe.wc_sessionPropose.req.ttl||L.FIVE_MINUTES,y=me(f),g=Ve(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:kd}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:xt()}),w=Q("session_connect",g.id),{reject:m,resolve:b,done:E}=br(f,If),$=({id:D})=>{D===g.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(g.id),this.events.emit(w,{error:{message:If,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(w,({error:D,session:S})=>{this.client.events.off("proposal_expire",$),D?m(D):S&&b(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:g,throwOnFailedPublish:!0,clientRpcId:g.id}),await this.setProposal(g.id,g),{uri:h,approval:E}}),R(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),R(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[pt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError($r.no_internet_connection),x}try{await this.isValidProposalId(r?.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError($r.proposal_not_found),x}try{await this.isValidApprove(r)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError($r.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:y,requiredNamespaces:g,optionalNamespaces:w}=p;let m=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:f});m||(m=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:pt.session_approve_started,properties:{topic:f,trace:[pt.session_approve_started,pt.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),E=y.publicKey,$=await this.client.core.crypto.generateSharedKey(b,E),D=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:b,metadata:this.client.metadata},expiry:me(dn)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),S=ce.relay;m.addTrace(pt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:S})}catch(x){throw m.setError($r.subscribe_session_topic_failure),x}m.addTrace(pt.subscribe_session_topic_success);const A=Ve(ie({},D),{topic:$,requiredNamespaces:g,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:b,transportType:ce.relay});await this.client.session.set($,A),m.addTrace(pt.store_session);try{m.addTrace(pt.publishing_session_settle),await this.sendRequest({topic:$,method:"wc_sessionSettle",params:D,throwOnFailedPublish:!0}).catch(x=>{throw m?.setError($r.session_settle_publish_failure),x}),m.addTrace(pt.session_settle_publish_success),m.addTrace(pt.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(x=>{throw m?.setError($r.session_approve_publish_failure),x}),m.addTrace(pt.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete($,oe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),x}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:y.metadata}),await this.client.proposal.delete(a,oe("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry($,me(dn)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),R(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i,rpcOpts:Oe.wc_sessionPropose.reject}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED")))}),R(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=br(),c=xt(),u=Ir().toString(),l=this.client.session.get(n).namespaces;return this.events.once(Q("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:l}),a(h)}),{acknowledged:s}}),R(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=xt(),{done:s,resolve:o,reject:a}=br();return this.events.once(Q("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,me(dn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=Oe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const c=xt(),u=Ir().toString(),{done:l,resolve:h,reject:d}=br(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:w,result:m})=>{w?d(w):h(m)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const y={request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},g=this.shouldSetTVF(p,y);return await Promise.all([new Promise(async w=>{await this.sendRequest(ie({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:y,expiry:o,throwOnFailedPublish:!0},g&&{tvf:this.getTVFParams(c,y)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await mE(this.client.core.storage,xf);await gE({id:c,topic:s,wcDeepLink:b})}w()}),l()]).then(w=>w[2])}),R(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);It(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):ot(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),R(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=xt(),s=Ir().toString(),{done:o,resolve:a,reject:c}=br();this.events.once(Q("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Ir().toString(),a=xt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:oe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=U("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>X_(n,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?ce.link_mode:ce.relay;o===ce.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:p,nbf:f,methods:y=[],expiry:g}=r,w=[...r.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const E=await this.client.core.crypto.generateKeyPair(),$=Xi(E);if(await Promise.all([this.client.auth.authKeys.set(us,{responseTopic:$,publicKey:E}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:m})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),y.length>0){const{namespace:P}=Mi(a[0]);let N=u2(P,"request",y);Vi(w)&&(N=h2(N,w.pop())),w.push(N)}const D=g&&g>Oe.wc_sessionAuthenticate.req.ttl?g:Oe.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(D)},A={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},x={requiredNamespaces:{},optionalNamespaces:A,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(Oe.wc_sessionPropose.req.ttl),id:xt()},{done:k,resolve:C,reject:B}=br(D,"Request expired"),j=xt(),I=Q("session_connect",x.id),_=Q("session_request",j),v=async({error:P,session:N})=>{this.events.off(_,O),P?B(P):N&&C({session:N})},O=async P=>{var N,F,M;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),P.error){const W=oe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===W.code?void 0:(this.events.off(I,v),B(P.error.message))}await this.deleteProposal(x.id),this.events.off(I,v);const{cacaos:z,responder:q}=P.result,V=[],K=[];for(const W of z){await Eh({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(oe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ye}=W,ue=Vi(ye.resources),le=[Lo(ye.iss)],$e=zi(ye.iss);if(ue){const Me=xh(ue),Kt=Ih(ue);V.push(...Me),le.push(...Kt)}for(const Me of le)K.push(`${Me}:${$e}`)}const ee=await this.client.core.crypto.generateSharedKey(E,q.publicKey);let G;V.length>0&&(G={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:me(dn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:yd([...new Set(V)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(ee,{transportType:o}),await this.client.session.set(ee,G),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:q.metadata}),G=this.client.session.get(ee)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(F=q.metadata.redirect)!=null&&F.linkMode&&(M=q.metadata.redirect)!=null&&M.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ee,{transportType:ce.link_mode})),C({auths:z,session:G})};this.events.once(I,v),this.events.once(_,O);let T;try{if(s){const P=Dr("wc_sessionAuthenticate",S,j);this.client.core.history.set(m,P);const N=await this.client.core.crypto.encode("",P,{type:Vn,encoding:ar});T=es(n,m,N)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:x,expiry:Oe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:x.id})])}catch(P){throw this.events.off(I,v),this.events.off(_,O),P}return await this.setProposal(x.id,x),await this.setAuthRequest(j,{request:Ve(ie({},S),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:T??b,response:k}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ar.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw s.setError(ei.no_internet_connection),g}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(ei.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ce.relay;a===ce.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=Xi(c),h={type:jt,receiverPublicKey:c,senderPublicKey:u},d=[],p=[];for(const g of i){if(!await Eh({cacao:g,projectId:this.client.core.projectId})){s.setError(ei.invalid_cacao);const $=oe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:$,encodeOpts:h}),new Error($.message)}s.addTrace(Ar.cacaos_verified);const{p:w}=g,m=Vi(w.resources),b=[Lo(w.iss)],E=zi(w.iss);if(m){const $=xh(m),D=Ih(m);d.push(...$),b.push(...D)}for(const $ of b)p.push(`${$}:${E}`)}const f=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Ar.create_authenticated_session_topic);let y;if(d?.length>0){y={topic:f,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(dn),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:yd([...new Set(d)],[...new Set(p)]),transportType:a},s.addTrace(Ar.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(g){throw s.setError(ei.subscribe_authenticated_session_topic_failure),g}s.addTrace(Ar.subscribe_authenticated_session_topic_success),await this.client.session.set(f,y),s.addTrace(Ar.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ar.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(g){throw s.setError(ei.authenticated_session_approve_publish_failure),g}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:y}}),R(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Xi(o),u={type:jt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Oe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return _h(n,i)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),R(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),R(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,oe("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(xf).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,oe("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=At.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),R(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError($r.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,oe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=At.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),R(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),R(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,me(Oe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),R(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=ce.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(Oe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),R(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,d=Dr(i,s,c);let p;const f=!!l;try{const w=f?ar:dt;p=await this.client.core.crypto.encode(n,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),w}let y;if(eD.includes(i)){const w=St(JSON.stringify(d)),m=St(p);y=await this.client.core.verify.register({id:m,decryptedId:w})}const g=Oe[i].req;if(g.attestation=y,o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(n,d),f){const w=es(l,n,p);await global.Linking.openURL(w,this.client.name)}else{const w=Oe[i].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Ve(ie({},h),{correlationId:d.id}),u?(w.internal=Ve(ie({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,w)):this.client.core.relayer.publish(n,p,w).catch(m=>this.client.logger.error(m))}return d.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=da(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),f}let d,p;try{d=await this.client.core.history.get(i,n);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(n,f.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),f}if(h){const f=es(c,i,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,y=Oe[f].res;y.tvf=Ve(ie({},p),{correlationId:n}),o?(y.internal=Ve(ie({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,y)):this.client.core.relayer.publish(i,l,y).catch(g=>this.client.logger.error(g))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=fa(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=es(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||Oe[p].res;this.client.core.relayer.publish(i,l,f)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;nr(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{nr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===At.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=At.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=At.idle}),R(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=U("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),R(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Vt.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||me(Oe.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:n,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:St(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Ot.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Oe.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(It(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const 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:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(ot(n)){await this.client.proposal.delete(s,oe("USER_DISCONNECTED"));const o=Q("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),R(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=n.params,p=[...this.pendingSessions.values()].find(g=>g.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const f=this.client.proposal.get(p.proposalId),y=Ve(ie(ie(ie({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:ce.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Q("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;It(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Q("session_approve",i),{})):ot(n)&&(await this.client.session.delete(r,oe("USER_DISCONNECTED")),this.events.emit(Q("session_approve",i),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Yn.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:oe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:r},i));try{Yn.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Yn.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=Q("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_update",i),{}):ot(n)&&this.events.emit(Q("session_update",i),{error:n.error})}),R(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(dn)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=Q("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_extend",i),{}):ot(n)&&this.events.emit(Q("session_extend",i),{error:n.error})}),R(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=Q("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);It(n)?this.events.emit(Q("session_ping",i),{}):ot(n)&&this.events.emit(Q("session_ping",i),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Ie.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:oe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),R(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:d}=a;try{await this.isValidRequest(ie({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:St(JSON.stringify(Dr("wc_sessionRequest",d,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(y),l===ce.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=Q("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Yn.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ie({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Yn.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,d=await this.getVerifyContext({attestationId:o,hash:St(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===ce.link_mode&&(n=u.metadata.redirect)!=null&&n.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,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:jt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Oe.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=At.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=Q("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Q("session_request",s.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===At.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=At.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:Dr("wc_sessionPropose",Ve(ie({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),R(this,"isValidConnect",async r=>{if(!Ze(r)){const{message:u}=U("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Re(n)||await this.isValidPairingTopic(n),!lS(c,!0)){const{message:u}=U("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Re(i)&&ts(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Re(s)&&ts(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,n)=>{const i=uS(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ze(r))throw new Error(U("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),u=oa(i,"approve()");if(u)throw new Error(u.message);const l=Ed(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!pe(s,!0)){const{message:h}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Ze(r)){const{message:s}=U("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!dS(i)){const{message:s}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ze(r)){const{message:u}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!bd(n)){const{message:u}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=nS(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=oa(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(nr(o)){const{message:u}=U("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ze(r)){const{message:c}=U("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=oa(i,"update()");if(o)throw new Error(o.message);const a=Ed(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async r=>{if(!Ze(r)){const{message:c}=U("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!vd(a,s)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!fS(i)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!yS(a,s,i.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!vS(o,Ca)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ca.min} and ${Ca.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ze(r)){const{message:o}=U("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!pS(s)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async r=>{if(!Ze(r)){const{message:a}=U("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!vd(o,s)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!gS(i)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!wS(o,s,i.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!pe(i,!1))throw new Error("uri is required parameter");if(!pe(s,!1))throw new Error("domain is required parameter");if(!pe(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Mi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Mi(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Qn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ce.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:n,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}),R(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=U("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),R(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=U("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),R(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,d;return!r||n!==ce.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=r?.redirect)==null?void 0:l.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=sh(r,"topic")||"",i=decodeURIComponent(sh(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:ce.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),R(this,"registerLinkModeListeners",async()=>{var r;if(To()||tr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),R(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(Df).includes(i.method)}),R(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return Ve(ie({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(r,n)=>{try{const i=Df[r];if(typeof n=="string")return[n];const s=n[i.key];if(Gn(s))return r==="solana_signAllTransactions"?s.map(o=>YE(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(us)?this.client.auth.authKeys.get(us):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===ce.link_mode?ar:dt});pa(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:St(n)})):ns(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ct.expired,async e=>{const{topic:r,id:n}=ih(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,U("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,U("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Or.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Or.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!pe(e,!1)){const{message:r}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!pe(e,!1)){const{message:r}=U("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=U("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=U("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(pe(e,!1)){const{message:r}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!hS(e)){const{message:r}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=U("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class dD extends Pr{constructor(e,r){super(e,r,Z8,Ta),this.core=e,this.logger=r}}class $f extends Pr{constructor(e,r){super(e,r,J8,Ta),this.core=e,this.logger=r}}class fD extends Pr{constructor(e,r){super(e,r,Q8,Ta,n=>n.id),this.core=e,this.logger=r}}class pD extends Pr{constructor(e,r){super(e,r,nD,cs,()=>us),this.core=e,this.logger=r}}class gD extends Pr{constructor(e,r){super(e,r,iD,cs),this.core=e,this.logger=r}}class yD extends Pr{constructor(e,r){super(e,r,sD,cs,n=>n.id),this.core=e,this.logger=r}}var wD=Object.defineProperty,mD=(t,e,r)=>e in t?wD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ba=(t,e,r)=>mD(t,typeof e!="symbol"?e+"":e,r);class bD{constructor(e,r){this.core=e,this.logger=r,Ba(this,"authKeys"),Ba(this,"pairingTopics"),Ba(this,"requests"),this.authKeys=new pD(this.core,this.logger),this.pairingTopics=new gD(this.core,this.logger),this.requests=new yD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var vD=Object.defineProperty,ED=(t,e,r)=>e in t?vD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z=(t,e,r)=>ED(t,typeof e!="symbol"?e+"":e,r);class Fa extends Zg{constructor(e){super(e),Z(this,"protocol",Ef),Z(this,"version",_f),Z(this,"name",Ra.name),Z(this,"metadata"),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Le.exports.EventEmitter),Z(this,"engine"),Z(this,"session"),Z(this,"proposal"),Z(this,"pendingRequest"),Z(this,"auth"),Z(this,"signConfig"),Z(this,"on",(n,i)=>this.events.on(n,i)),Z(this,"once",(n,i)=>this.events.once(n,i)),Z(this,"off",(n,i)=>this.events.off(n,i)),Z(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Z(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Z(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Z(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Z(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ra.name,this.metadata=cE(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Pt(Is({level:e?.logger||Ra.logger}));this.core=e?.core||new Pa(e),this.logger=je(r,this.name),this.session=new $f(this.core,this.logger),this.proposal=new dD(this.core,this.logger),this.pendingRequest=new fD(this.core,this.logger),this.engine=new hD(this),this.auth=new bD(this.core,this.logger)}static async init(e){const r=new Fa(e);return await r.initialize(),r}get context(){return He(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},L.toMiliseconds(L.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const _D=$f,SD=Fa;class xD extends Le.exports{constructor(){super()}}class Af{constructor(e){this.opts=e}}class Pf{constructor(e){this.client=e}}var ID=Object.defineProperty,DD=Object.defineProperties,OD=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,$D=Object.prototype.hasOwnProperty,AD=Object.prototype.propertyIsEnumerable,Rf=(t,e,r)=>e in t?ID(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,PD=(t,e)=>{for(var r in e||(e={}))$D.call(e,r)&&Rf(t,r,e[r]);if(Tf)for(var r of Tf(e))AD.call(e,r)&&Rf(t,r,e[r]);return t},TD=(t,e)=>DD(t,OD(e));class RD extends Pf{constructor(e){super(e),this.init=async()=>{this.signClient=await SD.init({core:this.client.core,metadata:this.client.metadata,signConfig:this.client.signConfig}),this.signClient.core.eventClient.init().catch(r=>{this.client.logger.warn(r)})},this.pair=async r=>{await this.client.core.pairing.pair(r)},this.approveSession=async r=>{const{topic:n,acknowledged:i}=await this.signClient.approve(TD(PD({},r),{id:r.id,namespaces:r.namespaces,sessionProperties:r.sessionProperties,sessionConfig:r.sessionConfig}));return await i(),this.signClient.session.get(n)},this.rejectSession=async r=>await this.signClient.reject(r),this.updateSession=async r=>await this.signClient.update(r),this.extendSession=async r=>await this.signClient.extend(r),this.respondSessionRequest=async r=>await this.signClient.respond(r),this.disconnectSession=async r=>await this.signClient.disconnect(r),this.emitSessionEvent=async r=>await this.signClient.emit(r),this.getActiveSessions=()=>this.signClient.session.getAll().reduce((r,n)=>(r[n.topic]=n,r),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.approveSessionAuthenticate=async r=>await this.signClient.approveSessionAuthenticate(r),this.rejectSessionAuthenticate=async r=>await this.signClient.rejectSessionAuthenticate(r),this.formatAuthMessage=r=>this.signClient.formatAuthMessage(r),this.registerDeviceToken=r=>this.client.core.echoClient.registerDeviceToken(r),this.on=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"on"),this.client.events.on(r,n)),this.once=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"once"),this.client.events.once(r,n)),this.off=(r,n)=>(this.setEvent(r,"off"),this.client.events.off(r,n)),this.removeListener=(r,n)=>(this.setEvent(r,"removeListener"),this.client.events.removeListener(r,n)),this.onSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onSessionProposal=r=>{this.client.events.emit("session_proposal",r)},this.onSessionDelete=r=>{this.client.events.emit("session_delete",r)},this.onProposalExpire=r=>{this.client.events.emit("proposal_expire",r)},this.onSessionRequestExpire=r=>{this.client.events.emit("session_request_expire",r)},this.onSessionRequestAuthenticate=r=>{this.client.events.emit("session_authenticate",r)},this.setEvent=(r,n)=>{switch(r){case"session_request":this.signClient.events[n]("session_request",this.onSessionRequest);break;case"session_proposal":this.signClient.events[n]("session_proposal",this.onSessionProposal);break;case"session_delete":this.signClient.events[n]("session_delete",this.onSessionDelete);break;case"proposal_expire":this.signClient.events[n]("proposal_expire",this.onProposalExpire);break;case"session_request_expire":this.signClient.events[n]("session_request_expire",this.onSessionRequestExpire);break;case"session_authenticate":this.signClient.events[n]("session_authenticate",this.onSessionRequestAuthenticate);break}},this.signClient={}}}const CD={decryptMessage:async t=>{const e={core:new Pa({storageOptions:t.storageOptions,storage:t.storage})};await e.core.crypto.init();const r=e.core.crypto.decode(t.topic,t.encryptedMessage);return e.core=null,r},getMetadata:async t=>{const e={core:new Pa({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new _D(e.core,e.core.logger),await e.sessionStore.init();const r=e.sessionStore.get(t.topic),n=r?.peer.metadata;return e.core=null,e.sessionStore=null,n}},Cf=class extends Af{constructor(t){super(t),this.events=new Le.exports,this.on=(e,r)=>this.engine.on(e,r),this.once=(e,r)=>this.engine.once(e,r),this.off=(e,r)=>this.engine.off(e,r),this.removeListener=(e,r)=>this.engine.removeListener(e,r),this.pair=async e=>{try{return await this.engine.pair(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(r){throw this.logger.error(r.message),r}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(r){throw this.logger.error(r.message),r}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(r){throw this.logger.error(r.message),r}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(r){throw this.logger.error(r.message),r}},this.getActiveSessions=()=>{try{return this.engine.getActiveSessions()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionProposals=()=>{try{return this.engine.getPendingSessionProposals()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.registerDeviceToken=e=>{try{return this.engine.registerDeviceToken(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSessionAuthenticate=e=>{try{return this.engine.approveSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSessionAuthenticate=e=>{try{return this.engine.rejectSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(r){throw this.logger.error(r.message),r}},this.metadata=t.metadata,this.name=t.name||ls,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new RD(this)}static async init(t){const e=new Cf(t);return await e.initialize(),e}async initialize(){this.logger.trace("Initialized");try{await this.engine.init(),this.logger.info("WalletKit Initialization Success")}catch(t){throw this.logger.info("WalletKit Initialization Failure"),this.logger.error(t.message),t}}};let La=Cf;La.notifications=CD;const ND=La;Fe.CLIENT_CONTEXT=ls,Fe.CLIENT_STORAGE_OPTIONS=Yf,Fe.CLIENT_STORAGE_PREFIX=Gf,Fe.IWalletKit=Af,Fe.IWalletKitEngine=Pf,Fe.IWalletKitEvents=xD,Fe.PROTOCOL=Za,Fe.PROTOCOL_VERSION=Wf,Fe.REQUEST_CONTEXT=Zf,Fe.WalletKit=ND,Fe.default=La,Object.defineProperty(Fe,"__esModule",{value:!0})});
|
|
39
|
+
***************************************************************************** */var ua=function(t,e){return ua=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},ua(t,e)};function BS(t,e){ua(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var la=function(){return la=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},la.apply(this,arguments)};function FS(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function LS(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function US(t,e){return function(r,n){e(r,n,t)}}function kS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function MS(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function jS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=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 r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function qS(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function zS(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ha(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function $d(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function VS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($d(arguments[e]));return t}function KS(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Jn(t){return this instanceof Jn?(this.v=t,this):new Jn(t)}function HS(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){n[d]&&(i[d]=function(p){return new Promise(function(f,y){s.push([d,p,f,y])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof Jn?Promise.resolve(d.value.v).then(u,l):h(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function WS(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Jn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function GS(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof ha=="function"?ha(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function YS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ZS(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function JS(t){return t&&t.__esModule?t:{default:t}}function XS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function QS(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var ex=Object.freeze({__proto__:null,__extends:BS,get __assign(){return la},__rest:FS,__decorate:LS,__param:US,__metadata:kS,__awaiter:MS,__generator:jS,__createBinding:qS,__exportStar:zS,__values:ha,__read:$d,__spread:VS,__spreadArrays:KS,__await:Jn,__asyncGenerator:HS,__asyncDelegator:WS,__asyncValues:GS,__makeTemplateObject:YS,__importStar:ZS,__importDefault:JS,__classPrivateFieldGet:XS,__classPrivateFieldSet:QS}),tx=ka(ex),qt={},Ad;function rx(){if(Ad)return qt;Ad=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.isBrowserCryptoAvailable=qt.getSubtleCrypto=qt.getBrowerCrypto=void 0;function t(){return yt?.crypto||yt?.msCrypto||{}}qt.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qt.isBrowserCryptoAvailable=r,qt}var zt={},Pd;function nx(){if(Pd)return zt;Pd=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.isBrowser=zt.isNode=zt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zt.isNode=e;function r(){return!t()&&!e()}return zt.isBrowser=r,zt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=tx;e.__exportStar(rx(),t),e.__exportStar(nx(),t)})(Od);function xt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ir(t=6){return BigInt(xt(t))}function Dr(t,e,r){return{id:r||xt(),jsonrpc:"2.0",method:t,params:e}}function da(t,e){return{id:t,jsonrpc:"2.0",result:e}}function fa(t,e,r){return{id:t,jsonrpc:"2.0",error:ix(e,r)}}function ix(t,e){return typeof t>"u"?Dd(xd):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dd(ca)),{message:t})),typeof e<"u"&&(t.data=e),RS(t.code)&&(t=CS(t.code)),t)}class sx{}class ox extends sx{constructor(){super()}}class ax extends ox{constructor(e){super()}}const cx="^wss?:";function ux(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function lx(t,e){const r=ux(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Td(t){return lx(t,cx)}function hx(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Rd(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function pa(t){return Rd(t)&&"method"in t}function ns(t){return Rd(t)&&(It(t)||ot(t))}function It(t){return"result"in t}function ot(t){return"error"in t}class dx extends ax{constructor(e){super(e),this.events=new Le.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Dr(e.method,e.params||[],e.id||Ir().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{ot(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ns(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 fx=()=>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"),px=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Cd=t=>t.split("?")[0],Nd=10,gx=fx();class yx{constructor(e){if(this.url=e,this.events=new Le.exports.EventEmitter,this.registering=!1,!Td(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(dr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Td(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Od.isReactNative()?void 0:{rejectUnauthorized:!hx(e)},s=new gx(e,[],i);px()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Nr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=fa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return NS(e,Cd(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Nd&&this.events.setMaxListeners(Nd)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Cd(this.url)}`));return this.events.emit("register_error",r),r}}const Bd="wc",Fd=2,is="core",Dt=`${Bd}@2:${is}:`,wx={name:is,logger:"error"},mx={database:":memory:"},bx="crypto",Ld="client_ed25519_seed",vx=L.ONE_DAY,Ex="keychain",_x="0.3",Sx="messages",xx="0.3",Ud=L.SIX_HOURS,Ix="publisher",kd="irn",Dx="error",Md="wss://relay.walletconnect.org",Ox="relayer",Ie={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"},$x="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ax=.1,ga="2.19.2",ce={link_mode:"link_mode",relay:"relay"},ss={inbound:"inbound",outbound:"outbound"},Px="0.3",Tx="WALLETCONNECT_CLIENT_ID",jd="WALLETCONNECT_LINK_MODE_APPS",rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Rx="subscription",Cx="0.3",Nx="pairing",Bx="0.3",Xn={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Or={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ft={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Fx="history",Lx="0.3",Ux="expirer",ct={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},kx="0.3",Mx="verify-api",jx="https://verify.walletconnect.com",qd="https://verify.walletconnect.org",Qn=qd,qx=`${Qn}/v3`,zx=[jx,qd],Vx="echo",Kx="https://echo.walletconnect.com",Ot={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"},Vt={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"},pt={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"},$r={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"},Ar={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"},ei={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"},Hx=.1,Wx="event-client",Gx=86400,Yx="https://pulse.walletconnect.org/batch";function Zx(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var Jx=Zx,Xx=Jx;const zd=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")},Qx=t=>new TextEncoder().encode(t),e3=t=>new TextDecoder().decode(t);class t3{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class r3{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Vd(this,e)}}class n3{constructor(e){this.decoders=e}or(e){return Vd(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Vd=(t,e)=>new n3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class i3{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new t3(e,r,n),this.decoder=new r3(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const os=({name:t,prefix:e,encode:r,decode:n})=>new i3(t,e,r,n),ti=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Xx(r,e);return os({prefix:t,name:e,encode:n,decode:s=>zd(i(s))})},s3=(t,e,r,n)=>{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*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},o3=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Ce=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>os({prefix:e,name:t,encode(i){return o3(i,n,r)},decode(i){return s3(i,n,r,t)}}),a3=os({prefix:"\0",name:"identity",encode:t=>e3(t),decode:t=>Qx(t)});var c3=Object.freeze({__proto__:null,identity:a3});const u3=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var l3=Object.freeze({__proto__:null,base2:u3});const h3=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var d3=Object.freeze({__proto__:null,base8:h3});const f3=ti({prefix:"9",name:"base10",alphabet:"0123456789"});var p3=Object.freeze({__proto__:null,base10:f3});const g3=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),y3=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var w3=Object.freeze({__proto__:null,base16:g3,base16upper:y3});const m3=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),b3=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),v3=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),E3=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_3=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),S3=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),x3=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),I3=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),D3=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var O3=Object.freeze({__proto__:null,base32:m3,base32upper:b3,base32pad:v3,base32padupper:E3,base32hex:_3,base32hexupper:S3,base32hexpad:x3,base32hexpadupper:I3,base32z:D3});const $3=ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),A3=ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var P3=Object.freeze({__proto__:null,base36:$3,base36upper:A3});const T3=ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),R3=ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var C3=Object.freeze({__proto__:null,base58btc:T3,base58flickr:R3});const N3=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),B3=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),F3=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),L3=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var U3=Object.freeze({__proto__:null,base64:N3,base64pad:B3,base64url:F3,base64urlpad:L3});const Kd=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}"),k3=Kd.reduce((t,e,r)=>(t[r]=e,t),[]),M3=Kd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function j3(t){return t.reduce((e,r)=>(e+=k3[r],e),"")}function q3(t){const e=[];for(const r of t){const n=M3[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const z3=os({prefix:"\u{1F680}",name:"base256emoji",encode:j3,decode:q3});var V3=Object.freeze({__proto__:null,base256emoji:z3}),K3=Wd,Hd=128,H3=127,W3=~H3,G3=Math.pow(2,31);function Wd(t,e,r){e=e||[],r=r||0;for(var n=r;t>=G3;)e[r++]=t&255|Hd,t/=128;for(;t&W3;)e[r++]=t&255|Hd,t>>>=7;return e[r]=t|0,Wd.bytes=r-n+1,e}var Y3=ya,Z3=128,Gd=127;function ya(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Gd)<<i:(o&Gd)*Math.pow(2,i),i+=7}while(o>=Z3);return ya.bytes=s-n,r}var J3=Math.pow(2,7),X3=Math.pow(2,14),Q3=Math.pow(2,21),eI=Math.pow(2,28),tI=Math.pow(2,35),rI=Math.pow(2,42),nI=Math.pow(2,49),iI=Math.pow(2,56),sI=Math.pow(2,63),oI=function(t){return t<J3?1:t<X3?2:t<Q3?3:t<eI?4:t<tI?5:t<rI?6:t<nI?7:t<iI?8:t<sI?9:10},aI={encode:K3,decode:Y3,encodingLength:oI},Yd=aI;const Zd=(t,e,r=0)=>(Yd.encode(t,e,r),e),Jd=t=>Yd.encodingLength(t),wa=(t,e)=>{const r=e.byteLength,n=Jd(t),i=n+Jd(r),s=new Uint8Array(i+r);return Zd(t,s,0),Zd(r,s,n),s.set(e,i),new cI(t,r,e,s)};class cI{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Xd=({name:t,code:e,encode:r})=>new uI(t,e,r);class uI{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?wa(this.code,r):r.then(n=>wa(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Qd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),lI=Xd({name:"sha2-256",code:18,encode:Qd("SHA-256")}),hI=Xd({name:"sha2-512",code:19,encode:Qd("SHA-512")});var dI=Object.freeze({__proto__:null,sha256:lI,sha512:hI});const ef=0,fI="identity",tf=zd;var pI=Object.freeze({__proto__:null,identity:{code:ef,name:fI,encode:tf,digest:t=>wa(ef,tf(t))}});new TextEncoder,new TextDecoder;const rf={...c3,...l3,...d3,...p3,...w3,...O3,...P3,...C3,...U3,...V3};({...dI,...pI});function gI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function nf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const sf=nf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ma=nf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=gI(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yI={utf8:sf,"utf-8":sf,hex:rf.base16,latin1:ma,ascii:ma,binary:ma,...rf};function wI(t,e="utf8"){const r=yI[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var mI=Object.defineProperty,bI=(t,e,r)=>e in t?mI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$t=(t,e,r)=>bI(t,typeof e!="symbol"?e+"":e,r);class vI{constructor(e,r){this.core=e,this.logger=r,$t(this,"keychain",new Map),$t(this,"name",Ex),$t(this,"version",_x),$t(this,"initialized",!1),$t(this,"storagePrefix",Dt),$t(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),$t(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),$t(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),$t(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=U("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),$t(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=je(r,this.name)}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ao(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EI=Object.defineProperty,_I=(t,e,r)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>_I(t,typeof e!="symbol"?e+"":e,r);class SI{constructor(e,r,n){this.core=e,this.logger=r,Ne(this,"name",bx),Ne(this,"keychain"),Ne(this,"randomSessionIdentifier",ia()),Ne(this,"initialized",!1),Ne(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ne(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ne(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=wu(i);return yu(s.publicKey)}),Ne(this,"generateKeyPair",()=>{this.isInitialized();const i=C_();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ne(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=wu(s),a=this.randomSessionIdentifier;return await Mm(a,i,vx,o)}),Ne(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=N_(a,s);return this.setSymKey(c,o)}),Ne(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Xi(i);return await this.keychain.set(o,i),o}),Ne(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"encode",async(i,s,o)=>{this.isInitialized();const a=hd(o),c=dr(s);if(fd(a))return L_(c,o?.encoding);if(dd(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return B_({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ne(this,"decode",async(i,s,o)=>{this.isInitialized();const a=k_(s,o);if(fd(a)){const c=U_(s,o?.encoding);return Nr(c)}if(dd(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=F_({symKey:c,encoded:s,encoding:o?.encoding});return Nr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ne(this,"getPayloadType",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return xr(o.type)}),Ne(this,"getPayloadSenderPublicKey",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return o.senderPublicKey?Ge(o.senderPublicKey,ze):void 0}),this.core=e,this.logger=je(r,this.name),this.keychain=n||new vI(this.core,this.logger)}get context(){return He(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ld)}catch{e=ia(),await this.keychain.set(Ld,e)}return wI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xI=Object.defineProperty,II=Object.defineProperties,DI=Object.getOwnPropertyDescriptors,of=Object.getOwnPropertySymbols,OI=Object.prototype.hasOwnProperty,$I=Object.prototype.propertyIsEnumerable,ba=(t,e,r)=>e in t?xI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,AI=(t,e)=>{for(var r in e||(e={}))OI.call(e,r)&&ba(t,r,e[r]);if(of)for(var r of of(e))$I.call(e,r)&&ba(t,r,e[r]);return t},PI=(t,e)=>II(t,DI(e)),nt=(t,e,r)=>ba(t,typeof e!="symbol"?e+"":e,r);class TI extends kg{constructor(e,r){super(e,r),this.logger=e,this.core=r,nt(this,"messages",new Map),nt(this,"messagesWithoutClientAck",new Map),nt(this,"name",Sx),nt(this,"version",xx),nt(this,"initialized",!1),nt(this,"storagePrefix",Dt),nt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),nt(this,"set",async(n,i,s)=>{this.isInitialized();const o=St(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===ss.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,PI(AI({},c),{[o]:i}))}return await this.persist(),o}),nt(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),nt(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),nt(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=St(i);return typeof s[o]<"u"}),nt(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=St(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),nt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=je(e,this.name),this.core=r}get context(){return He(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,Ao(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ao(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Po(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var RI=Object.defineProperty,CI=Object.defineProperties,NI=Object.getOwnPropertyDescriptors,af=Object.getOwnPropertySymbols,BI=Object.prototype.hasOwnProperty,FI=Object.prototype.propertyIsEnumerable,va=(t,e,r)=>e in t?RI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,as=(t,e)=>{for(var r in e||(e={}))BI.call(e,r)&&va(t,r,e[r]);if(af)for(var r of af(e))FI.call(e,r)&&va(t,r,e[r]);return t},Ea=(t,e)=>CI(t,NI(e)),gt=(t,e,r)=>va(t,typeof e!="symbol"?e+"":e,r);class LI extends Mg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,gt(this,"events",new Le.exports.EventEmitter),gt(this,"name",Ix),gt(this,"queue",new Map),gt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),gt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),gt(this,"needsTransportRestart",!1),gt(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||Ud,c=Qi(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||Ir().toString(),d={topic:n,message:i,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const f=new Promise(async y=>{const g=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Ie.publish,g),y(d))};this.relayer.events.on(Ie.publish,g);const w=rr(new Promise((m,b)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(m).catch(E=>{this.logger.warn(E,E?.message),b(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await w,this.events.removeListener(Ie.publish,g)}catch(m){this.queue.set(h,Ea(as({},d),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await rr(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),gt(this,"on",(n,i)=>{this.events.on(n,i)}),gt(this,"once",(n,i)=>{this.events.once(n,i)}),gt(this,"off",(n,i)=>{this.events.off(n,i)}),gt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=je(r,this.name),this.registerEventListeners()}get context(){return He(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=Ud,prompt:u,tag:l,id:h,attestation:d,tvf:p}=e,f={method:Wn(Qi().protocol).publish,params:as({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},p),id:h};Re((r=f.params)==null?void 0:r.prompt)&&((n=f.params)==null||delete n.prompt),Re((i=f.params)==null?void 0:i.tag)&&((s=f.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const y=await this.relayer.request(f);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,Ea(as({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(Ea(as({},e),{topic:i,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Cr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var UI=Object.defineProperty,kI=(t,e,r)=>e in t?UI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hn=(t,e,r)=>kI(t,typeof e!="symbol"?e+"":e,r);class MI{constructor(){hn(this,"map",new Map),hn(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),hn(this,"get",e=>this.map.get(e)||[]),hn(this,"exists",(e,r)=>this.get(e).includes(r)),hn(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),hn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var jI=Object.defineProperty,qI=Object.defineProperties,zI=Object.getOwnPropertyDescriptors,cf=Object.getOwnPropertySymbols,VI=Object.prototype.hasOwnProperty,KI=Object.prototype.propertyIsEnumerable,_a=(t,e,r)=>e in t?jI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ri=(t,e)=>{for(var r in e||(e={}))VI.call(e,r)&&_a(t,r,e[r]);if(cf)for(var r of cf(e))KI.call(e,r)&&_a(t,r,e[r]);return t},Sa=(t,e)=>qI(t,zI(e)),ne=(t,e,r)=>_a(t,typeof e!="symbol"?e+"":e,r);class HI extends zg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ne(this,"subscriptions",new Map),ne(this,"topicMap",new MI),ne(this,"events",new Le.exports.EventEmitter),ne(this,"name",Rx),ne(this,"version",Cx),ne(this,"pending",new Map),ne(this,"cached",[]),ne(this,"initialized",!1),ne(this,"storagePrefix",Dt),ne(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ne(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"clientId"),ne(this,"batchSubscribeTopicsLimit",500),ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ne(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Qi(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),ne(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),ne(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),ne(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),ne(this,"on",(n,i)=>{this.events.on(n,i)}),ne(this,"once",(n,i)=>{this.events.once(n,i)}),ne(this,"off",(n,i)=>{this.events.off(n,i)}),ne(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),ne(this,"start",async()=>{await this.onConnect()}),ne(this,"stop",async()=>{await this.onDisconnect()}),ne(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ne(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),ne(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Cr.pulse,async()=>{await this.checkPending()}),this.events.on(rt.created,async n=>{const i=rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(rt.deleted,async n=>{const i=rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=je(r,this.name),this.clientId=""}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Qi(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=oe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i;(!n||n?.transportType===ce.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Wn(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===ce.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(l=>this.logger.warn(l))},L.toMiliseconds(L.ONE_SECOND)),a;const c=new Promise(async l=>{const h=d=>{d.topic===e&&(this.events.removeListener(rt.created,h),l(d.id))};this.events.on(rt.created,h);try{const d=await rr(new Promise((p,f)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),f(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(rt.created,h),l(d)}catch{}}),u=await rr(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await rr(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await rr(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Wn(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Sa(ri({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ri({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,ri({},r)),this.topicMap.set(r.topic,e),this.events.emit(rt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(rt.deleted,Sa(ri({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Sa(ri({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await _E(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=U("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 St(e+await this.getClientId())}}var WI=Object.defineProperty,uf=Object.getOwnPropertySymbols,GI=Object.prototype.hasOwnProperty,YI=Object.prototype.propertyIsEnumerable,xa=(t,e,r)=>e in t?WI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lf=(t,e)=>{for(var r in e||(e={}))GI.call(e,r)&&xa(t,r,e[r]);if(uf)for(var r of uf(e))YI.call(e,r)&&xa(t,r,e[r]);return t},X=(t,e,r)=>xa(t,typeof e!="symbol"?e+"":e,r);class ZI extends jg{constructor(e){super(e),X(this,"protocol","wc"),X(this,"version",2),X(this,"core"),X(this,"logger"),X(this,"events",new Le.exports.EventEmitter),X(this,"provider"),X(this,"messages"),X(this,"subscriber"),X(this,"publisher"),X(this,"name",Ox),X(this,"transportExplicitlyClosed",!1),X(this,"initialized",!1),X(this,"connectionAttemptInProgress",!1),X(this,"relayUrl"),X(this,"projectId"),X(this,"packageName"),X(this,"bundleId"),X(this,"hasExperiencedNetworkDisruption",!1),X(this,"pingTimeout"),X(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),X(this,"reconnectTimeout"),X(this,"connectPromise"),X(this,"reconnectInProgress",!1),X(this,"requestsInFlight",[]),X(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),X(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Ir().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),X(this,"resetPingTimeout",()=>{ji()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),X(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),X(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Ie.connect)}),X(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),X(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Ie.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),X(this,"registerProviderListeners",()=>{this.provider.on(at.payload,this.onPayloadHandler),this.provider.on(at.connect,this.onConnectHandler),this.provider.on(at.disconnect,this.onDisconnectHandler),this.provider.on(at.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je(e.logger,this.name):Pt(Is({level:e.logger||Dx})),this.messages=new TI(this.logger,e.core),this.subscriber=new HI(this,this.logger),this.publisher=new LI(this,this.logger),this.relayUrl=e?.relayUrl||Md,this.projectId=e.projectId,sE()?this.packageName=eh():oE()&&(this.bundleId=eh()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return He(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:ce.relay},ss.outbound)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const 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,h)=>{a=await this.subscriber.subscribe(e,lf({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await rr(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(e).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Sd())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=me(L.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,ss.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,s),await rr(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(at.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(at.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(ji())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dx(new yx(hE({sdkVersion:ga,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),pa(e)){if(!e.method.endsWith($x))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:ce.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(lf({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ns(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ss.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const r=da(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(at.payload,this.onPayloadHandler),this.provider.off(at.connect,this.onConnectHandler),this.provider.off(at.disconnect,this.onDisconnectHandler),this.provider.off(at.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Sd();xS(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.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},L.toMiliseconds(Ax)))))}isInitialized(){if(!this.initialized){const{message:e}=U("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 JI(){}function hf(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 df(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ff(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XI="[object RegExp]",QI="[object String]",e8="[object Number]",t8="[object Boolean]",pf="[object Arguments]",r8="[object Symbol]",n8="[object Date]",i8="[object Map]",s8="[object Set]",o8="[object Array]",a8="[object Function]",c8="[object ArrayBuffer]",Ia="[object Object]",u8="[object Error]",l8="[object DataView]",h8="[object Uint8Array]",d8="[object Uint8ClampedArray]",f8="[object Uint16Array]",p8="[object Uint32Array]",g8="[object BigUint64Array]",y8="[object Int8Array]",w8="[object Int16Array]",m8="[object Int32Array]",b8="[object BigInt64Array]",v8="[object Float32Array]",E8="[object Float64Array]";function _8(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function S8(t,e,r){return ni(t,e,void 0,void 0,void 0,void 0,r)}function ni(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return ii(t,e,s,o)}return ii(t,e,s,o)}function ii(t,e,r,n){if(Object.is(t,e))return!0;let i=ff(t),s=ff(e);if(i===pf&&(i=Ia),s===pf&&(s=Ia),i!==s)return!1;switch(i){case QI:return t.toString()===e.toString();case e8:{const c=t.valueOf(),u=e.valueOf();return _8(c,u)}case t8:case n8:case r8:return Object.is(t.valueOf(),e.valueOf());case XI:return t.source===e.source&&t.flags===e.flags;case a8:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case i8:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ni(u,e.get(c),c,t,e,r,n))return!1;return!0}case s8:{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 h=c[l],d=u.findIndex(p=>ni(h,p,void 0,t,e,r,n));if(d===-1)return!1;u.splice(d,1)}return!0}case o8:case h8:case d8:case f8:case p8:case g8:case y8:case w8:case m8:case b8:case v8:case E8:{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(!ni(t[c],e[c],c,t,e,r,n))return!1;return!0}case c8:return t.byteLength!==e.byteLength?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case l8:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case u8:return t.name===e.name&&t.message===e.message;case Ia:{if(!(ii(t.constructor,e.constructor,r,n)||hf(t)&&hf(e)))return!1;const c=[...Object.keys(t),...df(t)],u=[...Object.keys(e),...df(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!ni(d,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function x8(t,e){return S8(t,e,JI)}var I8=Object.defineProperty,gf=Object.getOwnPropertySymbols,D8=Object.prototype.hasOwnProperty,O8=Object.prototype.propertyIsEnumerable,Da=(t,e,r)=>e in t?I8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yf=(t,e)=>{for(var r in e||(e={}))D8.call(e,r)&&Da(t,r,e[r]);if(gf)for(var r of gf(e))O8.call(e,r)&&Da(t,r,e[r]);return t},Je=(t,e,r)=>Da(t,typeof e!="symbol"?e+"":e,r);class Pr extends qg{constructor(e,r,n,i=Dt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,Je(this,"map",new Map),Je(this,"version",Px),Je(this,"cached",[]),Je(this,"initialized",!1),Je(this,"getKey"),Je(this,"storagePrefix",Dt),Je(this,"recentlyDeleted",[]),Je(this,"recentlyDeletedLimit",200),Je(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):tS(o)?this.map.set(o.id,o):rS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Je(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())}),Je(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Je(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>x8(a[c],o[c]))):this.values)),Je(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=yf(yf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Je(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=je(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $8=Object.defineProperty,A8=(t,e,r)=>e in t?$8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y=(t,e,r)=>A8(t,typeof e!="symbol"?e+"":e,r);class P8{constructor(e,r){this.core=e,this.logger=r,Y(this,"name",Nx),Y(this,"version",Bx),Y(this,"events",new Le.exports),Y(this,"pairings"),Y(this,"initialized",!1),Y(this,"storagePrefix",Dt),Y(this,"ignoredPayloadTypes",[jt]),Y(this,"registeredMethods",[]),Y(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Y(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Y(this,"create",async n=>{this.isInitialized();const i=ia(),s=await this.core.crypto.setSymKey(i),o=me(L.FIVE_MINUTES),a={protocol:kd},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=gd({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(Or.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:u}}),Y(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Ot.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=pd(n.uri);i.props.properties.topic=s,i.addTrace(Ot.pairing_uri_validation_success),i.addTrace(Ot.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Ot.existing_pairing),l.active)throw i.setError(Vt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Ot.pairing_not_expired)}const h=c||me(L.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,d),i.addTrace(Ot.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Or.create,d),i.addTrace(Ot.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Ot.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Vt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(Vt.subscribe_pairing_topic_failure),p}return i.addTrace(Ot.subscribe_pairing_topic_success),d}),Y(this,"activate",async({topic:n})=>{this.isInitialized();const i=me(L.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Y(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=br();this.events.once(Q("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Y(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Y(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Y(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Y(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",oe("USER_DISCONNECTED")),await this.deletePairing(i))}),Y(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return gd({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Y(this,"sendRequest",async(n,i,s)=>{const o=Dr(i,s),a=await this.core.crypto.encode(n,o),c=Xn[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Y(this,"sendResult",async(n,i,s)=>{const o=da(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"sendError",async(n,i,s)=>{const o=fa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c]?Xn[c].res:Xn.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,oe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Y(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>nr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Y(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Y(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Y(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Or.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{It(i)?this.events.emit(Q("pairing_ping",s),{}):ot(i)&&this.events.emit(Q("pairing_ping",s),{error:i.error})},500)}),Y(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Or.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=oe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Y(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(oe("WC_METHOD_UNSUPPORTED",n))}),Y(this,"isValidPair",(n,i)=>{var s;if(!Ze(n)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!eS(n.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}const o=pd(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Vt.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Y(this,"isValidPing",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidDisconnect",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidPairingTopic",async n=>{if(!pe(n,!1)){const{message:i}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(nr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=U("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=je(r,this.name),this.pairings=new Pr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return He(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==ce.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);pa(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ns(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(ct.expired,async e=>{const{topic:r}=ih(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Or.expire,{topic:r}))})}}var T8=Object.defineProperty,R8=(t,e,r)=>e in t?T8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>R8(t,typeof e!="symbol"?e+"":e,r);class C8 extends Ug{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new Le.exports.EventEmitter),Be(this,"name",Fx),Be(this,"version",Lx),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Dt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:me(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ft.created,o)}),Be(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=ot(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(ft.updated,i))}),Be(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),Be(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(ft.deleted,s)}}),this.persist()}),Be(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Be(this,"on",(n,i)=>{this.events.on(n,i)}),Be(this,"once",(n,i)=>{this.events.once(n,i)}),Be(this,"off",(n,i)=>{this.events.off(n,i)}),Be(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:Dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ft.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ft.created,e=>{const r=ft.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.updated,e=>{const r=ft.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.deleted,e=>{const r=ft.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Cr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ft.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var N8=Object.defineProperty,B8=(t,e,r)=>e in t?N8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ke=(t,e,r)=>B8(t,typeof e!="symbol"?e+"":e,r);class F8 extends Vg{constructor(e,r){super(e,r),this.core=e,this.logger=r,ke(this,"expirations",new Map),ke(this,"events",new Le.exports.EventEmitter),ke(this,"name",Ux),ke(this,"version",kx),ke(this,"cached",[]),ke(this,"initialized",!1),ke(this,"storagePrefix",Dt),ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ke(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),ke(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(ct.created,{target:s,expiration:o})}),ke(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),ke(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(ct.deleted,{target:i,expiration:s})}}),ke(this,"on",(n,i)=>{this.events.on(n,i)}),ke(this,"once",(n,i)=>{this.events.once(n,i)}),ke(this,"off",(n,i)=>{this.events.off(n,i)}),ke(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(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 dE(e);if(typeof e=="number")return fE(e);const{message:r}=U("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(ct.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;L.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ct.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Cr.pulse,()=>this.checkExpirations()),this.events.on(ct.created,e=>{const r=ct.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.expired,e=>{const r=ct.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.deleted,e=>{const r=ct.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var L8=Object.defineProperty,U8=(t,e,r)=>e in t?L8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e,r)=>U8(t,typeof e!="symbol"?e+"":e,r);class k8 extends Kg{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,ge(this,"name",Mx),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",qx),ge(this,"storagePrefix",Dt),ge(this,"version",Fd),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async i=>{if(!Cn()||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=_n(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",g),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",f,{signal:this.abortController.signal});const g=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(Hs(m.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",g),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};u.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),ge(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(Hs(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)}),ge(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(L.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}),ge(this,"getVerifyUrl",i=>{let s=i||Qn;return zx.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Qn}`),s=Qn),s}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(L.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)}}),ge(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(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")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(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}),ge(this,"validateAttestation",(i,s)=>{const o=j_(i,s.publicKey),a={hasExpired:L.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=je(r,this.name),this.abortController=new AbortController,this.isDevEnv=To(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return He(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var M8=Object.defineProperty,j8=(t,e,r)=>e in t?M8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wf=(t,e,r)=>j8(t,typeof e!="symbol"?e+"":e,r);class q8 extends Hg{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,wf(this,"context",Vx),wf(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${Kx}/${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=je(r,this.context)}}var z8=Object.defineProperty,mf=Object.getOwnPropertySymbols,V8=Object.prototype.hasOwnProperty,K8=Object.prototype.propertyIsEnumerable,Oa=(t,e,r)=>e in t?z8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,si=(t,e)=>{for(var r in e||(e={}))V8.call(e,r)&&Oa(t,r,e[r]);if(mf)for(var r of mf(e))K8.call(e,r)&&Oa(t,r,e[r]);return t},De=(t,e,r)=>Oa(t,typeof e!="symbol"?e+"":e,r);class H8 extends Wg{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,De(this,"context",Wx),De(this,"storagePrefix",Dt),De(this,"storageVersion",Hx),De(this,"events",new Map),De(this,"shouldPersist",!1),De(this,"init",async()=>{if(!To())try{const i={eventId:oh(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rh(this.core.relayer.protocol,this.core.relayer.version,ga)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),De(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=oh(),l=this.core.projectId||"",h=Date.now(),d=si({eventId:u,timestamp:h,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}),De(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 si(si({},a),this.setMethods(a.eventId))}),De(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),De(this,"setEventListeners",()=>{this.core.heartbeat.on(Cr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(i.timestamp)>Gx&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),De(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),De(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)}),De(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)}),De(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),De(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,si(si({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),De(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)}}),De(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Yx}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ga}${s}`,{method:"POST",body:JSON.stringify(i)})}),De(this,"getAppDomain",()=>th().url),this.logger=je(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var W8=Object.defineProperty,bf=Object.getOwnPropertySymbols,G8=Object.prototype.hasOwnProperty,Y8=Object.prototype.propertyIsEnumerable,$a=(t,e,r)=>e in t?W8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vf=(t,e)=>{for(var r in e||(e={}))G8.call(e,r)&&$a(t,r,e[r]);if(bf)for(var r of bf(e))Y8.call(e,r)&&$a(t,r,e[r]);return t},ae=(t,e,r)=>$a(t,typeof e!="symbol"?e+"":e,r);class Aa extends Ng{constructor(e){var r;super(e),ae(this,"protocol",Bd),ae(this,"version",Fd),ae(this,"name",is),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new Le.exports.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ce.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Md,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Is({level:typeof e?.logger=="string"&&e.logger?e.logger:wx.logger,name:is}),{logger:s,chunkLoggerController:o}=Tg({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=je(s,this.name),this.heartbeat=new ms,this.crypto=new SI(this,this.logger,e?.keychain),this.history=new C8(this,this.logger),this.expirer=new F8(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ng(vf(vf({},mx),e?.storageOptions)),this.relayer=new ZI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new P8(this,this.logger),this.verify=new k8(this,this.logger,this.storage),this.echoClient=new q8(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new H8(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Aa(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(Tx,n),r}get context(){return He(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(jd,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(jd)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Pa=Aa,Ef="wc",_f=2,Sf="client",Ta=`${Ef}@${_f}:${Sf}:`,Ra={name:Sf,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},xf="WALLETCONNECT_DEEPLINK_CHOICE",Z8="proposal",If="Proposal expired",J8="session",dn=L.SEVEN_DAYS,X8="engine",Oe={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},Ca={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},At={idle:"IDLE",active:"ACTIVE"},Df={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Q8="request",eD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tD="wc",rD="auth",nD="authKeys",iD="pairingTopics",sD="requests",cs=`${tD}@${1.5}:${rD}:`,us=`${cs}:PUB_KEY`;var oD=Object.defineProperty,aD=Object.defineProperties,cD=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,Na=(t,e,r)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ie=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&Na(t,r,e[r]);if(Of)for(var r of Of(e))lD.call(e,r)&&Na(t,r,e[r]);return t},Ve=(t,e)=>aD(t,cD(e)),R=(t,e,r)=>Na(t,typeof e!="symbol"?e+"":e,r);class hD extends Jg{constructor(e){super(e),R(this,"name",X8),R(this,"events",new Le.exports),R(this,"initialized",!1),R(this,"requestQueue",{state:At.idle,queue:[]}),R(this,"sessionRequestQueue",{state:At.idle,queue:[]}),R(this,"requestQueueDelay",L.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(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(Oe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Ve(ie({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,d=!1;try{if(l){const D=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),D}if(!l||!d){const{topic:D,uri:S}=await this.client.core.pairing.create();l=D,h=S}if(!l){const{message:D}=U("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const p=await this.client.core.crypto.generateKeyPair(),f=Oe.wc_sessionPropose.req.ttl||L.FIVE_MINUTES,y=me(f),g=Ve(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:kd}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:xt()}),w=Q("session_connect",g.id),{reject:m,resolve:b,done:E}=br(f,If),$=({id:D})=>{D===g.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(g.id),this.events.emit(w,{error:{message:If,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(w,({error:D,session:S})=>{this.client.events.off("proposal_expire",$),D?m(D):S&&b(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:g,throwOnFailedPublish:!0,clientRpcId:g.id}),await this.setProposal(g.id,g),{uri:h,approval:E}}),R(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),R(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[pt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError($r.no_internet_connection),x}try{await this.isValidProposalId(r?.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError($r.proposal_not_found),x}try{await this.isValidApprove(r)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError($r.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:y,requiredNamespaces:g,optionalNamespaces:w}=p;let m=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:f});m||(m=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:pt.session_approve_started,properties:{topic:f,trace:[pt.session_approve_started,pt.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),E=y.publicKey,$=await this.client.core.crypto.generateSharedKey(b,E),D=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:b,metadata:this.client.metadata},expiry:me(dn)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),S=ce.relay;m.addTrace(pt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:S})}catch(x){throw m.setError($r.subscribe_session_topic_failure),x}m.addTrace(pt.subscribe_session_topic_success);const A=Ve(ie({},D),{topic:$,requiredNamespaces:g,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:b,transportType:ce.relay});await this.client.session.set($,A),m.addTrace(pt.store_session);try{m.addTrace(pt.publishing_session_settle),await this.sendRequest({topic:$,method:"wc_sessionSettle",params:D,throwOnFailedPublish:!0}).catch(x=>{throw m?.setError($r.session_settle_publish_failure),x}),m.addTrace(pt.session_settle_publish_success),m.addTrace(pt.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(x=>{throw m?.setError($r.session_approve_publish_failure),x}),m.addTrace(pt.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete($,oe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),x}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:y.metadata}),await this.client.proposal.delete(a,oe("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry($,me(dn)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),R(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i,rpcOpts:Oe.wc_sessionPropose.reject}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED")))}),R(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=br(),c=xt(),u=Ir().toString(),l=this.client.session.get(n).namespaces;return this.events.once(Q("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:l}),a(h)}),{acknowledged:s}}),R(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=xt(),{done:s,resolve:o,reject:a}=br();return this.events.once(Q("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,me(dn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=Oe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const c=xt(),u=Ir().toString(),{done:l,resolve:h,reject:d}=br(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:w,result:m})=>{w?d(w):h(m)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const y={request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},g=this.shouldSetTVF(p,y);return await Promise.all([new Promise(async w=>{await this.sendRequest(ie({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:y,expiry:o,throwOnFailedPublish:!0},g&&{tvf:this.getTVFParams(c,y)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await mE(this.client.core.storage,xf);await gE({id:c,topic:s,wcDeepLink:b})}w()}),l()]).then(w=>w[2])}),R(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);It(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):ot(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),R(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=xt(),s=Ir().toString(),{done:o,resolve:a,reject:c}=br();this.events.once(Q("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Ir().toString(),a=xt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:oe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=U("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>X_(n,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?ce.link_mode:ce.relay;o===ce.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:p,nbf:f,methods:y=[],expiry:g}=r,w=[...r.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const E=await this.client.core.crypto.generateKeyPair(),$=Xi(E);if(await Promise.all([this.client.auth.authKeys.set(us,{responseTopic:$,publicKey:E}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:m})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),y.length>0){const{namespace:P}=Mi(a[0]);let N=u2(P,"request",y);Vi(w)&&(N=h2(N,w.pop())),w.push(N)}const D=g&&g>Oe.wc_sessionAuthenticate.req.ttl?g:Oe.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(D)},A={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},x={requiredNamespaces:{},optionalNamespaces:A,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(Oe.wc_sessionPropose.req.ttl),id:xt()},{done:k,resolve:C,reject:B}=br(D,"Request expired"),j=xt(),I=Q("session_connect",x.id),_=Q("session_request",j),v=async({error:P,session:N})=>{this.events.off(_,O),P?B(P):N&&C({session:N})},O=async P=>{var N,F,M;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),P.error){const W=oe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===W.code?void 0:(this.events.off(I,v),B(P.error.message))}await this.deleteProposal(x.id),this.events.off(I,v);const{cacaos:z,responder:q}=P.result,V=[],K=[];for(const W of z){await Eh({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(oe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ye}=W,ue=Vi(ye.resources),le=[Lo(ye.iss)],$e=zi(ye.iss);if(ue){const Me=xh(ue),Kt=Ih(ue);V.push(...Me),le.push(...Kt)}for(const Me of le)K.push(`${Me}:${$e}`)}const ee=await this.client.core.crypto.generateSharedKey(E,q.publicKey);let G;V.length>0&&(G={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:me(dn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:yd([...new Set(V)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(ee,{transportType:o}),await this.client.session.set(ee,G),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:q.metadata}),G=this.client.session.get(ee)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(F=q.metadata.redirect)!=null&&F.linkMode&&(M=q.metadata.redirect)!=null&&M.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ee,{transportType:ce.link_mode})),C({auths:z,session:G})};this.events.once(I,v),this.events.once(_,O);let T;try{if(s){const P=Dr("wc_sessionAuthenticate",S,j);this.client.core.history.set(m,P);const N=await this.client.core.crypto.encode("",P,{type:Vn,encoding:ar});T=es(n,m,N)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:x,expiry:Oe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:x.id})])}catch(P){throw this.events.off(I,v),this.events.off(_,O),P}return await this.setProposal(x.id,x),await this.setAuthRequest(j,{request:Ve(ie({},S),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:T??b,response:k}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ar.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw s.setError(ei.no_internet_connection),g}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(ei.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ce.relay;a===ce.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=Xi(c),h={type:jt,receiverPublicKey:c,senderPublicKey:u},d=[],p=[];for(const g of i){if(!await Eh({cacao:g,projectId:this.client.core.projectId})){s.setError(ei.invalid_cacao);const $=oe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:$,encodeOpts:h}),new Error($.message)}s.addTrace(Ar.cacaos_verified);const{p:w}=g,m=Vi(w.resources),b=[Lo(w.iss)],E=zi(w.iss);if(m){const $=xh(m),D=Ih(m);d.push(...$),b.push(...D)}for(const $ of b)p.push(`${$}:${E}`)}const f=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Ar.create_authenticated_session_topic);let y;if(d?.length>0){y={topic:f,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(dn),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:yd([...new Set(d)],[...new Set(p)]),transportType:a},s.addTrace(Ar.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(g){throw s.setError(ei.subscribe_authenticated_session_topic_failure),g}s.addTrace(Ar.subscribe_authenticated_session_topic_success),await this.client.session.set(f,y),s.addTrace(Ar.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ar.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(g){throw s.setError(ei.authenticated_session_approve_publish_failure),g}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:y}}),R(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Xi(o),u={type:jt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Oe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return _h(n,i)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),R(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),R(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,oe("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(xf).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,oe("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=At.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),R(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError($r.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,oe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=At.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),R(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),R(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,me(Oe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),R(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=ce.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(Oe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),R(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,d=Dr(i,s,c);let p;const f=!!l;try{const w=f?ar:dt;p=await this.client.core.crypto.encode(n,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),w}let y;if(eD.includes(i)){const w=St(JSON.stringify(d)),m=St(p);y=await this.client.core.verify.register({id:m,decryptedId:w})}const g=Oe[i].req;if(g.attestation=y,o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(n,d),f){const w=es(l,n,p);await global.Linking.openURL(w,this.client.name)}else{const w=Oe[i].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Ve(ie({},h),{correlationId:d.id}),u?(w.internal=Ve(ie({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,w)):this.client.core.relayer.publish(n,p,w).catch(m=>this.client.logger.error(m))}return d.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=da(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),f}let d,p;try{d=await this.client.core.history.get(i,n);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(n,f.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),f}if(h){const f=es(c,i,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,y=Oe[f].res;y.tvf=Ve(ie({},p),{correlationId:n}),o?(y.internal=Ve(ie({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,y)):this.client.core.relayer.publish(i,l,y).catch(g=>this.client.logger.error(g))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=fa(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=es(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||Oe[p].res;this.client.core.relayer.publish(i,l,f)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;nr(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{nr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===At.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=At.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=At.idle}),R(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=U("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),R(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Vt.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||me(Oe.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:n,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:St(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Ot.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Oe.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(It(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const 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:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(ot(n)){await this.client.proposal.delete(s,oe("USER_DISCONNECTED"));const o=Q("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),R(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=n.params,p=[...this.pendingSessions.values()].find(g=>g.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const f=this.client.proposal.get(p.proposalId),y=Ve(ie(ie(ie({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:ce.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Q("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;It(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Q("session_approve",i),{})):ot(n)&&(await this.client.session.delete(r,oe("USER_DISCONNECTED")),this.events.emit(Q("session_approve",i),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Yn.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:oe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:r},i));try{Yn.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Yn.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=Q("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_update",i),{}):ot(n)&&this.events.emit(Q("session_update",i),{error:n.error})}),R(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(dn)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=Q("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_extend",i),{}):ot(n)&&this.events.emit(Q("session_extend",i),{error:n.error})}),R(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=Q("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);It(n)?this.events.emit(Q("session_ping",i),{}):ot(n)&&this.events.emit(Q("session_ping",i),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Ie.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:oe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),R(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:d}=a;try{await this.isValidRequest(ie({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:St(JSON.stringify(Dr("wc_sessionRequest",d,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(y),l===ce.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=Q("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Yn.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ie({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Yn.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,d=await this.getVerifyContext({attestationId:o,hash:St(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===ce.link_mode&&(n=u.metadata.redirect)!=null&&n.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,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:jt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Oe.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=At.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=Q("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Q("session_request",s.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===At.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=At.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:Dr("wc_sessionPropose",Ve(ie({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),R(this,"isValidConnect",async r=>{if(!Ze(r)){const{message:u}=U("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Re(n)||await this.isValidPairingTopic(n),!lS(c,!0)){const{message:u}=U("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Re(i)&&ts(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Re(s)&&ts(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,n)=>{const i=uS(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ze(r))throw new Error(U("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),u=oa(i,"approve()");if(u)throw new Error(u.message);const l=Ed(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!pe(s,!0)){const{message:h}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Ze(r)){const{message:s}=U("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!dS(i)){const{message:s}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ze(r)){const{message:u}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!bd(n)){const{message:u}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=nS(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=oa(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(nr(o)){const{message:u}=U("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ze(r)){const{message:c}=U("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=oa(i,"update()");if(o)throw new Error(o.message);const a=Ed(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async r=>{if(!Ze(r)){const{message:c}=U("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!vd(a,s)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!fS(i)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!yS(a,s,i.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!vS(o,Ca)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ca.min} and ${Ca.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ze(r)){const{message:o}=U("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!pS(s)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async r=>{if(!Ze(r)){const{message:a}=U("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!vd(o,s)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!gS(i)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!wS(o,s,i.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!pe(i,!1))throw new Error("uri is required parameter");if(!pe(s,!1))throw new Error("domain is required parameter");if(!pe(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Mi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Mi(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Qn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ce.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:n,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}),R(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=U("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),R(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=U("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),R(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,d;return!r||n!==ce.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=r?.redirect)==null?void 0:l.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=sh(r,"topic")||"",i=decodeURIComponent(sh(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:ce.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),R(this,"registerLinkModeListeners",async()=>{var r;if(To()||tr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),R(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(Df).includes(i.method)}),R(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return Ve(ie({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(r,n)=>{try{const i=Df[r];if(typeof n=="string")return[n];const s=n[i.key];if(Gn(s))return r==="solana_signAllTransactions"?s.map(o=>YE(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(us)?this.client.auth.authKeys.get(us):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===ce.link_mode?ar:dt});pa(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:St(n)})):ns(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ct.expired,async e=>{const{topic:r,id:n}=ih(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,U("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,U("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Or.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Or.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!pe(e,!1)){const{message:r}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!pe(e,!1)){const{message:r}=U("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=U("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=U("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(pe(e,!1)){const{message:r}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!hS(e)){const{message:r}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=U("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class dD extends Pr{constructor(e,r){super(e,r,Z8,Ta),this.core=e,this.logger=r}}class $f extends Pr{constructor(e,r){super(e,r,J8,Ta),this.core=e,this.logger=r}}class fD extends Pr{constructor(e,r){super(e,r,Q8,Ta,n=>n.id),this.core=e,this.logger=r}}class pD extends Pr{constructor(e,r){super(e,r,nD,cs,()=>us),this.core=e,this.logger=r}}class gD extends Pr{constructor(e,r){super(e,r,iD,cs),this.core=e,this.logger=r}}class yD extends Pr{constructor(e,r){super(e,r,sD,cs,n=>n.id),this.core=e,this.logger=r}}var wD=Object.defineProperty,mD=(t,e,r)=>e in t?wD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ba=(t,e,r)=>mD(t,typeof e!="symbol"?e+"":e,r);class bD{constructor(e,r){this.core=e,this.logger=r,Ba(this,"authKeys"),Ba(this,"pairingTopics"),Ba(this,"requests"),this.authKeys=new pD(this.core,this.logger),this.pairingTopics=new gD(this.core,this.logger),this.requests=new yD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var vD=Object.defineProperty,ED=(t,e,r)=>e in t?vD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z=(t,e,r)=>ED(t,typeof e!="symbol"?e+"":e,r);class Fa extends Zg{constructor(e){super(e),Z(this,"protocol",Ef),Z(this,"version",_f),Z(this,"name",Ra.name),Z(this,"metadata"),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Le.exports.EventEmitter),Z(this,"engine"),Z(this,"session"),Z(this,"proposal"),Z(this,"pendingRequest"),Z(this,"auth"),Z(this,"signConfig"),Z(this,"on",(n,i)=>this.events.on(n,i)),Z(this,"once",(n,i)=>this.events.once(n,i)),Z(this,"off",(n,i)=>this.events.off(n,i)),Z(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Z(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Z(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Z(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Z(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ra.name,this.metadata=cE(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Pt(Is({level:e?.logger||Ra.logger}));this.core=e?.core||new Pa(e),this.logger=je(r,this.name),this.session=new $f(this.core,this.logger),this.proposal=new dD(this.core,this.logger),this.pendingRequest=new fD(this.core,this.logger),this.engine=new hD(this),this.auth=new bD(this.core,this.logger)}static async init(e){const r=new Fa(e);return await r.initialize(),r}get context(){return He(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},L.toMiliseconds(L.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const _D=$f,SD=Fa;class xD extends Le.exports{constructor(){super()}}class Af{constructor(e){this.opts=e}}class Pf{constructor(e){this.client=e}}var ID=Object.defineProperty,DD=Object.defineProperties,OD=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,$D=Object.prototype.hasOwnProperty,AD=Object.prototype.propertyIsEnumerable,Rf=(t,e,r)=>e in t?ID(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,PD=(t,e)=>{for(var r in e||(e={}))$D.call(e,r)&&Rf(t,r,e[r]);if(Tf)for(var r of Tf(e))AD.call(e,r)&&Rf(t,r,e[r]);return t},TD=(t,e)=>DD(t,OD(e));class RD extends Pf{constructor(e){super(e),this.init=async()=>{this.signClient=await SD.init({core:this.client.core,metadata:this.client.metadata,signConfig:this.client.signConfig}),this.signClient.core.eventClient.init().catch(r=>{this.client.logger.warn(r)})},this.pair=async r=>{await this.client.core.pairing.pair(r)},this.approveSession=async r=>{const{topic:n,acknowledged:i}=await this.signClient.approve(TD(PD({},r),{id:r.id,namespaces:r.namespaces,sessionProperties:r.sessionProperties,sessionConfig:r.sessionConfig}));return await i(),this.signClient.session.get(n)},this.rejectSession=async r=>await this.signClient.reject(r),this.updateSession=async r=>await this.signClient.update(r),this.extendSession=async r=>await this.signClient.extend(r),this.respondSessionRequest=async r=>await this.signClient.respond(r),this.disconnectSession=async r=>await this.signClient.disconnect(r),this.emitSessionEvent=async r=>await this.signClient.emit(r),this.getActiveSessions=()=>this.signClient.session.getAll().reduce((r,n)=>(r[n.topic]=n,r),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.approveSessionAuthenticate=async r=>await this.signClient.approveSessionAuthenticate(r),this.rejectSessionAuthenticate=async r=>await this.signClient.rejectSessionAuthenticate(r),this.formatAuthMessage=r=>this.signClient.formatAuthMessage(r),this.registerDeviceToken=r=>this.client.core.echoClient.registerDeviceToken(r),this.on=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"on"),this.client.events.on(r,n)),this.once=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"once"),this.client.events.once(r,n)),this.off=(r,n)=>(this.setEvent(r,"off"),this.client.events.off(r,n)),this.removeListener=(r,n)=>(this.setEvent(r,"removeListener"),this.client.events.removeListener(r,n)),this.onSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onSessionProposal=r=>{this.client.events.emit("session_proposal",r)},this.onSessionDelete=r=>{this.client.events.emit("session_delete",r)},this.onProposalExpire=r=>{this.client.events.emit("proposal_expire",r)},this.onSessionRequestExpire=r=>{this.client.events.emit("session_request_expire",r)},this.onSessionRequestAuthenticate=r=>{this.client.events.emit("session_authenticate",r)},this.setEvent=(r,n)=>{switch(r){case"session_request":this.signClient.events[n]("session_request",this.onSessionRequest);break;case"session_proposal":this.signClient.events[n]("session_proposal",this.onSessionProposal);break;case"session_delete":this.signClient.events[n]("session_delete",this.onSessionDelete);break;case"proposal_expire":this.signClient.events[n]("proposal_expire",this.onProposalExpire);break;case"session_request_expire":this.signClient.events[n]("session_request_expire",this.onSessionRequestExpire);break;case"session_authenticate":this.signClient.events[n]("session_authenticate",this.onSessionRequestAuthenticate);break}},this.signClient={}}}const CD={decryptMessage:async t=>{const e={core:new Pa({storageOptions:t.storageOptions,storage:t.storage})};await e.core.crypto.init();const r=e.core.crypto.decode(t.topic,t.encryptedMessage);return e.core=null,r},getMetadata:async t=>{const e={core:new Pa({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new _D(e.core,e.core.logger),await e.sessionStore.init();const r=e.sessionStore.get(t.topic),n=r?.peer.metadata;return e.core=null,e.sessionStore=null,n}},Cf=class extends Af{constructor(t){super(t),this.events=new Le.exports,this.on=(e,r)=>this.engine.on(e,r),this.once=(e,r)=>this.engine.once(e,r),this.off=(e,r)=>this.engine.off(e,r),this.removeListener=(e,r)=>this.engine.removeListener(e,r),this.pair=async e=>{try{return await this.engine.pair(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(r){throw this.logger.error(r.message),r}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(r){throw this.logger.error(r.message),r}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(r){throw this.logger.error(r.message),r}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(r){throw this.logger.error(r.message),r}},this.getActiveSessions=()=>{try{return this.engine.getActiveSessions()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionProposals=()=>{try{return this.engine.getPendingSessionProposals()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.registerDeviceToken=e=>{try{return this.engine.registerDeviceToken(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSessionAuthenticate=e=>{try{return this.engine.approveSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSessionAuthenticate=e=>{try{return this.engine.rejectSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(r){throw this.logger.error(r.message),r}},this.metadata=t.metadata,this.name=t.name||ls,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new RD(this)}static async init(t){const e=new Cf(t);return await e.initialize(),e}async initialize(){this.logger.trace("Initialized");try{await this.engine.init(),this.logger.info("WalletKit Initialization Success")}catch(t){throw this.logger.info("WalletKit Initialization Failure"),this.logger.error(t.message),t}}};let La=Cf;La.notifications=CD;const ND=La;Fe.CLIENT_CONTEXT=ls,Fe.CLIENT_STORAGE_OPTIONS=Yf,Fe.CLIENT_STORAGE_PREFIX=Gf,Fe.IWalletKit=Af,Fe.IWalletKitEngine=Pf,Fe.IWalletKitEvents=xD,Fe.PROTOCOL=Za,Fe.PROTOCOL_VERSION=Wf,Fe.REQUEST_CONTEXT=Zf,Fe.WalletKit=ND,Fe.default=La,Object.defineProperty(Fe,"__esModule",{value:!0})});
|
|
40
40
|
//# sourceMappingURL=index.umd.js.map
|