0

I want to call the balanceOf method from the ERC20 smart contract. Is it possible to do so using Metamask's RPC provider, or do I always need to provide my own host?

For example, this following example works fine, but I need to provide my own host with my API key, which I suspect is not ideal for a public DApp.

const erc20GetBalanceAbi: any = [
  {
    constant: true,
    inputs: [{ name: '_owner', type: 'address' }],
    name: 'balanceOf',
    outputs: [{ name: 'balance', type: 'uint256' }],
    type: 'function'
  }
];

async function getErc20Balance(wallet: string, tokenAddress: string) {
  const web3 = new Web3(new Web3.providers.HttpProvider('https://my.personal.rpc?apikey=123'));
  const contract = new web3.eth.Contract(erc20GetBalanceAbi, tokenAddress);
  return = await contract.methods.balanceOf(wallet).call();
}

To summarize: is there a way to leverage a connected Metamask account to make this kind of ABI function call? If not, what is the preferred way to provide an RPC host on a public DApp?

2 Answers 2

1

you should use wallet provider for connecting to RPC. for example in metamask:

let provider = await detectEthereumProvider();
if (provider === window.ethereum) {
     let web3 = new Web3(provider);
     ....

metamask document

1
  • Thank you, that works fine! I was definitely overthinking it. Aug 2 at 14:25
0

Yes you'll have to provide your own.

MetaMask RPC provider only works with MM (I tried to use the default RPC endpoint in my scripts before lol).

What you can do is to use a .evn file and import your RPC endpoint as an environment variable, so that your API key is not exposed, you should do the same if using private keys or other sensitive information.

Don't forget to include the .env file into your .gitignore so you don't push it online by mistake!

How to use environment variables

If you need suggestions for a good node provider I recommend Chainstack, which provides fast and reliable nodes!

2
  • Since it's a web application, even when imported as an environment variable, the API key will get exposed in the browser's network tab. Aug 2 at 14:15
  • I guess I misunderstood your question then, I did not realize that you wanted to do that using MM.
    – Soos3D
    Aug 2 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.