I have to build a token gated page. That means, only users that hold a specific ERC-20 in their MetaMask wallet, can access the page. But how can I access the MetaMask wallet and check it for Token?
Asked
Active
Viewed 420 times
1 Answers
2
You can get the user MetaMask address using the eth_requestAccounts
method of the Ethereum provider API.
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
Docs: https://docs.metamask.io/guide/getting-started.html#basic-considerations
Note: In older versions of MetaMask, it used to be possible to get all addresses that the user has allowed your app to fetch. Now it's possible to only get the first of the addresses that they share with you.
Then you can use the user address to pass it to the token contract function balanceOf(address)
. If the result is larger than 0, the user holds the tokens.
const abiJson = [{
"constant": true,
"inputs": [{"name":"who","type":"address"}],
"name": "balanceOf",
"outputs": [{"name":"","type":"uint256"}],
"payable": false,
"stateMutability": "view",
"type": "function"
}];
const tokenAddress = '0xdAC17F958D2ee523a2206206994597C13D831ec7';
const getUserBalance = async (userAddress) => {
const contract = new web3.eth.Contract(abiJson, tokenAddress);
const balance = await contract.methods.balanceOf(userAddress).call();
console.log(balance);
}
Note: Preferably on the backend. If you did this on the frontend, users could bypass your authentication mechanism.

Petr Hejda
- 40,554
- 8
- 72
- 100