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

How can I get provider url from connected wallet?

Open zhaoyi0113 opened this issue 1 year ago • 2 comments

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.

zhaoyi0113 avatar Feb 03 '24 09:02 zhaoyi0113

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)
...

kaptn3 avatar Feb 08 '24 13:02 kaptn3

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);

AjayiMike avatar Feb 10 '24 12:02 AjayiMike