@walletconnect/universal-provider
Version:
Universal Provider for WalletConnect Protocol
3 lines (2 loc) • 47.3 kB
JavaScript
import Le from"@walletconnect/sign-client";import{isValidObject as _,isCaipNamespace as ae,parseNamespaceKey as F,mergeArrays as k,parseChainId as U,calcExpiry as Me,isExpired as ce,getSdkError as oe,isValidArray as W}from"@walletconnect/utils";import{pino as Be,getDefaultLoggerOptions as Ge}from"@walletconnect/logger";import{formatJsonRpcRequest as he,formatJsonRpcResult as Je}from"@walletconnect/jsonrpc-utils";import P,{HttpConnection as ze}from"@walletconnect/jsonrpc-http-connection";import{JsonRpcProvider as g}from"@walletconnect/jsonrpc-provider";import ke from"events";const pe="error",We="wss://relay.walletconnect.org",Ke="wc",Ve="universal_provider",x=`${Ke}@2:${Ve}:`,de="https://rpc.walletconnect.org/v1/",ue="generic",Ye=`${de}bundler`,$="call_status",Xe=86400,m={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function K(s){return s==null||typeof s!="object"&&typeof s!="function"}function le(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function fe(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const Qe="[object RegExp]",me="[object String]",ve="[object Number]",ge="[object Boolean]",Pe="[object Arguments]",Ze="[object Symbol]",Te="[object Date]",et="[object Map]",tt="[object Set]",st="[object Array]",it="[object ArrayBuffer]",rt="[object Object]",nt="[object DataView]",at="[object Uint8Array]",ct="[object Uint8ClampedArray]",ot="[object Uint16Array]",ht="[object Uint32Array]",pt="[object Int8Array]",dt="[object Int16Array]",ut="[object Int32Array]",lt="[object Float32Array]",ft="[object Float64Array]";function V(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function mt(s,e){return O(s,void 0,s,new Map,e)}function O(s,e,t,i=new Map,n=void 0){const a=n?.(s,e,t,i);if(a!=null)return a;if(K(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]=O(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(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(O(c,void 0,t,i,n));return r}if(typeof Buffer<"u"&&Buffer.isBuffer(s))return s.subarray();if(V(s)){const r=new(Object.getPrototypeOf(s)).constructor(s.length);i.set(s,r);for(let c=0;c<s.length;c++)r[c]=O(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),y(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),y(r,s,t,i,n),r}if(s instanceof Blob){const r=new Blob([s],{type:s.type});return i.set(s,r),y(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,y(r,s,t,i,n),r}if(typeof s=="object"&&vt(s)){const r=Object.create(Object.getPrototypeOf(s));return i.set(s,r),y(r,s,t,i,n),r}return s}function y(s,e,t=s,i,n){const a=[...Object.keys(e),...le(e)];for(let r=0;r<a.length;r++){const c=a[r],o=Object.getOwnPropertyDescriptor(s,c);(o==null||o.writable)&&(s[c]=O(e[c],c,t,i,n))}}function vt(s){switch(fe(s)){case Pe:case st:case it:case nt:case ge:case Te:case lt:case ft:case pt:case dt:case ut:case et:case ve:case rt:case Qe:case tt:case me:case Ze:case at:case ct:case ot:case ht:return!0;default:return!1}}function gt(s,e){return mt(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 ve:case me:case ge:{const c=new s.constructor(s?.valueOf());return y(c,s),c}case Pe:{const c={};return y(c,s),c.length=s.length,c[Symbol.iterator]=s[Symbol.iterator],c}default:return}})}function we(s){return gt(s)}function ye(s){return s!==null&&typeof s=="object"&&fe(s)==="[object Arguments]"}function be(s){return typeof s=="object"&&s!==null}function Pt(){}function wt(s){return V(s)}function yt(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 bt(s){if(K(s))return s;if(Array.isArray(s)||V(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 It(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=L(n,r,i,new Map)}return n}function L(s,e,t,i){if(K(s)&&(s=Object(s)),e==null||typeof e!="object")return s;if(i.has(e))return bt(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),...le(e)];for(let a=0;a<n.length;a++){const r=n[a];let c=e[r],o=s[r];if(ye(c)&&(c={...c}),ye(o)&&(o={...o}),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=we(c)),Array.isArray(c))if(typeof o=="object"&&o!=null){const u=[],p=Reflect.ownKeys(o);for(let w=0;w<p.length;w++){const l=p[w];u[l]=o[l]}o=u}else o=[];const d=t(o,c,r,s,e,i);d!=null?s[r]=d:Array.isArray(c)||be(o)&&be(c)?s[r]=L(o,c,t,i):o==null&&yt(c)?s[r]=L({},c,t,i):o==null&&wt(c)?s[r]=we(c):(o===void 0||c!==void 0)&&(s[r]=c)}return s}function $t(s,...e){return It(s,...e,Pt)}var Ot=Object.defineProperty,Ct=Object.defineProperties,At=Object.getOwnPropertyDescriptors,Ie=Object.getOwnPropertySymbols,Et=Object.prototype.hasOwnProperty,Ht=Object.prototype.propertyIsEnumerable,$e=(s,e,t)=>e in s?Ot(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,M=(s,e)=>{for(var t in e||(e={}))Et.call(e,t)&&$e(s,t,e[t]);if(Ie)for(var t of Ie(e))Ht.call(e,t)&&$e(s,t,e[t]);return s},St=(s,e)=>Ct(s,At(e));function f(s,e,t){var i;const n=U(s);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${de}?chainId=${n.namespace}:${n.reference}&projectId=${t}`}function b(s){return s.includes(":")?s.split(":")[1]:s}function Oe(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Nt(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 Ce(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 B(s={},e={}){const t=Ce(Ae(s)),i=Ce(Ae(e));return $t(t,i)}function Ae(s){var e,t,i,n,a;const r={};if(!_(s))return r;for(const[c,o]of Object.entries(s)){const d=ae(c)?[c]:o.chains,u=o.methods||[],p=o.events||[],w=o.rpcMap||{},l=F(c);r[l]=St(M(M({},r[l]),o),{chains:k(d,(e=r[l])==null?void 0:e.chains),methods:k(u,(t=r[l])==null?void 0:t.methods),events:k(p,(i=r[l])==null?void 0:i.events)}),(_(w)||_(((n=r[l])==null?void 0:n.rpcMap)||{}))&&(r[l].rpcMap=M(M({},w),(a=r[l])==null?void 0:a.rpcMap))}return r}function Ee(s){return s.includes(":")?s.split(":")[2]:s}function He(s){const e={};for(const[t,i]of Object.entries(s)){const n=i.methods||[],a=i.events||[],r=i.accounts||[],c=ae(t)?[t]:i.chains?i.chains:Oe(i.accounts);e[t]={chains:c,methods:n,events:a,accounts:r}}return e}function Y(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))}function qt(s){try{const e=JSON.parse(s);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Se={},h=s=>Se[s],X=(s,e)=>{Se[s]=e};var Dt=Object.defineProperty,Ne=Object.getOwnPropertySymbols,jt=Object.prototype.hasOwnProperty,Rt=Object.prototype.propertyIsEnumerable,qe=(s,e,t)=>e in s?Dt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,De=(s,e)=>{for(var t in e||(e={}))jt.call(e,t)&&qe(s,t,e[t]);if(Ne)for(var t of Ne(e))Rt.call(e,t)&&qe(s,t,e[t]);return s};const je="eip155",_t=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],Ft=s=>s&&s.startsWith("0x")?BigInt(s).toString(10):s,Q=s=>s&&s.startsWith("0x")?s:`0x${BigInt(s).toString(16)}`,Re=s=>Object.keys(s).filter(e=>_t.includes(e)).reduce((e,t)=>(e[t]=Ut(s[t]),e),{}),Ut=s=>typeof s=="string"&&qt(s)?JSON.parse(s):s,xt=(s,e,t)=>{const{sessionProperties:i={},scopedProperties:n={}}=s,a={};if(!_(n)&&!_(i))return;const r=Re(i);for(const c of t){const o=Ft(c);if(!o)continue;a[Q(o)]=r;const d=n?.[`${je}:${o}`];if(d){const u=d?.[`${je}:${o}:${e}`];a[Q(o)]=De(De({},a[Q(o)]),Re(u||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 Lt=Object.defineProperty,Mt=(s,e,t)=>e in s?Lt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Bt=(s,e,t)=>Mt(s,typeof e!="symbol"?e+"":e,t);let Z;class re{constructor(e){Bt(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return Z||(Z=new re(e)),Z}}var Gt=Object.defineProperty,Jt=Object.defineProperties,zt=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertySymbols,kt=Object.prototype.hasOwnProperty,Wt=Object.prototype.propertyIsEnumerable,Fe=(s,e,t)=>e in s?Gt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Kt=(s,e)=>{for(var t in e||(e={}))kt.call(e,t)&&Fe(s,t,e[t]);if(_e)for(var t of _e(e))Wt.call(e,t)&&Fe(s,t,e[t]);return s},Vt=(s,e)=>Jt(s,zt(e));async function Yt(s,e){const t=U(s.result.capabilities.caip345.caip2),i=s.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(p=>Xt(t.reference,p,e))),a=n.filter(p=>p.status==="fulfilled").map(p=>p.value).filter(p=>p);n.filter(p=>p.status==="rejected").forEach(p=>console.warn("Failed to fetch transaction receipt:",p.reason));const r=!a.length||a.some(p=>!p),c=a.every(p=>p?.status==="0x1"),o=a.every(p=>p?.status==="0x0"),d=a.some(p=>p?.status==="0x0");let u;return r?u=100:c?u=200:o?u=500:d&&(u=600),{id:s.result.id,version:s.request.version,atomic:s.request.atomicRequired,chainId:s.request.chainId,capabilities:s.result.capabilities,receipts:a,status:u}}async function Xt(s,e,t){return await t(parseInt(s)).request(he("eth_getTransactionReceipt",[e]))}async function Qt({sendCalls:s,storage:e}){const t=await e.getItem($);await e.setItem($,Vt(Kt({},t),{[s.result.id]:{request:s.request,result:s.result,expiry:Me(Xe)}}))}async function Zt({resultId:s,storage:e}){const t=await e.getItem($);if(t){delete t[s],await e.setItem($,t);for(const i in t)ce(t[i].expiry)&&delete t[i];await e.setItem($,t)}}async function Tt({resultId:s,storage:e}){const t=await e.getItem($),i=t?.[s];if(i&&!ce(i.expiry))return i;await Zt({resultId:s,storage:e})}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,C=(s,e,t)=>ts(s,typeof e!="symbol"?e+"":e,t);class ss{constructor(e){C(this,"name","polkadot"),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()}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(m.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=b(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||f(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new P(i,h("disableProviderPing")))}}var is=Object.defineProperty,rs=Object.defineProperties,ns=Object.getOwnPropertyDescriptors,Ue=Object.getOwnPropertySymbols,as=Object.prototype.hasOwnProperty,cs=Object.prototype.propertyIsEnumerable,T=(s,e,t)=>e in s?is(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ee=(s,e)=>{for(var t in e||(e={}))as.call(e,t)&&T(s,t,e[t]);if(Ue)for(var t of Ue(e))cs.call(e,t)&&T(s,t,e[t]);return s},te=(s,e)=>rs(s,ns(e)),I=(s,e,t)=>T(s,typeof e!="symbol"?e+"":e,t);class os{constructor(e){I(this,"name","eip155"),I(this,"client"),I(this,"chainId"),I(this,"namespace"),I(this,"httpProviders"),I(this,"events"),I(this,"storage"),this.namespace=e.namespace,this.events=h("events"),this.client=h("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=re.getStorage(this.client.core.storage)}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);case"wallet_sendCalls":return await this.sendCalls(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(m.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||f(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new ze(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(b(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(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders=te(ee({},this.httpProviders),{[t]:this.createHttpProvider(t)}),this.httpProviders[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),u=((r=d?.sessionProperties)==null?void 0:r.capabilities)||{},p=`${c}${o.join(",")}`,w=u?.[p];if(w)return w;let l;try{l=xt(d,c,o)}catch(z){console.warn("Failed to extract capabilities from session",z)}if(l)return l;const ne=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:te(ee({},d.sessionProperties||{}),{capabilities:te(ee({},u||{}),{[p]:ne})})})}catch(z){console.warn("Failed to update session with capabilities",z)}return ne}async getCallStatus(e){var t,i,n;const a=this.client.session.get(e.topic),r=(t=a.sessionProperties)==null?void 0:t.bundler_name;if(r){const d=this.getBundlerUrl(e.chainId,r);try{return await this.getUserOperationReceipt(d,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,d)}}const c=(i=a.sessionProperties)==null?void 0:i.bundler_url;if(c)try{return await this.getUserOperationReceipt(c,e)}catch(d){console.warn("Failed to fetch call status from custom bundler",d,c)}const o=await Tt({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(o)try{return await Yt(o,this.getHttpProvider.bind(this))}catch(d){console.warn("Failed to fetch call status from stored send calls",d,o)}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(he("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`${Ye}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){var t,i,n;const a=await this.client.request(e),r=(t=e.request.params)==null?void 0:t[0],c=a?.id,o=a?.capabilities||{},d=(i=o?.caip345)==null?void 0:i.caip2,u=(n=o?.caip345)==null?void 0:n.transactionHashes;return!c||!d||!(u!=null&&u.length)||await Qt({sendCalls:{request:r,result:a},storage:this.storage}),a}}var hs=Object.defineProperty,ps=(s,e,t)=>e in s?hs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,A=(s,e,t)=>ps(s,typeof e!="symbol"?e+"":e,t);class ds{constructor(e){A(this,"name","solana"),A(this,"client"),A(this,"httpProviders"),A(this,"events"),A(this,"namespace"),A(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(m.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=b(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||f(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new P(i,h("disableProviderPing")))}}var us=Object.defineProperty,ls=(s,e,t)=>e in s?us(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E=(s,e,t)=>ls(s,typeof e!="symbol"?e+"":e,t);class fs{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(m.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=b(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||f(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new P(i,h("disableProviderPing")))}}var ms=Object.defineProperty,vs=(s,e,t)=>e in s?ms(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,H=(s,e,t)=>vs(s,typeof e!="symbol"?e+"":e,t);class gs{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||f(`${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(m.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||f(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new g(new P(i,h("disableProviderPing")))}}var Ps=Object.defineProperty,ws=(s,e,t)=>e in s?Ps(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,S=(s,e,t)=>ws(s,typeof e!="symbol"?e+"":e,t);class ys{constructor(e){S(this,"name","cip34"),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()}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(m.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=b(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 g(new P(i,h("disableProviderPing")))}}var bs=Object.defineProperty,Is=(s,e,t)=>e in s?bs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,N=(s,e,t)=>Is(s,typeof e!="symbol"?e+"":e,t);class $s{constructor(e){N(this,"name","elrond"),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()}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(m.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=b(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||f(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new P(i,h("disableProviderPing")))}}var Os=Object.defineProperty,Cs=(s,e,t)=>e in s?Os(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,q=(s,e,t)=>Cs(s,typeof e!="symbol"?e+"":e,t);class As{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(m.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=b(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||f(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new P(i,h("disableProviderPing")))}}var Es=Object.defineProperty,Hs=(s,e,t)=>e in s?Es(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,D=(s,e,t)=>Hs(s,typeof e!="symbol"?e+"":e,t);class Ss{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||f(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(m.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||f(e,this.namespace);return typeof i>"u"?void 0:new g(new P(i,h("disableProviderPing")))}}var Ns=Object.defineProperty,qs=(s,e,t)=>e in s?Ns(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,j=(s,e,t)=>qs(s,typeof e!="symbol"?e+"":e,t);class Ds{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||f(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(m.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||f(e,this.namespace);return typeof i>"u"?void 0:new g(new P(i))}}var js=Object.defineProperty,Rs=(s,e,t)=>e in s?js(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 _s{constructor(e){R(this,"name",ue),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(m.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 U(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=U(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||f(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new g(new P(i,h("disableProviderPing")))}}var Fs=Object.defineProperty,Us=Object.defineProperties,xs=Object.getOwnPropertyDescriptors,xe=Object.getOwnPropertySymbols,Ls=Object.prototype.hasOwnProperty,Ms=Object.prototype.propertyIsEnumerable,se=(s,e,t)=>e in s?Fs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,G=(s,e)=>{for(var t in e||(e={}))Ls.call(e,t)&&se(s,t,e[t]);if(xe)for(var t of xe(e))Ms.call(e,t)&&se(s,t,e[t]);return s},ie=(s,e)=>Us(s,xs(e)),v=(s,e,t)=>se(s,typeof e!="symbol"?e+"":e,t);class J{constructor(e){v(this,"client"),v(this,"namespaces"),v(this,"optionalNamespaces"),v(this,"sessionProperties"),v(this,"scopedProperties"),v(this,"events",new ke),v(this,"rpcProviders",{}),v(this,"session"),v(this,"providerOpts"),v(this,"logger"),v(this,"uri"),v(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Be(Ge({level:e?.logger||pe})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new J(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:G({},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,Je(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:oe("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=He(this.session.namespaces);this.namespaces=B(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=He(n.namespaces);return this.namespaces=B(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(!W(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 Le.init({core:this.providerOpts.core,logger:this.providerOpts.logger||pe,relayUrl:this.providerOpts.relayUrl||We,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=>F(t)))];X("client",this.client),X("events",this.events),X("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=Nt(t,this.session);if(i?.length===0)return;const n=Oe(i),a=B(this.namespaces,this.optionalNamespaces),r=ie(G({},a[t]),{accounts:i,chains:n});switch(t){case"eip155":this.rpcProviders[t]=new os({namespace:r});break;case"algorand":this.rpcProviders[t]=new gs({namespace:r});break;case"solana":this.rpcProviders[t]=new ds({namespace:r});break;case"cosmos":this.rpcProviders[t]=new fs({namespace:r});break;case"polkadot":this.rpcProviders[t]=new ss({namespace:r});break;case"cip34":this.rpcProviders[t]=new ys({namespace:r});break;case"elrond":this.rpcProviders[t]=new $s({namespace:r});break;case"multiversx":this.rpcProviders[t]=new As({namespace:r});break;case"near":this.rpcProviders[t]=new Ss({namespace:r});break;case"tezos":this.rpcProviders[t]=new Ds({namespace:r});break;default:this.rpcProviders[t]=new _s({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&&W(r)&&this.events.emit("accountsChanged",r.map(Ee))}else if(a.name==="chainChanged"){const r=i.chainId,c=i.event.data,o=F(r),d=Y(r)!==Y(c)?`${o}:${Y(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=ie(G({},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",ie(G({},oe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(m.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ue]}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=B(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=>F(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=F(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);const a=this.getProvider(i).getDefaultChain();t?(this.events.emit("chainChanged",n),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:a,newChainId:e})):this.getProvider(i).setDefaultChain(n),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(Ee);if(!W(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(`${x}/${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(`${x}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${x}/${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(x)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}}const Bs=J;export{Bs as UniversalProvider,J as default};
//# sourceMappingURL=index.es.js.map