Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zhaoyi0113 opened this issue Feb 3, 2024 · 2 comments
Open

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

zhaoyi0113 opened this issue Feb 3, 2024 · 2 comments

Comments

@zhaoyi0113
Copy link

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
Copy link

kaptn3 commented Feb 8, 2024

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants