Why you shouldn't use web3-react and what are the alternatives. And how we handled this at https://floordle.app/
I needed my users to be able to connect with MetaMask and WalletConnect.
When googling for ways to do that I saw lots of articles on how you can implement this with web3-react, so I thought this is a beaten path and decided to give it a go.
Now for using this I had to import a Provider and wrap my parent component around it, also I had to install additional packages ( ethers.js, @web3-react/walletconnect-connector and some other package that was a connector for MetaMask ). Connecting to metamask worked fine, but walletconnect was somehow not displaying the QR modal. I went to their github and saw 27 open issues 🥲.
git stash. bye.
Now I was going with a different approach. This is framework agnostic so you can wrap these functions inside your framework's patterns.
Step 1:
yarn add ethers @walletconnect/web3-provider
Step 2: Create an infura account and copy your infuraId
Step 3:
import WalletConnectProvider from '@walletconnect/web3-provider';
import { ethers } from 'ethers';
Step 4: This is used only for WalletConnect. If you don't need WalletConnect just ignore this step.
const provider = new WalletConnectProvider({
infuraId: 'INFURA_ID',
});
Step 5: This is used only for WalletConnect. If you don't need WalletConnect just ignore this step.
const connectWalletConnect = async () => {
const ethersProvider = new ethers.providers.Web3Provider(provider);
await provider.enable();
provider.on('accountsChanged', (accounts) => {
// you can access the accounts here
console.log(accounts);
});
provider.on('disconnect', (code, reason) => {
//fired when disconnecting WalletConnect
console.log(code, reason);
});
};
Step 6: Connecting MetaMask
const connectMetamask = async () => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const accounts = await provider.send('eth_requestAccounts', []);
//ta-da. you now have the accounts, in here you can invoke a function, setState etc
} catch (error) {
//do something with the error
}
};
And that's it. Let me know if you want me to post a full guide on how to create a hook for this.