Uniswap / web3-react

A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
https://web3-react-mu.vercel.app/
GNU General Public License v3.0
5.56k stars 1.52k forks source link

this.provider.on('connect') return wrong chainId #852

Open viet-nv opened 1 year ago

viet-nv commented 1 year ago

Hi! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Today I used patch-package to patch @web3-react/metamask@8.2.1 for the project I'm working on.

There is an issue with this.provider.on('connect') when both the OKX wallet extension and Metamask extension are installed. When I connect my wallet for the first time, OKX requests that I choose between using Metamask or OKX. If I select Metamask and then switch to another network from my dapp, web3-react always switches back to the network that OKX is using. This issue also occurs on the Uniswap Interface. I have recorded a video demonstrating how to reproduce the issue on Uniswap: https://drive.google.com/file/d/1ekooojSgq0FGPH8osMRFHJ3wS7Elqtx-/view?usp=sharing

Upon investigating the library, I discovered that the chainId returned from the connect event is incorrect. I am unsure about what's causing this problem with OKX, but I believe we can ensure consistent data by querying the chainId from the provider instead of relying on the value from the connect event.

Here is the diff that solved my problem:

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;

This issue body was partially generated by patch-package.

yzkun001 commented 1 year ago

Currently I have this problem, it seems to be a problem with the okx wallet. This problem occurs when the user has both metamask and okx installed.