web3-react icon indicating copy to clipboard operation
web3-react copied to clipboard

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

Open viet-nv opened this issue 2 years ago • 1 comments

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @web3-react/[email protected] 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.

viet-nv avatar Jul 04 '23 10:07 viet-nv

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.

yzkun001 avatar Nov 21 '23 03:11 yzkun001