@walletconnect/universal-provider
Version:
Universal Provider for WalletConnect Protocol
3 lines (2 loc) • 44.8 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});var Se=require("@walletconnect/sign-client"),p=require("@walletconnect/utils"),Z=require("@walletconnect/logger"),T=require("@walletconnect/jsonrpc-http-connection"),v=require("@walletconnect/jsonrpc-provider"),ee=require("@walletconnect/jsonrpc-utils"),qe=require("events");function B(s){return s&&typeof s=="object"&&"default"in s?s:{default:s}}var De=B(Se),P=B(T),je=B(qe);const te="error",Re="wss://relay.walletconnect.org",_e="wc",Fe="universal_provider",_=`${_e}@2:${Fe}:`,se="https://rpc.walletconnect.org/v1/",ie="generic",Ue=`${se}bundler`,f={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function G(s){return s==null||typeof s!="object"&&typeof s!="function"}function re(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function ne(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const xe="[object RegExp]",ae="[object String]",ce="[object Number]",oe="[object Boolean]",he="[object Arguments]",Le="[object Symbol]",Me="[object Date]",Je="[object Map]",Be="[object Set]",Ge="[object Array]",ke="[object ArrayBuffer]",ze="[object Object]",We="[object DataView]",Ke="[object Uint8Array]",Ve="[object Uint8ClampedArray]",Xe="[object Uint16Array]",Ye="[object Uint32Array]",Qe="[object Int8Array]",Ze="[object Int16Array]",Te="[object Int32Array]",et="[object Float32Array]",tt="[object Float64Array]";function k(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function st(s,e){return $(s,void 0,s,new Map,e)}function $(s,e,t,i=new Map,n=void 0){const a=n?.(s,e,t,i);if(a!=null)return a;if(G(s))return s;if(i.has(s))return i.get(s);if(Array.isArray(s)){const r=new Array(s.length);i.set(s,r);for(let c=0;c<s.length;c++)r[c]=$(s[c],c,t,i,n);return Object.hasOwn(s,"index")&&(r.index=s.index),Object.hasOwn(s,"input")&&(r.input=s.input),r}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp){const r=new RegExp(s.source,s.flags);return r.lastIndex=s.lastIndex,r}if(s instanceof Map){const r=new Map;i.set(s,r);for(const[c,o]of s)r.set(c,$(o,c,t,i,n));return r}if(s instanceof Set){const r=new Set;i.set(s,r);for(const c of s)r.add($(c,void 0,t,i,n));return r}if(typeof Buffer<"u"&&Buffer.isBuffer(s))return s.subarray();if(k(s)){const r=new(Object.getPrototypeOf(s)).constructor(s.length);i.set(s,r);for(let c=0;c<s.length;c++)r[c]=$(s[c],c,t,i,n);return r}if(s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);if(s instanceof DataView){const r=new DataView(s.buffer.slice(0),s.byteOffset,s.byteLength);return i.set(s,r),b(r,s,t,i,n),r}if(typeof File<"u"&&s instanceof File){const r=new File([s],s.name,{type:s.type});return i.set(s,r),b(r,s,t,i,n),r}if(s instanceof Blob){const r=new Blob([s],{type:s.type});return i.set(s,r),b(r,s,t,i,n),r}if(s instanceof Error){const r=new s.constructor;return i.set(s,r),r.message=s.message,r.name=s.name,r.stack=s.stack,r.cause=s.cause,b(r,s,t,i,n),r}if(typeof s=="object"&&it(s)){const r=Object.create(Object.getPrototypeOf(s));return i.set(s,r),b(r,s,t,i,n),r}return s}function b(s,e,t=s,i,n){const a=[...Object.keys(e),...re(e)];for(let r=0;r<a.length;r++){const c=a[r],o=Object.getOwnPropertyDescriptor(s,c);(o==null||o.writable)&&(s[c]=$(e[c],c,t,i,n))}}function it(s){switch(ne(s)){case he:case Ge:case ke:case We:case oe:case Me:case et:case tt:case Qe:case Ze:case Te:case Je:case ce:case ze:case xe:case Be:case ae:case Le:case Ke:case Ve:case Xe:case Ye:return!0;default:return!1}}function rt(s,e){return st(s,(t,i,n,a)=>{const r=e?.(t,i,n,a);if(r!=null)return r;if(typeof s=="object")switch(Object.prototype.toString.call(s)){case ce:case ae:case oe:{const c=new s.constructor(s?.valueOf());return b(c,s),c}case he:{const c={};return b(c,s),c.length=s.length,c[Symbol.iterator]=s[Symbol.iterator],c}default:return}})}function pe(s){return rt(s)}function de(s){return s!==null&&typeof s=="object"&&ne(s)==="[object Arguments]"}function ue(s){return typeof s=="object"&&s!==null}function nt(){}function at(s){return k(s)}function ct(s){if(typeof s!="object"||s==null)return!1;if(Object.getPrototypeOf(s)===null)return!0;if(Object.prototype.toString.call(s)!=="[object Object]"){const t=s[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(s,Symbol.toStringTag)?.writable?!1:s.toString()===`[object ${t}]`}let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}function ot(s){if(G(s))return s;if(Array.isArray(s)||k(s)||s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);const e=Object.getPrototypeOf(s),t=e.constructor;if(s instanceof Date||s instanceof Map||s instanceof Set)return new t(s);if(s instanceof RegExp){const i=new t(s);return i.lastIndex=s.lastIndex,i}if(s instanceof DataView)return new t(s.buffer.slice(0));if(s instanceof Error){const i=new t(s.message);return i.stack=s.stack,i.name=s.name,i.cause=s.cause,i}if(typeof File<"u"&&s instanceof File)return new t([s],s.name,{type:s.type,lastModified:s.lastModified});if(typeof s=="object"){const i=Object.create(e);return Object.assign(i,s)}return s}function ht(s,...e){const t=e.slice(0,-1),i=e[e.length-1];let n=s;for(let a=0;a<t.length;a++){const r=t[a];n=F(n,r,i,new Map)}return n}function F(s,e,t,i){if(G(s)&&(s=Object(s)),e==null||typeof e!="object")return s;if(i.has(e))return ot(i.get(e));if(i.set(e,s),Array.isArray(e)){e=e.slice();for(let a=0;a<e.length;a++)e[a]=e[a]??void 0}const n=[...Object.keys(e),...re(e)];for(let a=0;a<n.length;a++){const r=n[a];let c=e[r],o=s[r];if(de(c)&&(c={...c}),de(o)&&(o={...o}),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=pe(c)),Array.isArray(c))if(typeof o=="object"&&o!=null){const g=[],y=Reflect.ownKeys(o);for(let w=0;w<y.length;w++){const u=y[w];g[u]=o[u]}o=g}else o=[];const d=t(o,c,r,s,e,i);d!=null?s[r]=d:Array.isArray(c)||ue(o)&&ue(c)?s[r]=F(o,c,t,i):o==null&&ct(c)?s[r]=F({},c,t,i):o==null&&at(c)?s[r]=pe(c):(o===void 0||c!==void 0)&&(s[r]=c)}return s}function pt(s,...e){return ht(s,...e,nt)}var dt=Object.defineProperty,ut=Object.defineProperties,lt=Object.getOwnPropertyDescriptors,le=Object.getOwnPropertySymbols,ft=Object.prototype.hasOwnProperty,mt=Object.prototype.propertyIsEnumerable,fe=(s,e,t)=>e in s?dt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,U=(s,e)=>{for(var t in e||(e={}))ft.call(e,t)&&fe(s,t,e[t]);if(le)for(var t of le(e))mt.call(e,t)&&fe(s,t,e[t]);return s},vt=(s,e)=>ut(s,lt(e));function l(s,e,t){var i;const n=p.parseChainId(s);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${se}?chainId=${n.namespace}:${n.reference}&projectId=${t}`}function I(s){return s.includes(":")?s.split(":")[1]:s}function me(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function gt(s,e){const t=Object.keys(e.namespaces).filter(n=>n.includes(s));if(!t.length)return[];const i=[];return t.forEach(n=>{const a=e.namespaces[n].accounts;i.push(...a)}),i}function ve(s){return Object.fromEntries(Object.entries(s).filter(([e,t])=>{var i,n;return((i=t?.chains)==null?void 0:i.length)&&((n=t?.chains)==null?void 0:n.length)>0}))}function x(s={},e={}){const t=ve(ge(s)),i=ve(ge(e));return pt(t,i)}function ge(s){var e,t,i,n,a;const r={};if(!p.isValidObject(s))return r;for(const[c,o]of Object.entries(s)){const d=p.isCaipNamespace(c)?[c]:o.chains,g=o.methods||[],y=o.events||[],w=o.rpcMap||{},u=p.parseNamespaceKey(c);r[u]=vt(U(U({},r[u]),o),{chains:p.mergeArrays(d,(e=r[u])==null?void 0:e.chains),methods:p.mergeArrays(g,(t=r[u])==null?void 0:t.methods),events:p.mergeArrays(y,(i=r[u])==null?void 0:i.events)}),(p.isValidObject(w)||p.isValidObject(((n=r[u])==null?void 0:n.rpcMap)||{}))&&(r[u].rpcMap=U(U({},w),(a=r[u])==null?void 0:a.rpcMap))}return r}function Pe(s){return s.includes(":")?s.split(":")[2]:s}function we(s){const e={};for(const[t,i]of Object.entries(s)){const n=i.methods||[],a=i.events||[],r=i.accounts||[],c=p.isCaipNamespace(t)?[t]:i.chains?i.chains:me(i.accounts);e[t]={chains:c,methods:n,events:a,accounts:r}}return e}function z(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const ye={},h=s=>ye[s],W=(s,e)=>{ye[s]=e};var Pt=Object.defineProperty,be=Object.getOwnPropertySymbols,wt=Object.prototype.hasOwnProperty,yt=Object.prototype.propertyIsEnumerable,Ie=(s,e,t)=>e in s?Pt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$e=(s,e)=>{for(var t in e||(e={}))wt.call(e,t)&&Ie(s,t,e[t]);if(be)for(var t of be(e))yt.call(e,t)&&Ie(s,t,e[t]);return s};const Oe="eip155",bt=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],It=s=>s&&s.startsWith("0x")?BigInt(s).toString(10):s,K=s=>s&&s.startsWith("0x")?s:`0x${BigInt(s).toString(16)}`,Ae=s=>Object.keys(s).filter(e=>bt.includes(e)).reduce((e,t)=>(e[t]=s[t],e),{}),$t=(s,e,t)=>{const{sessionProperties:i={},scopedProperties:n={}}=s,a={};if(!p.isValidObject(n)&&!p.isValidObject(i))return;const r=Ae(i);for(const c of t){const o=It(c);if(!o)continue;a[K(o)]=r;const d=n?.[`${Oe}:${o}`];if(d){const g=d?.[`${Oe}:${o}:${e}`];a[K(o)]=$e($e({},a[K(o)]),Ae(g||d))}}for(const[c,o]of Object.entries(a))Object.keys(o).length===0&&delete a[c];return Object.keys(a).length>0?a:void 0};var Ot=Object.defineProperty,At=(s,e,t)=>e in s?Ot(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,O=(s,e,t)=>At(s,typeof e!="symbol"?e+"":e,t);class Ct{constructor(e){O(this,"name","polkadot"),O(this,"client"),O(this,"httpProviders"),O(this,"events"),O(this,"namespace"),O(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=I(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var Et=Object.defineProperty,Ht=Object.defineProperties,Nt=Object.getOwnPropertyDescriptors,Ce=Object.getOwnPropertySymbols,St=Object.prototype.hasOwnProperty,qt=Object.prototype.propertyIsEnumerable,V=(s,e,t)=>e in s?Et(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ee=(s,e)=>{for(var t in e||(e={}))St.call(e,t)&&V(s,t,e[t]);if(Ce)for(var t of Ce(e))qt.call(e,t)&&V(s,t,e[t]);return s},He=(s,e)=>Ht(s,Nt(e)),A=(s,e,t)=>V(s,typeof e!="symbol"?e+"":e,t);class Dt{constructor(e){A(this,"name","eip155"),A(this,"client"),A(this,"chainId"),A(this,"namespace"),A(this,"httpProviders"),A(this,"events"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||l(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new T.HttpConnection(i,h("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=parseInt(I(t));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let n=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const a=parseInt(n,16);if(this.isChainApproved(a))this.setDefaultChain(`${a}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${a}`);else throw new Error(`Failed to switch to chain 'eip155:${a}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,n,a,r;const c=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0],o=((a=(n=e.request)==null?void 0:n.params)==null?void 0:a[1])||[];if(!c)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const d=this.client.session.get(e.topic),g=((r=d?.sessionProperties)==null?void 0:r.capabilities)||{},y=`${c}${o.join(",")}`,w=g?.[y];if(w)return w;let u;try{u=$t(d,c,o)}catch(J){console.warn("Failed to extract capabilities from session",J)}if(u)return u;const Q=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:He(Ee({},d.sessionProperties||{}),{capabilities:He(Ee({},g||{}),{[y]:Q})})})}catch(J){console.warn("Failed to update session with capabilities",J)}return Q}async getCallStatus(e){var t,i;const n=this.client.session.get(e.topic),a=(t=n.sessionProperties)==null?void 0:t.bundler_name;if(a){const c=this.getBundlerUrl(e.chainId,a);try{return await this.getUserOperationReceipt(c,e)}catch(o){console.warn("Failed to fetch call status from bundler",o,c)}}const r=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(r)try{return await this.getUserOperationReceipt(r,e)}catch(c){console.warn("Failed to fetch call status from custom bundler",c,r)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const n=new URL(e),a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee.formatJsonRpcRequest("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!a.ok)throw new Error(`Failed to fetch user operation receipt - ${a.status}`);return await a.json()}getBundlerUrl(e,t){return`${Ue}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var jt=Object.defineProperty,Rt=(s,e,t)=>e in s?jt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,C=(s,e,t)=>Rt(s,typeof e!="symbol"?e+"":e,t);class _t{constructor(e){C(this,"name","solana"),C(this,"client"),C(this,"httpProviders"),C(this,"events"),C(this,"namespace"),C(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=I(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var Ft=Object.defineProperty,Ut=(s,e,t)=>e in s?Ft(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E=(s,e,t)=>Ut(s,typeof e!="symbol"?e+"":e,t);class xt{constructor(e){E(this,"name","cosmos"),E(this,"client"),E(this,"httpProviders"),E(this,"events"),E(this,"namespace"),E(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=I(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var Lt=Object.defineProperty,Mt=(s,e,t)=>e in s?Lt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,H=(s,e,t)=>Mt(s,typeof e!="symbol"?e+"":e,t);class Jt{constructor(e){H(this,"name","algorand"),H(this,"client"),H(this,"httpProviders"),H(this,"events"),H(this,"namespace"),H(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||l(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var Bt=Object.defineProperty,Gt=(s,e,t)=>e in s?Bt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,N=(s,e,t)=>Gt(s,typeof e!="symbol"?e+"":e,t);class kt{constructor(e){N(this,"name","cip34"),N(this,"client"),N(this,"httpProviders"),N(this,"events"),N(this,"namespace"),N(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),n=I(t);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var zt=Object.defineProperty,Wt=(s,e,t)=>e in s?zt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,S=(s,e,t)=>Wt(s,typeof e!="symbol"?e+"":e,t);class Kt{constructor(e){S(this,"name","elrond"),S(this,"client"),S(this,"httpProviders"),S(this,"events"),S(this,"namespace"),S(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=I(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var Vt=Object.defineProperty,Xt=(s,e,t)=>e in s?Vt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,q=(s,e,t)=>Xt(s,typeof e!="symbol"?e+"":e,t);class Yt{constructor(e){q(this,"name","multiversx"),q(this,"client"),q(this,"httpProviders"),q(this,"events"),q(this,"namespace"),q(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=I(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var Qt=Object.defineProperty,Zt=(s,e,t)=>e in s?Qt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,D=(s,e,t)=>Zt(s,typeof e!="symbol"?e+"":e,t);class Tt{constructor(e){D(this,"name","near"),D(this,"client"),D(this,"httpProviders"),D(this,"events"),D(this,"namespace"),D(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||l(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace);return typeof i>"u"?void 0:new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var es=Object.defineProperty,ts=(s,e,t)=>e in s?es(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,j=(s,e,t)=>ts(s,typeof e!="symbol"?e+"":e,t);class ss{constructor(e){j(this,"name","tezos"),j(this,"client"),j(this,"httpProviders"),j(this,"events"),j(this,"namespace"),j(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||l(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace);return typeof i>"u"?void 0:new v.JsonRpcProvider(new P.default(i))}}var is=Object.defineProperty,rs=(s,e,t)=>e in s?is(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,R=(s,e,t)=>rs(s,typeof e!="symbol"?e+"":e,t);class ns{constructor(e){R(this,"name",ie),R(this,"client"),R(this,"httpProviders"),R(this,"events"),R(this,"namespace"),R(this,"chainId"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(f.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return p.parseChainId(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(n=>{const a=p.parseChainId(n);i[a.reference]=this.createHttpProvider(n)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||l(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.JsonRpcProvider(new P.default(i,h("disableProviderPing")))}}var as=Object.defineProperty,cs=Object.defineProperties,os=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertySymbols,hs=Object.prototype.hasOwnProperty,ps=Object.prototype.propertyIsEnumerable,X=(s,e,t)=>e in s?as(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,L=(s,e)=>{for(var t in e||(e={}))hs.call(e,t)&&X(s,t,e[t]);if(Ne)for(var t of Ne(e))ps.call(e,t)&&X(s,t,e[t]);return s},Y=(s,e)=>cs(s,os(e)),m=(s,e,t)=>X(s,typeof e!="symbol"?e+"":e,t);class M{constructor(e){m(this,"client"),m(this,"namespaces"),m(this,"optionalNamespaces"),m(this,"sessionProperties"),m(this,"scopedProperties"),m(this,"events",new je.default),m(this,"rpcProviders",{}),m(this,"session"),m(this,"providerOpts"),m(this,"logger"),m(this,"uri"),m(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Z.pino(Z.getDefaultLoggerOptions({level:e?.logger||te})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new M(e);return await t.initialize(),t}async request(e,t,i){const[n,a]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:L({},e),chainId:`${n}:${a}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,n){const a=new Date().getTime();this.request(e,i,n).then(r=>t(null,ee.formatJsonRpcResult(a,r))).catch(r=>t(r,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:p.getSdkError("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const a=await n();if(this.session=a.session,this.session){const r=we(this.session.namespaces);this.namespaces=x(this.namespaces,r),await this.persist("namespaces",this.namespaces),this.onConnect()}return a}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const n=await i();this.session=n;const a=we(n.namespaces);return this.namespaces=x(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!p.isValidArray(t))return;for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}catch(t){this.logger.warn("Failed to cleanup pending pairings",t)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await De.default.init({core:this.providerOpts.core,logger:this.providerOpts.logger||te,relayUrl:this.providerOpts.relayUrl||Re,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>p.parseNamespaceKey(t)))];W("client",this.client),W("events",this.events),W("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=gt(t,this.session);if(i?.length===0)return;const n=me(i),a=x(this.namespaces,this.optionalNamespaces),r=Y(L({},a[t]),{accounts:i,chains:n});switch(t){case"eip155":this.rpcProviders[t]=new Dt({namespace:r});break;case"algorand":this.rpcProviders[t]=new Jt({namespace:r});break;case"solana":this.rpcProviders[t]=new _t({namespace:r});break;case"cosmos":this.rpcProviders[t]=new xt({namespace:r});break;case"polkadot":this.rpcProviders[t]=new Ct({namespace:r});break;case"cip34":this.rpcProviders[t]=new kt({namespace:r});break;case"elrond":this.rpcProviders[t]=new Kt({namespace:r});break;case"multiversx":this.rpcProviders[t]=new Yt({namespace:r});break;case"near":this.rpcProviders[t]=new Tt({namespace:r});break;case"tezos":this.rpcProviders[t]=new ss({namespace:r});break;default:this.rpcProviders[t]=new ns({namespace:r})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:n}=e;if(n!==((t=this.session)==null?void 0:t.topic))return;const{event:a}=i;if(a.name==="accountsChanged"){const r=a.data;r&&p.isValidArray(r)&&this.events.emit("accountsChanged",r.map(Pe))}else if(a.name==="chainChanged"){const r=i.chainId,c=i.event.data,o=p.parseNamespaceKey(r),d=z(r)!==z(c)?`${o}:${z(c)}`:r;this.onChainChanged(d)}else this.events.emit(a.name,a.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:a}=t,r=(n=this.client)==null?void 0:n.session.get(e);this.session=Y(L({},r),{namespaces:a}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Y(L({},p.getSdkError("USER_DISCONNECTED")),{data:e.topic})))}),this.on(f.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ie]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:a}=e;this.optionalNamespaces=x(t,i),this.sessionProperties=n,this.scopedProperties=a}validateChain(e){const[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(r=>p.parseNamespaceKey(r)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const n=p.parseNamespaceKey(Object.keys(this.namespaces)[0]),a=this.rpcProviders[n].getDefaultChain();return[n,a]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);if(!n)return;this.updateNamespaceChain(i,n),this.events.emit("chainChanged",n);const a=this.getProvider(i).getDefaultChain();t||this.getProvider(i).setDefaultChain(n),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:a,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:i}){var n,a;try{if(t===i)return;const r=(a=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:a.accounts;if(!r)return;const c=r.filter(o=>o.includes(`${i}:`)).map(Pe);if(!p.isValidArray(c))return;this.events.emit("accountsChanged",c)}catch(r){this.logger.warn("Failed to emit accountsChanged on chain change",r)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,n={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${_}/${e}${n}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${_}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${_}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(_)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}}const ds=M;exports.UniversalProvider=ds,exports.default=M;
//# sourceMappingURL=index.cjs.js.map