From 77d00060251677deabee3e9229349adec5ac8dc3 Mon Sep 17 00:00:00 2001 From: Nguyen Van Viet Date: Thu, 11 Apr 2024 17:48:25 +0700 Subject: [PATCH] feat: implement eip-6963 (#2489) * feat: implement eip-6963 * refactor: remove unused code * fix: update chainId from wallet * fix: update chainId from wallet * fix: lo price * fix: CR-841 * fix: wallet connect * fix: mobile coinbase link * fix: network modal --- package.json | 10 +- ...alletconnect+ethereum-provider+2.8.1.patch | 29 -- patches/@web3-react+metamask+8.2.1.patch | 20 -- src/components/AddToMetamask/index.tsx | 8 +- .../components/DraggableNetworkButton.tsx | 14 +- src/components/Header/web3/SelectWallet.tsx | 22 +- .../Header/web3/WalletModal/Option.tsx | 208 ++++--------- .../Header/web3/WalletModal/PendingView.tsx | 50 +-- .../Header/web3/WalletModal/WarningBox.tsx | 15 +- .../Header/web3/WalletModal/index.tsx | 192 +++--------- .../web3/WalletModal/useConnections.tsx | 69 +++++ .../SwapForm/SlippageSettingGroup.tsx | 7 +- .../TransactionConfirmationModal/index.tsx | 18 +- src/components/WalletPopup/WalletView.tsx | 12 +- src/components/Web3ReactManager/index.tsx | 34 --- src/components/swapv2/LimitOrder/helpers.ts | 7 +- src/connection/WalletConnectV2.ts | 61 ++++ src/connection/activate.ts | 80 +++++ src/connection/eagerlyConnect.ts | 75 +++++ src/connection/eip6963/index.ts | 180 +++++++++++ src/connection/eip6963/providers.ts | 66 ++++ src/connection/eip6963/types.ts | 23 ++ src/connection/eip6963/utils.ts | 39 +++ src/connection/index.ts | 288 ++++++++++++++++++ src/connection/meta.ts | 29 ++ src/connection/types.ts | 37 +++ src/connection/utils.ts | 94 ++++++ src/constants/connectors/utils.ts | 6 +- src/constants/wallets.ts | 17 +- src/hooks/index.ts | 53 +--- src/hooks/useSwapCallbackV3.ts | 6 +- src/hooks/useSwapV2Callback.ts | 6 +- src/hooks/web3/useActivationWallet.ts | 60 ---- src/hooks/web3/useChangeNetwork.ts | 41 +-- src/hooks/web3/useDisconnectWallet.ts | 46 +-- src/hooks/web3/useEagerConnect.ts | 81 ----- .../web3/useSyncNetworkParamWithStore.ts | 20 +- src/index.tsx | 19 +- src/pages/App.tsx | 159 +++++----- src/pages/Oauth/AuthForm/useAutoSignIn.tsx | 6 +- src/react-app-env.d.ts | 2 + src/state/authen/hooks.ts | 17 +- src/state/tokenPrices/hooks.ts | 7 +- src/state/transactions/updater.tsx | 33 +- src/state/user/actions.ts | 4 + src/state/user/reducer.ts | 23 ++ src/utils/index.ts | 24 -- src/utils/isDataUri.ts | 7 + src/utils/sendTransaction.ts | 3 +- src/utils/sentry.ts | 5 +- src/utils/walletMeta.ts | 91 ++++++ yarn.lock | 61 ++-- 52 files changed, 1586 insertions(+), 898 deletions(-) delete mode 100644 patches/@walletconnect+ethereum-provider+2.8.1.patch delete mode 100644 patches/@web3-react+metamask+8.2.1.patch create mode 100644 src/components/Header/web3/WalletModal/useConnections.tsx delete mode 100644 src/components/Web3ReactManager/index.tsx create mode 100644 src/connection/WalletConnectV2.ts create mode 100644 src/connection/activate.ts create mode 100644 src/connection/eagerlyConnect.ts create mode 100644 src/connection/eip6963/index.ts create mode 100644 src/connection/eip6963/providers.ts create mode 100644 src/connection/eip6963/types.ts create mode 100644 src/connection/eip6963/utils.ts create mode 100644 src/connection/index.ts create mode 100644 src/connection/meta.ts create mode 100644 src/connection/types.ts create mode 100644 src/connection/utils.ts delete mode 100644 src/hooks/web3/useActivationWallet.ts delete mode 100644 src/hooks/web3/useEagerConnect.ts create mode 100644 src/utils/isDataUri.ts create mode 100644 src/utils/walletMeta.ts diff --git a/package.json b/package.json index 54d4cb6ec9..0cd12a2e23 100644 --- a/package.json +++ b/package.json @@ -45,15 +45,15 @@ "dependencies": { "@0xsquid/sdk": "^2.8.1", "@apollo/client": "^3.7.1", - "@blocto/web3-react-connector": "^1.0.0", + "@blocto/web3-react-connector": "^1.0.7", "@coinbase/wallet-sdk": "^3.0.4", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@holdstation/paymaster-helper": "^2.0.20", - "@kyberswap/oauth2": "1.0.2", "@kyberswap/krystal-walletconnect-v2": "0.0.1", "@kyberswap/ks-sdk-classic": "^1.0.3", "@kyberswap/ks-sdk-core": "1.1.3", "@kyberswap/ks-sdk-elastic": "^1.1.2", + "@kyberswap/oauth2": "1.0.2", "@lingui/macro": "^4.6.0", "@lingui/react": "^4.6.0", "@popperjs/core": "^2.11.6", @@ -67,8 +67,11 @@ "@use-gesture/react": "^10.2.27", "@web3-react/coinbase-wallet": "8.2.0", "@web3-react/core": "8.2.0", + "@web3-react/eip1193": "8.2.0", + "@web3-react/empty": "8.2.0", "@web3-react/gnosis-safe": "8.2.0", - "@web3-react/metamask": "^8.2.1", + "@web3-react/metamask": "8.2.1", + "@web3-react/network": "8.2.0", "@web3-react/types": "8.2.0", "@web3-react/walletconnect-v2": "^8.3.3", "@zkmelabs/widget": "^0.1.3", @@ -89,6 +92,7 @@ "html2canvas": "^1.4.1", "html5-qrcode": "^2.3.8", "inter-ui": "^3.19.3", + "jotai": "1.3.7", "jsbi": "^3.2.5", "lightweight-charts": "^3.3.0", "memoize-one": "^6.0.0", diff --git a/patches/@walletconnect+ethereum-provider+2.8.1.patch b/patches/@walletconnect+ethereum-provider+2.8.1.patch deleted file mode 100644 index 35f3ecddd5..0000000000 --- a/patches/@walletconnect+ethereum-provider+2.8.1.patch +++ /dev/null @@ -1,29 +0,0 @@ -diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js -index 4c23c8c..b87fc08 100644 ---- a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js -+++ b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js -@@ -1,2 +1,2 @@ --"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var A=require("events"),h=require("@walletconnect/utils"),T=require("@walletconnect/universal-provider");function R(i){if(i&&i.__esModule)return i;var t=Object.create(null);return i&&Object.keys(i).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return i[e]}})}}),t.default=i,Object.freeze(t)}const S="wc",j="ethereum_provider",N=`${S}@2:${j}:`,q="https://rpc.walletconnect.com/v1/",u=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m=["chainChanged","accountsChanged"],$=["message","disconnect","connect"];var U=Object.defineProperty,Q=Object.defineProperties,L=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,O=(i,t,e)=>t in i?U(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,I=(i,t)=>{for(var e in t||(t={}))V.call(t,e)&&O(i,e,t[e]);if(_)for(var e of _(t))H.call(t,e)&&O(i,e,t[e]);return i},y=(i,t)=>Q(i,L(t));function C(i){return Number(i[0].split(":")[1])}function E(i){return`0x${i.toString(16)}`}function z(i){const{chains:t,optionalChains:e,methods:s,optionalMethods:n,events:a,optionalEvents:l,rpcMap:c}=i;if(!h.isValidArray(t))throw new Error("Invalid chains");const o=t,r=s||u,f=a||m,b={[C(o)]:c[C(o)]},w={chains:o,methods:r,events:f,rpcMap:b},d=a?.filter(v=>!m.includes(v)),p=s?.filter(v=>!u.includes(v));if(!e&&!l&&!n&&!(d!=null&&d.length)&&!(p!=null&&p.length))return{required:w};const M=d?.length&&p?.length||!e,P={chains:[...new Set(M?o.concat(e||[]):e)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(l||[]))],rpcMap:c};return{required:w,optional:P}}class g{constructor(){this.events=new A.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,e)=>(this.events.on(t,e),this),this.once=(t,e)=>(this.events.once(t,e),this),this.removeListener=(t,e)=>(this.events.removeListener(t,e),this),this.off=(t,e)=>(this.events.off(t,e),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const e=new g;return await e.initialize(t),e}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,e){this.signer.sendAsync(t,e,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:e,optional:s}=z(this.rpc);try{const n=await new Promise(async(l,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(y(I({namespaces:{[this.namespace]:e}},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic})).then(r=>{l(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;this.setChainIds(this.rpc.chains);const a=h.getAccountsFromNamespaces(n.namespaces,[this.namespace]);this.setAccounts(a),this.events.emit("connect",{chainId:E(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",E(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",y(I({},h.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var e,s;this.rpc.showQrModal&&((e=this.modal)==null||e.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",E(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.setHttpProvider(e)}}parseAccountId(t){const[e,s,n]=t.split(":");return{chainId:`${e}:${s}`,address:n}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;return{chains:((e=t.chains)==null?void 0:e.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||u,events:t?.events||m,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(s=t?.qrModalOptions)!=null?s:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(n=>{s[n]=this.getRpcUrl(n,e)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await T.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let e;try{const{WalletConnectModal:s}=await Promise.resolve().then(function(){return R(require("@walletconnect/modal"))});e=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(e)try{this.modal=new e(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:n}=t;e&&h.isValidArray(e)&&(this.rpc.chains=e.map(a=>this.formatChainId(a)),e.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)})),s&&h.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(a=>this.formatChainId(a)),s.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${q}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const G=g;exports.EthereumProvider=G,exports.OPTIONAL_EVENTS=$,exports.OPTIONAL_METHODS=D,exports.REQUIRED_EVENTS=m,exports.REQUIRED_METHODS=u,exports.default=g; -+"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var A=require("events"),h=require("@walletconnect/utils"),T=require("@walletconnect/universal-provider");function R(i){if(i&&i.__esModule)return i;var t=Object.create(null);return i&&Object.keys(i).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return i[e]}})}}),t.default=i,Object.freeze(t)}const S="wc",j="ethereum_provider",N=`${S}@2:${j}:`,q="https://rpc.walletconnect.com/v1/",u=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m=["chainChanged","accountsChanged"],$=["message","disconnect","connect"];var U=Object.defineProperty,Q=Object.defineProperties,L=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,O=(i,t,e)=>t in i?U(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,I=(i,t)=>{for(var e in t||(t={}))V.call(t,e)&&O(i,e,t[e]);if(_)for(var e of _(t))H.call(t,e)&&O(i,e,t[e]);return i},y=(i,t)=>Q(i,L(t));function C(i){return Number(i[0].split(":")[1])}function E(i){return`0x${i.toString(16)}`}function z(i){const{chains:t,optionalChains:e,methods:s,optionalMethods:n,events:a,optionalEvents:l,rpcMap:c}=i;if(!h.isValidArray(t))throw new Error("Invalid chains");const o=t,r=s||u,f=a||m,b={[C(o)]:c[C(o)]},w={chains:o,methods:r,events:f,rpcMap:b},d=a?.filter(v=>!m.includes(v)),p=s?.filter(v=>!u.includes(v));if(!e&&!l&&!n&&!(d!=null&&d.length)&&!(p!=null&&p.length))return{required:w};const M=d?.length&&p?.length||!e,P={chains:[...new Set(M?o.concat(e||[]):e)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(l||[]))],rpcMap:c};return{required:w,optional:P}}class g{constructor(){this.events=new A.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,e)=>(this.events.on(t,e),this),this.once=(t,e)=>(this.events.once(t,e),this),this.removeListener=(t,e)=>(this.events.removeListener(t,e),this),this.off=(t,e)=>(this.events.off(t,e),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const e=new g;return await e.initialize(t),e}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,e){this.signer.sendAsync(t,e,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:e,optional:s}=z(this.rpc);try{const n=await new Promise(async(l,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(y(I({namespaces:{[this.namespace]:e}},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic})).then(r=>{l(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;const chainId=this.signer.rpcProviders.eip155.chainId;this.setChainIds([this.formatChainId(chainId)]);const a=h.getAccountsFromNamespaces(n.namespaces,[this.namespace]);this.setAccounts(a),this.events.emit("connect",{chainId:E(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",E(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",y(I({},h.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var e,s;this.rpc.showQrModal&&((e=this.modal)==null||e.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",E(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.setHttpProvider(e)}}parseAccountId(t){const[e,s,n]=t.split(":");return{chainId:`${e}:${s}`,address:n}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;return{chains:((e=t.chains)==null?void 0:e.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||u,events:t?.events||m,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(s=t?.qrModalOptions)!=null?s:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(n=>{s[n]=this.getRpcUrl(n,e)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await T.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let e;try{const{WalletConnectModal:s}=await Promise.resolve().then(function(){return R(require("@walletconnect/modal"))});e=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(e)try{this.modal=new e(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:n}=t;e&&h.isValidArray(e)&&(this.rpc.chains=e.map(a=>this.formatChainId(a)),e.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)})),s&&h.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(a=>this.formatChainId(a)),s.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${q}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=this.signer.rpcProviders.eip155.chainId;this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const G=g;exports.EthereumProvider=G,exports.OPTIONAL_EVENTS=$,exports.OPTIONAL_METHODS=D,exports.REQUIRED_EVENTS=m,exports.REQUIRED_METHODS=u,exports.default=g; - //# sourceMappingURL=index.cjs.js.map -diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js -index db2e087..2ba50a0 100644 ---- a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js -+++ b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js -@@ -1,2 +1,2 @@ --import{EventEmitter as P}from"events";import{getAccountsFromNamespaces as R,getSdkError as T,isValidArray as v}from"@walletconnect/utils";import{UniversalProvider as S}from"@walletconnect/universal-provider";const j="wc",q="ethereum_provider",N=`${j}@2:${q}:`,$="https://rpc.walletconnect.com/v1/",p=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],u=["chainChanged","accountsChanged"],U=["message","disconnect","connect"];var Q=Object.defineProperty,L=Object.defineProperties,H=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,y=(a,t,s)=>t in a?Q(a,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[t]=s,I=(a,t)=>{for(var s in t||(t={}))G.call(t,s)&&y(a,s,t[s]);if(_)for(var s of _(t))K.call(t,s)&&y(a,s,t[s]);return a},M=(a,t)=>L(a,H(t));function C(a){return Number(a[0].split(":")[1])}function w(a){return`0x${a.toString(16)}`}function V(a){const{chains:t,optionalChains:s,methods:i,optionalMethods:n,events:e,optionalEvents:h,rpcMap:c}=a;if(!v(t))throw new Error("Invalid chains");const o=t,r=i||p,f=e||u,O={[C(o)]:c[C(o)]},E={chains:o,methods:r,events:f,rpcMap:O},l=e?.filter(g=>!u.includes(g)),d=i?.filter(g=>!p.includes(g));if(!s&&!h&&!n&&!(l!=null&&l.length)&&!(d!=null&&d.length))return{required:E};const b=l?.length&&d?.length||!s,A={chains:[...new Set(b?o.concat(s||[]):s)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(h||[]))],rpcMap:c};return{required:E,optional:A}}class m{constructor(){this.events=new P,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new m;return await s.initialize(t),s}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,s){this.signer.sendAsync(t,s,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=V(this.rpc);try{const n=await new Promise(async(h,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M(I({namespaces:{[this.namespace]:s}},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(r=>{h(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;this.setChainIds(this.rpc.chains);const e=R(n.namespaces,[this.namespace]);this.setAccounts(e),this.events.emit("connect",{chainId:w(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",w(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",M(I({},T("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",w(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.setHttpProvider(s)}}parseAccountId(t){const[s,i,n]=t.split(":");return{chainId:`${s}:${i}`,address:n}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;return{chains:((s=t.chains)==null?void 0:s.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||p,events:t?.events||u,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(i=t?.qrModalOptions)!=null?i:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(n=>{i[n]=this.getRpcUrl(n,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await import("@walletconnect/modal");s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:n}=t;s&&v(s)&&(this.rpc.chains=s.map(e=>this.formatChainId(e)),s.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)})),i&&v(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(e=>this.formatChainId(e)),i.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${$}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const W=m;export{W as EthereumProvider,U as OPTIONAL_EVENTS,D as OPTIONAL_METHODS,u as REQUIRED_EVENTS,p as REQUIRED_METHODS,m as default}; -+import{EventEmitter as P}from"events";import{getAccountsFromNamespaces as R,getSdkError as T,isValidArray as v}from"@walletconnect/utils";import{UniversalProvider as S}from"@walletconnect/universal-provider";const j="wc",q="ethereum_provider",N=`${j}@2:${q}:`,$="https://rpc.walletconnect.com/v1/",p=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],u=["chainChanged","accountsChanged"],U=["message","disconnect","connect"];var Q=Object.defineProperty,L=Object.defineProperties,H=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,y=(a,t,s)=>t in a?Q(a,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[t]=s,I=(a,t)=>{for(var s in t||(t={}))G.call(t,s)&&y(a,s,t[s]);if(_)for(var s of _(t))K.call(t,s)&&y(a,s,t[s]);return a},M=(a,t)=>L(a,H(t));function C(a){return Number(a[0].split(":")[1])}function w(a){return`0x${a.toString(16)}`}function V(a){const{chains:t,optionalChains:s,methods:i,optionalMethods:n,events:e,optionalEvents:h,rpcMap:c}=a;if(!v(t))throw new Error("Invalid chains");const o=t,r=i||p,f=e||u,O={[C(o)]:c[C(o)]},E={chains:o,methods:r,events:f,rpcMap:O},l=e?.filter(g=>!u.includes(g)),d=i?.filter(g=>!p.includes(g));if(!s&&!h&&!n&&!(l!=null&&l.length)&&!(d!=null&&d.length))return{required:E};const b=l?.length&&d?.length||!s,A={chains:[...new Set(b?o.concat(s||[]):s)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(h||[]))],rpcMap:c};return{required:E,optional:A}}class m{constructor(){this.events=new P,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new m;return await s.initialize(t),s}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,s){this.signer.sendAsync(t,s,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=V(this.rpc);try{const n=await new Promise(async(h,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M(I({namespaces:{[this.namespace]:s}},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(r=>{h(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;const chainId = this.signer.rpcProviders.eip155.chainId;this.setChainIds([this.formatChainId(chainId)]);const e=R(n.namespaces,[this.namespace]);this.setAccounts(e),this.events.emit("connect",{chainId:w(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",w(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",M(I({},T("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",w(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.setHttpProvider(s)}}parseAccountId(t){const[s,i,n]=t.split(":");return{chainId:`${s}:${i}`,address:n}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;return{chains:((s=t.chains)==null?void 0:s.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||p,events:t?.events||u,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(i=t?.qrModalOptions)!=null?i:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(n=>{i[n]=this.getRpcUrl(n,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await import("@walletconnect/modal");s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:n}=t;s&&v(s)&&(this.rpc.chains=s.map(e=>this.formatChainId(e)),s.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)})),i&&v(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(e=>this.formatChainId(e)),i.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${$}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=this.signer.rpcProviders.eip155.chainId;this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const W=m;export{W as EthereumProvider,U as OPTIONAL_EVENTS,D as OPTIONAL_METHODS,u as REQUIRED_EVENTS,p as REQUIRED_METHODS,m as default}; - //# sourceMappingURL=index.es.js.map -diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js -index 83e05d2..7df0974 100644 ---- a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js -+++ b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js -@@ -95,7 +95,7 @@ __p += '`),wt&&(pe+=`' + - function print() { __p += __j.call(arguments, '') } - `:`; - `)+pe+`return __p --}`;var ot=uw(function(){return vt(S,Pe+"return "+pe).apply(r,M)});if(ot.source=pe,X0(ot))throw ot;return ot}function qR(s){return yt(s).toLowerCase()}function VR(s){return yt(s).toUpperCase()}function KR(s,a,u){if(s=yt(s),s&&(u||a===r))return ym(s);if(!s||!(a=tn(a)))return s;var g=In(s),y=In(a),S=bm(g,y),M=_m(g,y)+1;return Ni(g,S,M).join("")}function GR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.slice(0,xm(s)+1);if(!s||!(a=tn(a)))return s;var g=In(s),y=_m(g,In(a))+1;return Ni(g,0,y).join("")}function ZR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.replace(Kt,"");if(!s||!(a=tn(a)))return s;var g=In(s),y=bm(g,In(a));return Ni(g,y).join("")}function YR(s,a){var u=z,g=ee;if(Bt(a)){var y="separator"in a?a.separator:y;u="length"in a?it(a.length):u,g="omission"in a?tn(a.omission):g}s=yt(s);var S=s.length;if(oo(s)){var M=In(s);S=M.length}if(u>=S)return s;var k=u-ao(g);if(k<1)return g;var Z=M?Ni(M,0,k).join(""):s.slice(0,k);if(y===r)return Z+g;if(M&&(k+=Z.length-k),Q0(y)){if(s.slice(k).search(y)){var ue,he=Z;for(y.global||(y=g0(y.source,yt(fn.exec(y))+"g")),y.lastIndex=0;ue=y.exec(he);)var pe=ue.index;Z=Z.slice(0,pe===r?k:pe)}}else if(s.indexOf(tn(y),k)!=k){var be=Z.lastIndexOf(y);be>-1&&(Z=Z.slice(0,be))}return Z+g}function JR(s){return s=yt(s),s&&zt.test(s)?s.replace(Ii,OS):s}var XR=go(function(s,a,u){return s+(u?" ":"")+a.toUpperCase()}),rd=h2("toUpperCase");function lw(s,a,u){return s=yt(s),a=u?r:a,a===r?_S(s)?DS(s):fS(s):s.match(a)||[]}var uw=ct(function(s,a){try{return vr(s,r,a)}catch(u){return X0(u)?u:new Ye(u)}}),QR=ii(function(s,a){return pn(a,function(u){u=Hn(u),ri(s,u,Y0(s[u],s))}),s});function eN(s){var a=s==null?0:s.length,u=ze();return s=a?Ut(s,function(g){if(typeof g[1]!="function")throw new gn(c);return[u(g[0]),g[1]]}):[],ct(function(g){for(var y=-1;++yre)return[];var u=ie,g=Ar(s,ie);a=ze(a),s-=ie;for(var y=f0(g,a);++u0||a<0)?new dt(u):(s<0?u=u.takeRight(-s):s&&(u=u.drop(s)),a!==r&&(a=it(a),u=a<0?u.dropRight(-a):u.take(a-s)),u)},dt.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},dt.prototype.toArray=function(){return this.take(ie)},Bn(dt.prototype,function(s,a){var u=/^(?:filter|find|map|reject)|While$/.test(a),g=/^(?:head|last)$/.test(a),y=C[g?"take"+(a=="last"?"Right":""):a],S=g||/^find/.test(a);y&&(C.prototype[a]=function(){var M=this.__wrapped__,k=g?[1]:arguments,Z=M instanceof dt,ue=k[0],he=Z||Qe(M),pe=function(ft){var wt=y.apply(C,Si([ft],k));return g&&be?wt[0]:wt};he&&u&&typeof ue=="function"&&ue.length!=1&&(Z=he=!1);var be=this.__chain__,Pe=!!this.__actions__.length,We=S&&!be,ot=Z&&!Pe;if(!S&&he){M=ot?M:new dt(this);var qe=s.apply(M,k);return qe.__actions__.push({func:Wl,args:[pe],thisArg:r}),new mn(qe,be)}return We&&ot?s.apply(this,k):(qe=this.thru(pe),We?g?qe.value()[0]:qe.value():qe)})}),pn(["pop","push","shift","sort","splice","unshift"],function(s){var a=ml[s],u=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",g=/^(?:pop|shift)$/.test(s);C.prototype[s]=function(){var y=arguments;if(g&&!this.__chain__){var S=this.value();return a.apply(Qe(S)?S:[],y)}return this[u](function(M){return a.apply(Qe(M)?M:[],y)})}}),Bn(dt.prototype,function(s,a){var u=C[a];if(u){var g=u.name+"";bt.call(ho,g)||(ho[g]=[]),ho[g].push({name:a,func:u})}}),ho[Ul(r,G).name]=[{name:"wrapper",func:r}],dt.prototype.clone=JS,dt.prototype.reverse=XS,dt.prototype.value=QS,C.prototype.at=SP,C.prototype.chain=DP,C.prototype.commit=$P,C.prototype.next=PP,C.prototype.plant=RP,C.prototype.reverse=NP,C.prototype.toJSON=C.prototype.valueOf=C.prototype.value=LP,C.prototype.first=C.prototype.head,_a&&(C.prototype[_a]=TP),C},co=$S();Qt?((Qt.exports=co)._=co,Ot._=co):mt._=co}).call(Wo)})(gh,gh.exports);var b7=Object.defineProperty,_7=Object.defineProperties,E7=Object.getOwnPropertyDescriptors,Eg=Object.getOwnPropertySymbols,x7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,xg=(t,e,r)=>e in t?b7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oc=(t,e)=>{for(var r in e||(e={}))x7.call(e,r)&&xg(t,r,e[r]);if(Eg)for(var r of Eg(e))C7.call(e,r)&&xg(t,r,e[r]);return t},I7=(t,e)=>_7(t,E7(e));function cn(t,e,r){let n;const i=mh(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${y7}?chainId=eip155:${i}&projectId=${r}`),n}function mh(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function O7(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function A7(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function S7(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const o=e.namespaces[i].accounts;n.push(...o)}),n}function D7(t,e={}){const r=Cg(t),n=Cg(e);return gh.exports.merge(r,n)}function Cg(t){var e,r,n,i;const o={};if(!Ds(t))return o;for(const[c,l]of Object.entries(t)){const h=M1(c)?[c]:l.chains,d=l.methods||[],v=l.events||[],x=l.rpcMap||{},_=Za(c);o[_]=I7(oc(oc({},o[_]),l),{chains:Su(h,(e=o[_])==null?void 0:e.chains),methods:Su(d,(r=o[_])==null?void 0:r.methods),events:Su(v,(n=o[_])==null?void 0:n.events),rpcMap:oc(oc({},x),(i=o[_])==null?void 0:i.rpcMap)})}return o}const Ig={},Jt=t=>Ig[t],wh=(t,e)=>{Ig[t]=e};class $7{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class P7{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}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,r){const n=mh(e);if(!this.httpProviders[n]){const i=r||cn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}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,r){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=mh(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;O7(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class T7{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class R7{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class N7{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class L7{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class M7{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}var U7=Object.defineProperty,j7=Object.defineProperties,F7=Object.getOwnPropertyDescriptors,Og=Object.getOwnPropertySymbols,B7=Object.prototype.hasOwnProperty,k7=Object.prototype.propertyIsEnumerable,Ag=(t,e,r)=>e in t?U7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ac=(t,e)=>{for(var r in e||(e={}))B7.call(e,r)&&Ag(t,r,e[r]);if(Og)for(var r of Og(e))k7.call(e,r)&&Ag(t,r,e[r]);return t},vh=(t,e)=>j7(t,F7(e));class yh{constructor(e){this.events=new br.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||bg})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new yh(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ac({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,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}),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:Yt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(o=>{this.session=o}).catch(o=>{if(o.message!==pg)throw o;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(zn(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await dh.init({logger:this.providerOpts.logger||bg,relayUrl:this.providerOpts.relayUrl||m7,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),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(r=>Za(r)))];wh("client",this.client),wh("events",this.events),wh("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=S7(r,this.session),i=A7(n),o=D7(this.namespaces,this.optionalNamespaces),c=vh(ac({},o[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new P7({namespace:c});break;case"solana":this.rpcProviders[r]=new T7({namespace:c});break;case"cosmos":this.rpcProviders[r]=new R7({namespace:c});break;case"polkadot":this.rpcProviders[r]=new $7({namespace:c});break;case"cip34":this.rpcProviders[r]=new N7({namespace:c});break;case"elrond":this.rpcProviders[r]=new L7({namespace:c});break;case"multiversx":this.rpcProviders[r]=new M7({namespace:c});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=vh(ac({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",vh(ac({},Yt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(di.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).map(c=>Za(c)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Za(Object.keys(this.namespaces)[0]),o=this.rpcProviders[i].getDefaultChain();return[i,o]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){var n;const[i,o]=this.validateChain(e);r||this.getProvider(i).setDefaultChain(o),((n=this.namespaces[i])!=null?n:this.namespaces[`${i}:${o}`]).defaultChain=o,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",o)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${_g}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${_g}/${e}`)}}const H7=yh,z7="wc",W7="ethereum_provider",q7=`${z7}@2:${W7}:`,V7="https://rpc.walletconnect.com/v1/",cc=["eth_sendTransaction","personal_sign"],K7=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],lc=["chainChanged","accountsChanged"],G7=["message","disconnect","connect"];var Z7=Object.defineProperty,Y7=Object.defineProperties,J7=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,X7=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,Dg=(t,e,r)=>e in t?Z7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bh=(t,e)=>{for(var r in e||(e={}))X7.call(e,r)&&Dg(t,r,e[r]);if(Sg)for(var r of Sg(e))Q7.call(e,r)&&Dg(t,r,e[r]);return t},$g=(t,e)=>Y7(t,J7(e));function _h(t){return Number(t[0].split(":")[1])}function Eh(t){return`0x${t.toString(16)}`}function ex(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:o,optionalEvents:c,rpcMap:l}=t;if(!zn(e))throw new Error("Invalid chains");const h=e,d=n||cc,v=o||lc,x={[_h(h)]:l[_h(h)]},_={chains:h,methods:d,events:v,rpcMap:x},O=o?.filter(G=>!lc.includes(G)),P=n?.filter(G=>!cc.includes(G));if(!r&&!c&&!i&&!(O!=null&&O.length)&&!(P!=null&&P.length))return{required:_};const U=O?.length&&P?.length||!r,H={chains:[...new Set(U?h.concat(r||[]):r)],methods:[...new Set(d.concat(i||[]))],events:[...new Set(v.concat(c||[]))],rpcMap:l};return{required:_,optional:H}}class uc{constructor(){this.events=new br.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=q7,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new uc;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=ex(this.rpc);try{const i=await new Promise(async(c,l)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),l(new Error("Connection request reset. Please try again.")))})),await this.signer.connect($g(bh({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(d=>{c(d)}).catch(d=>{l(new Error(d.message))})});if(!i)return;this.setChainIds(this.rpc.chains);const o=N5(i.namespaces,[this.namespace]);this.setAccounts(o),this.events.emit("connect",{chainId:Eh(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Eh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",$g(bh({},Yt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Eh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||cc,events:e?.events||lc,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:(n=e?.qrModalOptions)!=null?n:void 0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=_h(this.rpc.chains),this.signer=await H7.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:n}=await Promise.resolve().then(function(){return Px});r=n}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(bh({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&zn(r)&&(this.rpc.chains=r.map(o=>this.formatChainId(o)),r.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)})),n&&zn(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(o=>this.formatChainId(o)),n.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${V7}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const tx=uc,rx=Symbol(),Pg=Object.getPrototypeOf,xh=new WeakMap,nx=t=>t&&(xh.has(t)?xh.get(t):Pg(t)===Object.prototype||Pg(t)===Array.prototype),ix=t=>nx(t)&&t[rx]||null,Tg=(t,e=!0)=>{xh.set(t,e)},Ch=t=>typeof t=="object"&&t!==null,pi=new WeakMap,hc=new WeakSet,sx=(t=Object.is,e=(d,v)=>new Proxy(d,v),r=d=>Ch(d)&&!hc.has(d)&&(Array.isArray(d)||!(Symbol.iterator in d))&&!(d instanceof WeakMap)&&!(d instanceof WeakSet)&&!(d instanceof Error)&&!(d instanceof Number)&&!(d instanceof Date)&&!(d instanceof String)&&!(d instanceof RegExp)&&!(d instanceof ArrayBuffer),n=d=>{switch(d.status){case"fulfilled":return d.value;case"rejected":throw d.reason;default:throw d}},i=new WeakMap,o=(d,v,x=n)=>{const _=i.get(d);if(_?.[0]===v)return _[1];const O=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d));return Tg(O,!0),i.set(d,[v,O]),Reflect.ownKeys(d).forEach(P=>{if(Object.getOwnPropertyDescriptor(O,P))return;const U=Reflect.get(d,P),H={value:U,enumerable:!0,configurable:!0};if(hc.has(U))Tg(U,!1);else if(U instanceof Promise)delete H.value,H.get=()=>x(U);else if(pi.has(U)){const[G,N]=pi.get(U);H.value=o(G,N(),x)}Object.defineProperty(O,P,H)}),O},c=new WeakMap,l=[1,1],h=d=>{if(!Ch(d))throw new Error("object required");const v=c.get(d);if(v)return v;let x=l[0];const _=new Set,O=(J,z=++l[0])=>{x!==z&&(x=z,_.forEach(ee=>ee(J,z)))};let P=l[1];const U=(J=++l[1])=>(P!==J&&!_.size&&(P=J,G.forEach(([z])=>{const ee=z[1](J);ee>x&&(x=ee)})),x),H=J=>(z,ee)=>{const de=[...z];de[1]=[J,...de[1]],O(de,ee)},G=new Map,N=(J,z)=>{if(G.has(J))throw new Error("prop listener already exists");if(_.size){const ee=z[3](H(J));G.set(J,[z,ee])}else G.set(J,[z])},L=J=>{var z;const ee=G.get(J);ee&&(G.delete(J),(z=ee[1])==null||z.call(ee))},$=J=>(_.add(J),_.size===1&&G.forEach(([ee,de],me)=>{if(de)throw new Error("remove already exists");const A=ee[3](H(me));G.set(me,[ee,A])}),()=>{_.delete(J),_.size===0&&G.forEach(([ee,de],me)=>{de&&(de(),G.set(me,[ee]))})}),T=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d)),f=e(T,{deleteProperty(J,z){const ee=Reflect.get(J,z);L(z);const de=Reflect.deleteProperty(J,z);return de&&O(["delete",[z],ee]),de},set(J,z,ee,de){const me=Reflect.has(J,z),A=Reflect.get(J,z,de);if(me&&(t(A,ee)||c.has(ee)&&t(A,c.get(ee))))return!0;L(z),Ch(ee)&&(ee=ix(ee)||ee);let j=ee;if(ee instanceof Promise)ee.then(ce=>{ee.status="fulfilled",ee.value=ce,O(["resolve",[z],ce])}).catch(ce=>{ee.status="rejected",ee.reason=ce,O(["reject",[z],ce])});else{!pi.has(ee)&&r(ee)&&(j=h(ee));const ce=!hc.has(j)&&pi.get(j);ce&&N(z,ce)}return Reflect.set(J,z,j,de),O(["set",[z],ee,A]),!0}});c.set(d,f);const E=[T,U,o,$];return pi.set(f,E),Reflect.ownKeys(d).forEach(J=>{const z=Object.getOwnPropertyDescriptor(d,J);"value"in z&&(f[J]=d[J],delete z.value,delete z.writable),Object.defineProperty(T,J,z)}),f})=>[h,pi,hc,t,e,r,n,i,o,c,l],[ox]=sx();function Rn(t={}){return ox(t)}function Kn(t,e,r){const n=pi.get(t);n||console.warn("Please use proxy object");let i;const o=[],c=n[3];let l=!1;const d=c(v=>{if(o.push(v),r){e(o.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,l&&e(o.splice(0))}))});return l=!0,()=>{l=!1,d()}}function ax(t,e){const r=pi.get(t);r||console.warn("Please use proxy object");const[n,i,o]=r;return o(n,i(),e)}var Rg={},fc={};fc.byteLength=ux,fc.toByteArray=fx,fc.fromByteArray=gx;for(var Nn=[],ln=[],cx=typeof Uint8Array<"u"?Uint8Array:Array,Ih="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ps=0,lx=Ih.length;Ps0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function ux(t){var e=Ng(t),r=e[0],n=e[1];return(r+n)*3/4-n}function hx(t,e,r){return(e+r)*3/4-r}function fx(t){var e,r=Ng(t),n=r[0],i=r[1],o=new cx(hx(t,n,i)),c=0,l=i>0?n-4:n,h;for(h=0;h>16&255,o[c++]=e>>8&255,o[c++]=e&255;return i===2&&(e=ln[t.charCodeAt(h)]<<2|ln[t.charCodeAt(h+1)]>>4,o[c++]=e&255),i===1&&(e=ln[t.charCodeAt(h)]<<10|ln[t.charCodeAt(h+1)]<<4|ln[t.charCodeAt(h+2)]>>2,o[c++]=e>>8&255,o[c++]=e&255),o}function dx(t){return Nn[t>>18&63]+Nn[t>>12&63]+Nn[t>>6&63]+Nn[t&63]}function px(t,e,r){for(var n,i=[],o=e;ol?l:c+o));return n===1?(e=t[r-1],i.push(Nn[e>>2]+Nn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Nn[e>>10]+Nn[e>>4&63]+Nn[e<<2&63]+"=")),i.join("")}var Oh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */Oh.read=function(t,e,r,n,i){var o,c,l=i*8-n-1,h=(1<>1,v=-7,x=r?i-1:0,_=r?-1:1,O=t[e+x];for(x+=_,o=O&(1<<-v)-1,O>>=-v,v+=l;v>0;o=o*256+t[e+x],x+=_,v-=8);for(c=o&(1<<-v)-1,o>>=-v,v+=n;v>0;c=c*256+t[e+x],x+=_,v-=8);if(o===0)o=1-d;else{if(o===h)return c?NaN:(O?-1:1)*(1/0);c=c+Math.pow(2,n),o=o-d}return(O?-1:1)*c*Math.pow(2,o-n)},Oh.write=function(t,e,r,n,i,o){var c,l,h,d=o*8-i-1,v=(1<>1,_=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=n?0:o-1,P=n?1:-1,U=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=v):(c=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-c))<1&&(c--,h*=2),c+x>=1?e+=_/h:e+=_*Math.pow(2,1-x),e*h>=2&&(c++,h/=2),c+x>=v?(l=0,c=v):c+x>=1?(l=(e*h-1)*Math.pow(2,i),c=c+x):(l=e*Math.pow(2,x-1)*Math.pow(2,i),c=0));i>=8;t[r+O]=l&255,O+=P,l/=256,i-=8);for(c=c<0;t[r+O]=c&255,O+=P,c/=256,d-=8);t[r+O-P]|=U*128};/*! -+}`;var ot=uw(function(){return vt(S,Pe+"return "+pe).apply(r,M)});if(ot.source=pe,X0(ot))throw ot;return ot}function qR(s){return yt(s).toLowerCase()}function VR(s){return yt(s).toUpperCase()}function KR(s,a,u){if(s=yt(s),s&&(u||a===r))return ym(s);if(!s||!(a=tn(a)))return s;var g=In(s),y=In(a),S=bm(g,y),M=_m(g,y)+1;return Ni(g,S,M).join("")}function GR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.slice(0,xm(s)+1);if(!s||!(a=tn(a)))return s;var g=In(s),y=_m(g,In(a))+1;return Ni(g,0,y).join("")}function ZR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.replace(Kt,"");if(!s||!(a=tn(a)))return s;var g=In(s),y=bm(g,In(a));return Ni(g,y).join("")}function YR(s,a){var u=z,g=ee;if(Bt(a)){var y="separator"in a?a.separator:y;u="length"in a?it(a.length):u,g="omission"in a?tn(a.omission):g}s=yt(s);var S=s.length;if(oo(s)){var M=In(s);S=M.length}if(u>=S)return s;var k=u-ao(g);if(k<1)return g;var Z=M?Ni(M,0,k).join(""):s.slice(0,k);if(y===r)return Z+g;if(M&&(k+=Z.length-k),Q0(y)){if(s.slice(k).search(y)){var ue,he=Z;for(y.global||(y=g0(y.source,yt(fn.exec(y))+"g")),y.lastIndex=0;ue=y.exec(he);)var pe=ue.index;Z=Z.slice(0,pe===r?k:pe)}}else if(s.indexOf(tn(y),k)!=k){var be=Z.lastIndexOf(y);be>-1&&(Z=Z.slice(0,be))}return Z+g}function JR(s){return s=yt(s),s&&zt.test(s)?s.replace(Ii,OS):s}var XR=go(function(s,a,u){return s+(u?" ":"")+a.toUpperCase()}),rd=h2("toUpperCase");function lw(s,a,u){return s=yt(s),a=u?r:a,a===r?_S(s)?DS(s):fS(s):s.match(a)||[]}var uw=ct(function(s,a){try{return vr(s,r,a)}catch(u){return X0(u)?u:new Ye(u)}}),QR=ii(function(s,a){return pn(a,function(u){u=Hn(u),ri(s,u,Y0(s[u],s))}),s});function eN(s){var a=s==null?0:s.length,u=ze();return s=a?Ut(s,function(g){if(typeof g[1]!="function")throw new gn(c);return[u(g[0]),g[1]]}):[],ct(function(g){for(var y=-1;++yre)return[];var u=ie,g=Ar(s,ie);a=ze(a),s-=ie;for(var y=f0(g,a);++u0||a<0)?new dt(u):(s<0?u=u.takeRight(-s):s&&(u=u.drop(s)),a!==r&&(a=it(a),u=a<0?u.dropRight(-a):u.take(a-s)),u)},dt.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},dt.prototype.toArray=function(){return this.take(ie)},Bn(dt.prototype,function(s,a){var u=/^(?:filter|find|map|reject)|While$/.test(a),g=/^(?:head|last)$/.test(a),y=C[g?"take"+(a=="last"?"Right":""):a],S=g||/^find/.test(a);y&&(C.prototype[a]=function(){var M=this.__wrapped__,k=g?[1]:arguments,Z=M instanceof dt,ue=k[0],he=Z||Qe(M),pe=function(ft){var wt=y.apply(C,Si([ft],k));return g&&be?wt[0]:wt};he&&u&&typeof ue=="function"&&ue.length!=1&&(Z=he=!1);var be=this.__chain__,Pe=!!this.__actions__.length,We=S&&!be,ot=Z&&!Pe;if(!S&&he){M=ot?M:new dt(this);var qe=s.apply(M,k);return qe.__actions__.push({func:Wl,args:[pe],thisArg:r}),new mn(qe,be)}return We&&ot?s.apply(this,k):(qe=this.thru(pe),We?g?qe.value()[0]:qe.value():qe)})}),pn(["pop","push","shift","sort","splice","unshift"],function(s){var a=ml[s],u=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",g=/^(?:pop|shift)$/.test(s);C.prototype[s]=function(){var y=arguments;if(g&&!this.__chain__){var S=this.value();return a.apply(Qe(S)?S:[],y)}return this[u](function(M){return a.apply(Qe(M)?M:[],y)})}}),Bn(dt.prototype,function(s,a){var u=C[a];if(u){var g=u.name+"";bt.call(ho,g)||(ho[g]=[]),ho[g].push({name:a,func:u})}}),ho[Ul(r,G).name]=[{name:"wrapper",func:r}],dt.prototype.clone=JS,dt.prototype.reverse=XS,dt.prototype.value=QS,C.prototype.at=SP,C.prototype.chain=DP,C.prototype.commit=$P,C.prototype.next=PP,C.prototype.plant=RP,C.prototype.reverse=NP,C.prototype.toJSON=C.prototype.valueOf=C.prototype.value=LP,C.prototype.first=C.prototype.head,_a&&(C.prototype[_a]=TP),C},co=$S();Qt?((Qt.exports=co)._=co,Ot._=co):mt._=co}).call(Wo)})(gh,gh.exports);var b7=Object.defineProperty,_7=Object.defineProperties,E7=Object.getOwnPropertyDescriptors,Eg=Object.getOwnPropertySymbols,x7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,xg=(t,e,r)=>e in t?b7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oc=(t,e)=>{for(var r in e||(e={}))x7.call(e,r)&&xg(t,r,e[r]);if(Eg)for(var r of Eg(e))C7.call(e,r)&&xg(t,r,e[r]);return t},I7=(t,e)=>_7(t,E7(e));function cn(t,e,r){let n;const i=mh(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${y7}?chainId=eip155:${i}&projectId=${r}`),n}function mh(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function O7(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function A7(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function S7(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const o=e.namespaces[i].accounts;n.push(...o)}),n}function D7(t,e={}){const r=Cg(t),n=Cg(e);return gh.exports.merge(r,n)}function Cg(t){var e,r,n,i;const o={};if(!Ds(t))return o;for(const[c,l]of Object.entries(t)){const h=M1(c)?[c]:l.chains,d=l.methods||[],v=l.events||[],x=l.rpcMap||{},_=Za(c);o[_]=I7(oc(oc({},o[_]),l),{chains:Su(h,(e=o[_])==null?void 0:e.chains),methods:Su(d,(r=o[_])==null?void 0:r.methods),events:Su(v,(n=o[_])==null?void 0:n.events),rpcMap:oc(oc({},x),(i=o[_])==null?void 0:i.rpcMap)})}return o}const Ig={},Jt=t=>Ig[t],wh=(t,e)=>{Ig[t]=e};class $7{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class P7{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}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,r){const n=mh(e);if(!this.httpProviders[n]){const i=r||cn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}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,r){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=mh(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;O7(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class T7{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class R7{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class N7{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class L7{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class M7{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("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,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}var U7=Object.defineProperty,j7=Object.defineProperties,F7=Object.getOwnPropertyDescriptors,Og=Object.getOwnPropertySymbols,B7=Object.prototype.hasOwnProperty,k7=Object.prototype.propertyIsEnumerable,Ag=(t,e,r)=>e in t?U7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ac=(t,e)=>{for(var r in e||(e={}))B7.call(e,r)&&Ag(t,r,e[r]);if(Og)for(var r of Og(e))k7.call(e,r)&&Ag(t,r,e[r]);return t},vh=(t,e)=>j7(t,F7(e));class yh{constructor(e){this.events=new br.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||bg})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new yh(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ac({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,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}),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:Yt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(o=>{this.session=o}).catch(o=>{if(o.message!==pg)throw o;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(zn(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await dh.init({logger:this.providerOpts.logger||bg,relayUrl:this.providerOpts.relayUrl||m7,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),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(r=>Za(r)))];wh("client",this.client),wh("events",this.events),wh("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=S7(r,this.session),i=A7(n),o=D7(this.namespaces,this.optionalNamespaces),c=vh(ac({},o[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new P7({namespace:c});break;case"solana":this.rpcProviders[r]=new T7({namespace:c});break;case"cosmos":this.rpcProviders[r]=new R7({namespace:c});break;case"polkadot":this.rpcProviders[r]=new $7({namespace:c});break;case"cip34":this.rpcProviders[r]=new N7({namespace:c});break;case"elrond":this.rpcProviders[r]=new L7({namespace:c});break;case"multiversx":this.rpcProviders[r]=new M7({namespace:c});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=vh(ac({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",vh(ac({},Yt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(di.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).map(c=>Za(c)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Za(Object.keys(this.namespaces)[0]),o=this.rpcProviders[i].getDefaultChain();return[i,o]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){var n;const[i,o]=this.validateChain(e);r||this.getProvider(i).setDefaultChain(o),((n=this.namespaces[i])!=null?n:this.namespaces[`${i}:${o}`]).defaultChain=o,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",o)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${_g}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${_g}/${e}`)}}const H7=yh,z7="wc",W7="ethereum_provider",q7=`${z7}@2:${W7}:`,V7="https://rpc.walletconnect.com/v1/",cc=["eth_sendTransaction","personal_sign"],K7=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],lc=["chainChanged","accountsChanged"],G7=["message","disconnect","connect"];var Z7=Object.defineProperty,Y7=Object.defineProperties,J7=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,X7=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,Dg=(t,e,r)=>e in t?Z7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bh=(t,e)=>{for(var r in e||(e={}))X7.call(e,r)&&Dg(t,r,e[r]);if(Sg)for(var r of Sg(e))Q7.call(e,r)&&Dg(t,r,e[r]);return t},$g=(t,e)=>Y7(t,J7(e));function _h(t){return Number(t[0].split(":")[1])}function Eh(t){return`0x${t.toString(16)}`}function ex(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:o,optionalEvents:c,rpcMap:l}=t;if(!zn(e))throw new Error("Invalid chains");const h=e,d=n||cc,v=o||lc,x={[_h(h)]:l[_h(h)]},_={chains:h,methods:d,events:v,rpcMap:x},O=o?.filter(G=>!lc.includes(G)),P=n?.filter(G=>!cc.includes(G));if(!r&&!c&&!i&&!(O!=null&&O.length)&&!(P!=null&&P.length))return{required:_};const U=O?.length&&P?.length||!r,H={chains:[...new Set(U?h.concat(r||[]):r)],methods:[...new Set(d.concat(i||[]))],events:[...new Set(v.concat(c||[]))],rpcMap:l};return{required:_,optional:H}}class uc{constructor(){this.events=new br.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=q7,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new uc;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=ex(this.rpc);try{const i=await new Promise(async(c,l)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),l(new Error("Connection request reset. Please try again.")))})),await this.signer.connect($g(bh({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(d=>{c(d)}).catch(d=>{l(new Error(d.message))})});if(!i)return;const chainId = this.signer.rpcProviders.eip155.chainId;this.setChainIds([this.formatChainId(chainId)]);const o=N5(i.namespaces,[this.namespace]);this.setAccounts(o),this.events.emit("connect",{chainId:Eh(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Eh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",$g(bh({},Yt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Eh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||cc,events:e?.events||lc,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:(n=e?.qrModalOptions)!=null?n:void 0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=_h(this.rpc.chains),this.signer=await H7.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:n}=await Promise.resolve().then(function(){return Px});r=n}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(bh({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&zn(r)&&(this.rpc.chains=r.map(o=>this.formatChainId(o)),r.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)})),n&&zn(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(o=>this.formatChainId(o)),n.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${V7}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=this.signer.rpcProviders.eip155.chainId;this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const tx=uc,rx=Symbol(),Pg=Object.getPrototypeOf,xh=new WeakMap,nx=t=>t&&(xh.has(t)?xh.get(t):Pg(t)===Object.prototype||Pg(t)===Array.prototype),ix=t=>nx(t)&&t[rx]||null,Tg=(t,e=!0)=>{xh.set(t,e)},Ch=t=>typeof t=="object"&&t!==null,pi=new WeakMap,hc=new WeakSet,sx=(t=Object.is,e=(d,v)=>new Proxy(d,v),r=d=>Ch(d)&&!hc.has(d)&&(Array.isArray(d)||!(Symbol.iterator in d))&&!(d instanceof WeakMap)&&!(d instanceof WeakSet)&&!(d instanceof Error)&&!(d instanceof Number)&&!(d instanceof Date)&&!(d instanceof String)&&!(d instanceof RegExp)&&!(d instanceof ArrayBuffer),n=d=>{switch(d.status){case"fulfilled":return d.value;case"rejected":throw d.reason;default:throw d}},i=new WeakMap,o=(d,v,x=n)=>{const _=i.get(d);if(_?.[0]===v)return _[1];const O=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d));return Tg(O,!0),i.set(d,[v,O]),Reflect.ownKeys(d).forEach(P=>{if(Object.getOwnPropertyDescriptor(O,P))return;const U=Reflect.get(d,P),H={value:U,enumerable:!0,configurable:!0};if(hc.has(U))Tg(U,!1);else if(U instanceof Promise)delete H.value,H.get=()=>x(U);else if(pi.has(U)){const[G,N]=pi.get(U);H.value=o(G,N(),x)}Object.defineProperty(O,P,H)}),O},c=new WeakMap,l=[1,1],h=d=>{if(!Ch(d))throw new Error("object required");const v=c.get(d);if(v)return v;let x=l[0];const _=new Set,O=(J,z=++l[0])=>{x!==z&&(x=z,_.forEach(ee=>ee(J,z)))};let P=l[1];const U=(J=++l[1])=>(P!==J&&!_.size&&(P=J,G.forEach(([z])=>{const ee=z[1](J);ee>x&&(x=ee)})),x),H=J=>(z,ee)=>{const de=[...z];de[1]=[J,...de[1]],O(de,ee)},G=new Map,N=(J,z)=>{if(G.has(J))throw new Error("prop listener already exists");if(_.size){const ee=z[3](H(J));G.set(J,[z,ee])}else G.set(J,[z])},L=J=>{var z;const ee=G.get(J);ee&&(G.delete(J),(z=ee[1])==null||z.call(ee))},$=J=>(_.add(J),_.size===1&&G.forEach(([ee,de],me)=>{if(de)throw new Error("remove already exists");const A=ee[3](H(me));G.set(me,[ee,A])}),()=>{_.delete(J),_.size===0&&G.forEach(([ee,de],me)=>{de&&(de(),G.set(me,[ee]))})}),T=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d)),f=e(T,{deleteProperty(J,z){const ee=Reflect.get(J,z);L(z);const de=Reflect.deleteProperty(J,z);return de&&O(["delete",[z],ee]),de},set(J,z,ee,de){const me=Reflect.has(J,z),A=Reflect.get(J,z,de);if(me&&(t(A,ee)||c.has(ee)&&t(A,c.get(ee))))return!0;L(z),Ch(ee)&&(ee=ix(ee)||ee);let j=ee;if(ee instanceof Promise)ee.then(ce=>{ee.status="fulfilled",ee.value=ce,O(["resolve",[z],ce])}).catch(ce=>{ee.status="rejected",ee.reason=ce,O(["reject",[z],ce])});else{!pi.has(ee)&&r(ee)&&(j=h(ee));const ce=!hc.has(j)&&pi.get(j);ce&&N(z,ce)}return Reflect.set(J,z,j,de),O(["set",[z],ee,A]),!0}});c.set(d,f);const E=[T,U,o,$];return pi.set(f,E),Reflect.ownKeys(d).forEach(J=>{const z=Object.getOwnPropertyDescriptor(d,J);"value"in z&&(f[J]=d[J],delete z.value,delete z.writable),Object.defineProperty(T,J,z)}),f})=>[h,pi,hc,t,e,r,n,i,o,c,l],[ox]=sx();function Rn(t={}){return ox(t)}function Kn(t,e,r){const n=pi.get(t);n||console.warn("Please use proxy object");let i;const o=[],c=n[3];let l=!1;const d=c(v=>{if(o.push(v),r){e(o.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,l&&e(o.splice(0))}))});return l=!0,()=>{l=!1,d()}}function ax(t,e){const r=pi.get(t);r||console.warn("Please use proxy object");const[n,i,o]=r;return o(n,i(),e)}var Rg={},fc={};fc.byteLength=ux,fc.toByteArray=fx,fc.fromByteArray=gx;for(var Nn=[],ln=[],cx=typeof Uint8Array<"u"?Uint8Array:Array,Ih="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ps=0,lx=Ih.length;Ps0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function ux(t){var e=Ng(t),r=e[0],n=e[1];return(r+n)*3/4-n}function hx(t,e,r){return(e+r)*3/4-r}function fx(t){var e,r=Ng(t),n=r[0],i=r[1],o=new cx(hx(t,n,i)),c=0,l=i>0?n-4:n,h;for(h=0;h>16&255,o[c++]=e>>8&255,o[c++]=e&255;return i===2&&(e=ln[t.charCodeAt(h)]<<2|ln[t.charCodeAt(h+1)]>>4,o[c++]=e&255),i===1&&(e=ln[t.charCodeAt(h)]<<10|ln[t.charCodeAt(h+1)]<<4|ln[t.charCodeAt(h+2)]>>2,o[c++]=e>>8&255,o[c++]=e&255),o}function dx(t){return Nn[t>>18&63]+Nn[t>>12&63]+Nn[t>>6&63]+Nn[t&63]}function px(t,e,r){for(var n,i=[],o=e;ol?l:c+o));return n===1?(e=t[r-1],i.push(Nn[e>>2]+Nn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Nn[e>>10]+Nn[e>>4&63]+Nn[e<<2&63]+"=")),i.join("")}var Oh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */Oh.read=function(t,e,r,n,i){var o,c,l=i*8-n-1,h=(1<>1,v=-7,x=r?i-1:0,_=r?-1:1,O=t[e+x];for(x+=_,o=O&(1<<-v)-1,O>>=-v,v+=l;v>0;o=o*256+t[e+x],x+=_,v-=8);for(c=o&(1<<-v)-1,o>>=-v,v+=n;v>0;c=c*256+t[e+x],x+=_,v-=8);if(o===0)o=1-d;else{if(o===h)return c?NaN:(O?-1:1)*(1/0);c=c+Math.pow(2,n),o=o-d}return(O?-1:1)*c*Math.pow(2,o-n)},Oh.write=function(t,e,r,n,i,o){var c,l,h,d=o*8-i-1,v=(1<>1,_=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=n?0:o-1,P=n?1:-1,U=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=v):(c=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-c))<1&&(c--,h*=2),c+x>=1?e+=_/h:e+=_*Math.pow(2,1-x),e*h>=2&&(c++,h/=2),c+x>=v?(l=0,c=v):c+x>=1?(l=(e*h-1)*Math.pow(2,i),c=c+x):(l=e*Math.pow(2,x-1)*Math.pow(2,i),c=0));i>=8;t[r+O]=l&255,O+=P,l/=256,i-=8);for(c=c<0;t[r+O]=c&255,O+=P,c/=256,d-=8);t[r+O-P]|=U*128};/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh diff --git a/patches/@web3-react+metamask+8.2.1.patch b/patches/@web3-react+metamask+8.2.1.patch deleted file mode 100644 index 8b23dd9630..0000000000 --- a/patches/@web3-react+metamask+8.2.1.patch +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/node_modules/@web3-react/metamask/dist/index.js b/node_modules/@web3-react/metamask/dist/index.js -index c8476dd..a613ed1 100644 ---- a/node_modules/@web3-react/metamask/dist/index.js -+++ b/node_modules/@web3-react/metamask/dist/index.js -@@ -64,7 +64,14 @@ class MetaMask extends types_1.Connector { - this.provider = (_b = this.provider.providers.find((p) => p.isMetaMask)) !== null && _b !== void 0 ? _b : this.provider.providers[0]; - } - this.provider.on('connect', ({ chainId }) => { -- this.actions.update({ chainId: parseChainId(chainId) }); -+ this.provider -+ .request({ method: 'eth_chainId' }) -+ .then(chainId => { -+ this.actions.update({ chainId: parseChainId(chainId) }) -+ }) -+ .catch(() => { -+ this.actions.update({ chainId: parseChainId(chainId) }) -+ }) - }); - this.provider.on('disconnect', (error) => { - var _a; diff --git a/src/components/AddToMetamask/index.tsx b/src/components/AddToMetamask/index.tsx index 9dc039d60a..e3c9462afe 100644 --- a/src/components/AddToMetamask/index.tsx +++ b/src/components/AddToMetamask/index.tsx @@ -1,10 +1,10 @@ import { Token } from '@kyberswap/ks-sdk-core' +import { getConnection } from 'connection' import styled from 'styled-components' import { ButtonEmpty } from 'components/Button' import { RowFixed } from 'components/Row' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import { getTokenLogoURL } from 'utils' const StyledLogo = styled.img` @@ -14,6 +14,8 @@ const StyledLogo = styled.img` export default function AddTokenToMetaMask({ token }: { token: Token }) { const { chainId, walletKey } = useActiveWeb3React() + const { connector } = useWeb3React() + const connection = getConnection(connector) async function addToMetaMask() { const tokenAddress = token.address @@ -44,7 +46,7 @@ export default function AddTokenToMetaMask({ token }: { token: Token }) { return ( - + ) diff --git a/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx b/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx index c0843dd2ba..3d4ea2a7ff 100644 --- a/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx +++ b/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx @@ -1,5 +1,6 @@ import { ChainId } from '@kyberswap/ks-sdk-core' import { Trans, t } from '@lingui/macro' +import { getConnection } from 'connection' import { motion, useAnimationControls, useDragControls } from 'framer-motion' import { rgba } from 'polished' import { stringify } from 'querystring' @@ -14,8 +15,7 @@ import Row from 'components/Row' import { MouseoverTooltip } from 'components/Tooltip' import { NetworkInfo } from 'constants/networks/type' import { Z_INDEXS } from 'constants/styles' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import { ChainState } from 'hooks/useChainsConfig' import useParsedQueryString from 'hooks/useParsedQueryString' import useTheme from 'hooks/useTheme' @@ -133,8 +133,10 @@ const DraggableNetworkButton = ({ isComingSoon?: boolean }) => { const theme = useTheme() - const { isWrongNetwork, wallet } = useActiveWeb3React() + const { isWrongNetwork, walletKey: walletName, chainId: walletChainId } = useActiveWeb3React() const { changeNetwork } = useChangeNetwork() + const { connector } = useWeb3React() + const connection = getConnection(connector) const [dragging, setDragging] = useState(false) const ref = useRef(null) const dragControls = useDragControls() @@ -145,7 +147,7 @@ const DraggableNetworkButton = ({ const isMaintenance = state === ChainState.MAINTENANCE const disabled = isComingSoon || (activeChainIds ? !activeChainIds?.includes(chainId) : false) || isMaintenance const selected = isSelected && !isWrongNetwork - const walletKey = wallet.chainId === chainId ? wallet.walletKey : null + const walletKey = walletChainId === chainId ? walletName : null const handleChainSelect = () => { if (disabled) return @@ -288,9 +290,9 @@ const DraggableNetworkButton = ({ )} {selected && !walletKey && } - {walletKey && ( + {walletKey && connection.getProviderInfo().icon && ( - {SUPPORTED_WALLETS[walletKey].name + )} diff --git a/src/components/Header/web3/SelectWallet.tsx b/src/components/Header/web3/SelectWallet.tsx index 594edc006b..1cbd84e0e4 100644 --- a/src/components/Header/web3/SelectWallet.tsx +++ b/src/components/Header/web3/SelectWallet.tsx @@ -1,6 +1,7 @@ import { Trans } from '@lingui/macro' +import { getConnection } from 'connection' import { darken, lighten } from 'polished' -import { useMemo } from 'react' +import { useEffect, useMemo } from 'react' import { Activity } from 'react-feather' import { useMedia } from 'react-use' import styled from 'styled-components' @@ -13,16 +14,17 @@ import Loader from 'components/Loader' import { RowBetween } from 'components/Row' import { MouseoverTooltip } from 'components/Tooltip' import { TutorialIds } from 'components/Tutorial/TutorialSwap/constant' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import useENSName from 'hooks/useENSName' import useLogin from 'hooks/useLogin' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useTheme from 'hooks/useTheme' import { useNetworkModalToggle, useWalletModalToggle } from 'state/application/hooks' +import { useAppDispatch } from 'state/hooks' import { useSignedAccountInfo } from 'state/profile/hooks' import { isTransactionRecent, newTransactionsFirst, useAllTransactions } from 'state/transactions/hooks' import { TransactionDetails } from 'state/transactions/type' +import { updateRecentConnectionMeta } from 'state/user/actions' import { MEDIA_WIDTHS } from 'theme' import { shortenAddress } from 'utils' @@ -109,6 +111,9 @@ function Web3StatusInner() { const { signIn } = useLogin() const { ENSName } = useENSName(account ?? undefined) const theme = useTheme() + const { connector } = useWeb3React() + const connection = getConnection(connector) + const dispatch = useAppDispatch() const allTransactions = useAllTransactions() @@ -121,6 +126,15 @@ function Web3StatusInner() { const pendingLength = sortedRecentTransactions.filter(tx => !tx.receipt).length + useEffect(() => { + if (account || ENSName) { + const { rdns } = connection.getProviderInfo() + dispatch( + updateRecentConnectionMeta({ type: connection.type, address: account, ENSName: ENSName ?? undefined, rdns }), + ) + } + }, [ENSName, account, connection, dispatch]) + const hasPendingTransactions = !!pendingLength const toggleWalletModal = useWalletModalToggle() const toggleNetworkModal = useNetworkModalToggle() @@ -182,7 +196,7 @@ function Web3StatusInner() { ) : ( walletKey && ( - {SUPPORTED_WALLETS[walletKey].name + ) )} diff --git a/src/components/Header/web3/WalletModal/Option.tsx b/src/components/Header/web3/WalletModal/Option.tsx index a01edf5d1e..6874d51113 100644 --- a/src/components/Header/web3/WalletModal/Option.tsx +++ b/src/components/Header/web3/WalletModal/Option.tsx @@ -1,16 +1,13 @@ -import { Trans } from '@lingui/macro' +import { ActivationStatus, useActivationState } from 'connection/activate' +import { Connection } from 'connection/types' import { darken } from 'polished' import React from 'react' import styled, { css } from 'styled-components' -import { MouseoverTooltip } from 'components/Tooltip' -import { SUPPORTED_WALLET, SUPPORTED_WALLETS, WalletReadyState } from 'constants/wallets' import { useActiveWeb3React } from 'hooks' +import { useCloseModal } from 'state/application/hooks' +import { ApplicationModal } from 'state/application/types' import { useIsAcceptedTerm } from 'state/user/hooks' -import { ExternalLink } from 'theme' -import checkForBraveBrowser from 'utils/checkForBraveBrowser' - -import { C98OverrideGuide } from './WarningBox' const IconWrapper = styled.div` display: flex; @@ -94,163 +91,90 @@ const OptionCardLeft = styled.div` height: 100%; ` -const StyledLink = styled(ExternalLink)` - width: 100%; - &:hover { - text-decoration: none; - } -` +// const StyledLink = styled(ExternalLink)` +// width: 100%; +// &:hover { +// text-decoration: none; +// } +// ` -const Option = ({ - walletKey, - readyState, - installLink, - isOverridden, - onSelected, -}: { - walletKey: SUPPORTED_WALLET - readyState?: WalletReadyState - installLink?: string - isOverridden?: boolean - onSelected?: (walletKey: SUPPORTED_WALLET) => any -}) => { - const { walletKey: walletKeyConnected } = useActiveWeb3React() - const isBraveBrowser = checkForBraveBrowser() +const Option = ({ connection }: { connection: Connection }) => { + const { activationState, tryActivation } = useActivationState() const [isAcceptedTerm] = useIsAcceptedTerm() - const wallet = SUPPORTED_WALLETS[walletKey] - const isConnected = !!walletKeyConnected && walletKey === walletKeyConnected + const { chainId } = useActiveWeb3React() + + const { name, icon } = connection.getProviderInfo() + + const isSomeOptionPending = activationState.status === ActivationStatus.PENDING + const isCurrentOptionPending = isSomeOptionPending && activationState.connection === connection - const icon = wallet.icon + const closeWalletModal = useCloseModal(ApplicationModal.WALLET) const content = ( isAcceptedTerm && - !isOverridden && - !(walletKey === 'BRAVE' && !isBraveBrowser) - ? () => onSelected(walletKey) - : undefined + tryActivation( + connection, + () => { + closeWalletModal() + }, + chainId, + ) } - connected={isConnected} + connected={isCurrentOptionPending} isDisabled={!isAcceptedTerm} - installLink={installLink} - overridden={isOverridden} > {'Icon'} - {wallet.name} + {name} ) if (!isAcceptedTerm) return content - if (readyState === WalletReadyState.Loadable && wallet.href) { - return {content} - } - - if (walletKey === 'WALLET_CONNECT') { - return ( - Under development and unsupported by most wallets.}> - {content} - - ) - } - - if (walletKey === 'BRAVE') { - // Brave wallet only can use in Brave browser - if (!isBraveBrowser) { - return ( - - Brave wallet can only be used in Brave Browser. Download it{' '} - here↗ - - } - > - {content} - - ) - } - // Brave wallet overrided by Metamask extension - if (isBraveBrowser && !window.ethereum?.isBraveWallet) { - return ( - - Brave Wallet overridden by MetaMask Wallet. Disable MetaMask extension in order to use Brave Wallet. - - } - > - {content} - - ) - } - // Brave wallet overrided by Metamask extension - if (isBraveBrowser) { - return ( - - Brave Wallet overridden by Phantom Wallet. Disable Phantom extension in order to use Brave Wallet. - - } - > - {content} - - ) - } - } - - if (readyState === WalletReadyState.NotDetected) { - return ( - - You will need to install {wallet.name} extension/dapp before you can connect with it on KyberSwap. Get it{' '} - here↗ - - } - > - {content} - - ) - } - - if (isOverridden) { - return ( - - You need to enable "Override Wallet" in Coin98 settings. - - ) : ( - - ) - } - placement="bottom" - > - {content} - - ) - } + // if (readyState === WalletReadyState.NotDetected) { + // return ( + // + // You will need to install {wallet.name} extension/dapp before you can connect with it on KyberSwap. Get it{' '} + // here↗ + // + // } + // > + // {content} + // + // ) + // } + // + // if (isOverridden) { + // return ( + // + // You need to enable "Override Wallet" in Coin98 settings. + // + // ) : ( + // + // ) + // } + // placement="bottom" + // > + // {content} + // + // ) + // } return content } diff --git a/src/components/Header/web3/WalletModal/PendingView.tsx b/src/components/Header/web3/WalletModal/PendingView.tsx index 68da17155a..b9b73f7d80 100644 --- a/src/components/Header/web3/WalletModal/PendingView.tsx +++ b/src/components/Header/web3/WalletModal/PendingView.tsx @@ -1,12 +1,12 @@ import { Trans } from '@lingui/macro' +import { ActivationStatus, useActivationState } from 'connection/activate' import { darken } from 'polished' -import { ReactNode } from 'react' import styled from 'styled-components' import Loader from 'components/Loader' -import { SUPPORTED_WALLET, SUPPORTED_WALLETS } from 'constants/wallets' - -import { WarningBox } from './WarningBox' +import { useActiveWeb3React } from 'hooks' +import { useCloseModal } from 'state/application/hooks' +import { ApplicationModal } from 'state/application/types' const PendingSection = styled.div` ${({ theme }) => theme.flexColumnNoWrap}; @@ -67,42 +67,46 @@ const LoadingWrapper = styled.div` width: 100%; ` -export default function PendingView({ - walletKey, - hasError = false, - onClickTryAgain, - context, -}: { - walletKey?: SUPPORTED_WALLET - hasError?: boolean - onClickTryAgain: () => void - context?: ReactNode -}) { - const walletName = walletKey ? SUPPORTED_WALLETS[walletKey].name : '' +export default function PendingView() { + const { activationState, tryActivation } = useActivationState() + + const { chainId } = useActiveWeb3React() + const closeWalletModal = useCloseModal(ApplicationModal.WALLET) + if (activationState.status === ActivationStatus.IDLE) return null + + const { name } = activationState.connection.getProviderInfo() return ( - + - {hasError ? ( + {activationState.status === ActivationStatus.ERROR ? (
- Error connecting to {walletName}. + Error connecting to {name}.
- + + tryActivation( + activationState.connection, + () => { + closeWalletModal() + }, + chainId, + ) + } + > Try Again
) : ( <> - Initializing with {walletName}... + Initializing with {name}... )}
- - {context}
) } diff --git a/src/components/Header/web3/WalletModal/WarningBox.tsx b/src/components/Header/web3/WalletModal/WarningBox.tsx index 30bbf53de6..2c17974f9d 100644 --- a/src/components/Header/web3/WalletModal/WarningBox.tsx +++ b/src/components/Header/web3/WalletModal/WarningBox.tsx @@ -8,9 +8,7 @@ import { ReactComponent as WarningIcon } from 'assets/images/warning.svg' import { SUPPORTED_WALLET, SUPPORTED_WALLETS } from 'constants/wallets' import useTheme from 'hooks/useTheme' import { ExternalLink } from 'theme' -import { detectInjectedType } from 'utils' import checkForBraveBrowser from 'utils/checkForBraveBrowser' -import { isOverriddenWallet } from 'utils/index' const WarningBoxWrapper = styled.div` width: 100%; @@ -73,13 +71,12 @@ export const C98OverrideGuide = ({ }) => { const theme = useTheme() const [show, setShow] = useState(false) - const injectedType = detectInjectedType() if (!walletKey) return null - if (!injectedType) return null const walletName = SUPPORTED_WALLETS[walletKey].name - const injectedName = SUPPORTED_WALLETS[injectedType].name + // TODO: remove + const injectedName = 'BRAVE' const isSelectCoin98 = walletKey === 'COIN98' return ( @@ -133,12 +130,8 @@ export const WarningBox = ({ walletKey }: { walletKey?: SUPPORTED_WALLET }) => { const theme = useTheme() const isBraveBrowser = checkForBraveBrowser() - const injectedType = detectInjectedType() if (!walletKey) return null - if (!injectedType) return null - - if (walletKey === injectedType) return null if (!isBraveBrowser && walletKey === 'BRAVE') { return ( @@ -181,9 +174,5 @@ export const WarningBox = ({ walletKey }: { walletKey?: SUPPORTED_WALLET }) => { ) } - if (isOverriddenWallet(walletKey)) { - return - } - return null } diff --git a/src/components/Header/web3/WalletModal/index.tsx b/src/components/Header/web3/WalletModal/index.tsx index 4abb06191e..cdedbccaf0 100644 --- a/src/components/Header/web3/WalletModal/index.tsx +++ b/src/components/Header/web3/WalletModal/index.tsx @@ -1,10 +1,10 @@ import { Trans } from '@lingui/macro' +import { ActivationStatus, useActivationState } from 'connection/activate' +import { ConnectionType } from 'connection/types' import dayjs from 'dayjs' import { rgba } from 'polished' -import { useCallback, useEffect, useState } from 'react' +import { useEffect, useState } from 'react' import { ChevronLeft } from 'react-feather' -import { useLocation } from 'react-router-dom' -import { usePrevious } from 'react-use' import { Text } from 'rebass' import styled from 'styled-components' @@ -13,11 +13,9 @@ import Modal from 'components/Modal' import { RowBetween } from 'components/Row' import WalletPopup from 'components/WalletPopup' import { TERM_FILES_PATH } from 'constants/index' -import { SUPPORTED_WALLET, SUPPORTED_WALLETS, WalletInfo, WalletReadyState } from 'constants/wallets' -import { useActiveWeb3React, useWeb3React } from 'hooks' +import { useActiveWeb3React } from 'hooks' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useTheme from 'hooks/useTheme' -import { useActivationWallet } from 'hooks/web3/useActivationWallet' import { ApplicationModal } from 'state/application/actions' import { useCloseModal, @@ -26,13 +24,11 @@ import { useOpenNetworkModal, useWalletModalToggle, } from 'state/application/hooks' -import { useIsConnectingWallet } from 'state/authen/hooks' import { useIsAcceptedTerm } from 'state/user/hooks' import { ExternalLink } from 'theme' -import { isOverriddenWallet } from 'utils' -import Option from './Option' import PendingView from './PendingView' +import { useConnections } from './useConnections' const CloseIcon = styled.div` height: 24px; @@ -107,31 +103,12 @@ const HoverText = styled.div` } ` -enum WALLET_VIEWS { - CHANGE_WALLET = 'CHANGE_WALLET', - ACCOUNT = 'account', - PENDING = 'pending', -} - -type WalletInfoExtended = WalletInfo & { - key: SUPPORTED_WALLET - readyStateResult: WalletReadyState | undefined - isOverridden: boolean -} - export default function WalletModal() { - const { isWrongNetwork, account, walletKey } = useActiveWeb3React() - // important that these are destructed from the account-specific web3-react context - const { active, connector } = useWeb3React() - const { tryActivation } = useActivationWallet() - - const theme = useTheme() + const { isWrongNetwork, account } = useActiveWeb3React() - const [walletView, setWalletView] = useState(WALLET_VIEWS.ACCOUNT) - const [pendingWalletKey, setPendingWalletKey] = useState() + const { activationState, cancelActivation } = useActivationState() - const [pendingError, setPendingError] = useState() - const [error, setError] = useState(null) + const theme = useTheme() const walletModalOpen = useModalOpen(ApplicationModal.WALLET) const toggleWalletModal = useWalletModalToggle() @@ -139,130 +116,35 @@ export default function WalletModal() { const openWalletModal = useOpenModal(ApplicationModal.WALLET) const openNetworkModal = useOpenNetworkModal() - const previousAccount = usePrevious(account) + const onDismiss = () => { + cancelActivation() + closeWalletModal() + } const [isAcceptedTerm, setIsAcceptedTerm] = useIsAcceptedTerm() - const location = useLocation() const { mixpanelHandler } = useMixpanel() - useEffect(() => { - !account && walletModalOpen && mixpanelHandler(MIXPANEL_TYPE.WALLET_CONNECT_CLICK) - }, [mixpanelHandler, walletModalOpen, account]) - - // close on connection, when logged out before - useEffect(() => { - if (account && !previousAccount && walletModalOpen) { - toggleWalletModal() - } - }, [account, previousAccount, toggleWalletModal, walletModalOpen, location.pathname]) - useEffect(() => { if (isWrongNetwork) { openNetworkModal() } }, [isWrongNetwork, openNetworkModal]) - // always reset to account view - useEffect(() => { - if (walletModalOpen) { - setPendingError(false) - setError(null) - setWalletView(WALLET_VIEWS.ACCOUNT) - } - }, [walletModalOpen]) - - // close modal when a connection is successful - const activePrevious = usePrevious(active) - const connectorPrevious = usePrevious(connector) - - useEffect(() => { - if (walletModalOpen && ((active && !activePrevious) || (connector !== connectorPrevious && !error))) { - setWalletView(WALLET_VIEWS.ACCOUNT) - } - }, [setWalletView, active, error, connector, walletModalOpen, activePrevious, connectorPrevious]) - - const [, setIsConnectingWallet] = useIsConnectingWallet() - const handleWalletChange = useCallback( - async (walletKey: SUPPORTED_WALLET) => { - mixpanelHandler(MIXPANEL_TYPE.WALLET_CONNECT_WALLET_CLICK, { wallet: walletKey }) - setPendingWalletKey(walletKey) - setWalletView(WALLET_VIEWS.PENDING) - setIsConnectingWallet(true) - try { - await tryActivation(walletKey) - setPendingError(false) - setError(null) - } catch (error) { - setPendingError(true) - setError(error) - } - setTimeout(() => { - setIsConnectingWallet(false) - }, 1000) - }, - [tryActivation, setIsConnectingWallet, mixpanelHandler], - ) - - function getOptions() { - // Generate list of wallets and states of it depend on current network - const parsedWalletList: WalletInfoExtended[] = (Object.keys(SUPPORTED_WALLETS) as SUPPORTED_WALLET[]).map(k => { - const wallet = SUPPORTED_WALLETS[k] - const readyState = wallet.readyState() - const overridden = isOverriddenWallet(k) || (walletKey === 'COIN98' && !window.ethereum?.isCoin98) - - return { - ...wallet, - key: k, - readyStateResult: readyState, - isOverridden: overridden, - installLink: readyState === WalletReadyState.NotDetected ? wallet.installLink : undefined, - } - }) + const { orderedConnections } = useConnections() - const sortPoint: { [readyState in WalletReadyState]: number } = { - [WalletReadyState.Installed]: 1000, - [WalletReadyState.Loadable]: 100, - [WalletReadyState.NotDetected]: 10, - [WalletReadyState.Unsupported]: 1, - } - const sortWallets = (walletA: WalletInfoExtended, walletB: WalletInfoExtended): number => { - return ( - sortPoint[walletB.readyStateResult || WalletReadyState.Unsupported] - - sortPoint[walletA.readyStateResult || WalletReadyState.Unsupported] - ) - } - return ( - parsedWalletList - .sort(sortWallets) - // Filter Unsupported state wallets - .filter(wallet => wallet.readyStateResult !== WalletReadyState.Unsupported) - .map(wallet => ( -