Here is an example article based on your post:
Custom Token Balance Error in MetaMask
I recently deployed a custom ERC20 token using Solidity on my local machine and configured a random distribution to 10 accounts that I imported into Hardhat for testing purposes. As part of the deployment process, I configured Metamask to import all of these accounts.
Initially, everything seemed to work as expected. I was able to call balanceOf
on the deployed smart contract and get accurate results. However, when I tried to access the balance of a specific account using the same balanceOf
function, I started getting an error message.
After some investigation, I discovered that the problem was not with my Hardhat deployment or configuration, but with Metamask itself. Specifically, it seems that the “imported custom token” functionality in Metamask does not work as expected when used with a deployed smart contract.
Problem: Imported custom token
According to various forums and community discussions, I was able to reproduce the issue by importing my 10 accounts into Metamask using the “importer” function. When I imported these accounts into Metamask, I noticed that they were not actually used as accounts in the deployed contract.
The balanceOf
function expects a specific account address or contract balance mapping index, but since my accounts were imported without specifying which one to use, it did not work correctly. To resolve this issue, I had to specify the correct account address using the “importer” function provided by Metamask.
Troubleshooting
To resolve this issue, I did the following steps:
- Create a new file called
importer.js
in the same directory as my contract and deploy the contract code.
- In this importer script, use the following line of code to import the specified accounts into Metamask:
const accounts = await window.ethereum.send("importers", {
accounts: [
{ name: "account1" },
{ name: "account2" },
// ... add more accounts here if needed ...
],
});
This will import the specified accounts into Metamask and set them as the current account for our contract.
- Update my contract deployment code to use this importer script instead of importing all accounts with a
balanceOf
call:
pragma solidity ^0.8.0;
contract CustomContract {
// ...
}
importer(address _importer) payable importers._accounts;
function balanceOf() public view returns (uint256) {
uint256 balance = _importer.balanceOf(_contractAddress);
return balance;
}
By following these steps, I was able to resolve the issue with importing custom tokens into Metamask and accessing their balances in my deployed contract.