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.48k stars 1.51k forks source link

How can I get provider url from connected wallet? #908

Open zhaoyi0113 opened 5 months ago

zhaoyi0113 commented 5 months ago

I am using this library to connect to metamask wallet. And I'd like to connect to a contract from Ethereum network. I found this library only focus on wallet and react but not smart contract. So I am using web3.js library for contract interaction. But the question is how I can get the provider information like URL from web3-react.


const { connector, hooks } = useWeb3React();
const connect = async () => {
    const chainId = Web3.utils.toHex(5);
    try {
      await connector.activate();
    } catch (err) {
      console.error('User rejected the request', err);
    }
  };

return (
    <div>

        <Button onClick={connect}> Connect</Button>

    </div>
  ); 

the above code is to open Metamask from browser. Now I need to create a Contract instance:

import { Contract } from 'web3-eth-contract';

const abi = [{...}];
const address = '0x...';
const contract = new Contract(abi, address { provider: 'http://127.0.0.1:8545' }); 

I need to provider some parameters for Contract constructor function. I am able to get abi, address, but how can I get the provider url from web3-react provider? I'd like to get the URL from the connected wallet rather than setting up an env var for that.

kaptn3 commented 4 months ago

Hi! I was also looking for an answer to the question, this code with web3.js works

const { connector } = useWeb3React();
...
const web3 = new Web3(connector.provider);
web3.eth.Contract(abi, address)
...
AjayiMike commented 4 months ago

connector, hooks

The same way you got connector and hooks from useWeb3React, you can also get a provider.

Everytime you're connected, you get a provider. the provider becomes undefined when you disconnect.

to fix: instead of this: const { connector, hooks } = useWeb3React();

You can also get the provider alongside connector and hooks like so const { connector, hooks, provider } = useWeb3React();

And instead of creating your contract instance like this: const contract = new Contract(abi, address { provider: 'http://127.0.0.1:8545' });

you can create it using the provider from web3-react const contract = new Contract(abi, address, provider);