Skip to content

Instantly share code, notes, and snippets.

@dicethedev
Created April 26, 2023 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dicethedev/77ccb0ebedafe4df3292b36a19b98e1f to your computer and use it in GitHub Desktop.
Save dicethedev/77ccb0ebedafe4df3292b36a19b98e1f to your computer and use it in GitHub Desktop.
How to extract the contract address from an ERC20 token owned by a user using Ethers.js
import { ethers } from 'ethers';
const ERC20_ABI = ... // Replace with the ABI of your ERC20 token
async function getContractAddress(tokenAddress, userAddress) {
const provider = new ethers.providers.InfuraProvider('mainnet', 'YOUR_INFURA_PROJECT_ID');
const contract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);
const balance = await contract.balanceOf(userAddress);
console.log(`Contract address of ${tokenAddress}: ${contract.address}`);
}
getContractAddress('0x123...', '0x456...');
/*In this example, we are creating a new ethers.Contract instance with the ERC20 token's ABI and address.
*We can then use the contract.address property to retrieve the contract address of the ERC20 token.
*Note that we are using ethers.providers.InfuraProvider as the provider for the ethers.js library.
*This allows us to connect to the Ethereum network using Infura, which provides a reliable and stable API
*endpoint for interacting with the network.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment