Skip to content

Instantly share code, notes, and snippets.

@MayowaObisesan
Last active August 10, 2023 19:11
Show Gist options
  • Save MayowaObisesan/98e849cf9d9838d0cc7fc6afbe92769b to your computer and use it in GitHub Desktop.
Save MayowaObisesan/98e849cf9d9838d0cc7fc6afbe92769b to your computer and use it in GitHub Desktop.
This script fetches the USDC token details from the ethereum mainnet and returns: the total_supply, the name, the token symbol and the balance
/*
TODO:
Locate the address of USDC on ethereum mainnet,
1. Query the balance, the token decimal, the name, and the token symbol.
*/
/*
// 3 things are needed to interact with a Smart contract:
1. Address
2. ABI
3. provider
*/
import { ethers } from 'ethers';
const provider = ethers.getDefaultProvider("mainnet");
// Define the USDC contract address
const DaiAddress = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
// Define the USDC contract ABI (simplified)
const daiAbi = [
"function totalSupply() view returns (uint256)",
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() external view returns (uint8)",
"function balanceOf(address account) external view returns (uint256)"
];
// Create a contract object
const DaiContract = new ethers.Contract(DaiAddress, daiAbi, provider);
console.log("###############################");
console.log("Querying DAI token Details:");
console.log("###############################");
// Using the promises chaining style
function daiDetails() {
DaiContract.name().then(name => {
console.log("The name of the token is: ", name)
})
DaiContract.symbol().then(symbol => {
console.log("The symbol of the token is: ", symbol)
})
// Call the totalSupply method
DaiContract.totalSupply().then((result) => {
// Convert the result from wei to ether
let supply = ethers.formatEther(result);
console.log("The total supply of DAI is", supply);
});
provider.getBalance(DaiAddress).then((result) => {
console.log("The balance of DAI is : ", ethers.formatEther(result));
});
DaiContract.decimals().then(result => {
console.log("The decimal of the token is: ", ethers.formatUnits(result).toString())
})
}
daiDetails();
// OR USING THE ASYNC/AWAIT STYLE
const daiDetails2 = async () => {
const daiName = await DaiContract.name();
const daiSymbol = await DaiContract.symbol();
const daiBalance = await DaiContract.balanceOf(DaiAddress);
const daiTotalSupply = await DaiContract.totalSupply();
const daiDecimal = await DaiContract.decimals();
console.log("\nUsing async/await form");
console.log("The name of DAI token is: ", daiName);
console.log("The symbol of DAI token is: ", daiSymbol);
console.log("The balance of DAI token is: ", ethers.formatEther(daiBalance));
console.log("The total Supply of DAI token is: ", ethers.formatEther(daiTotalSupply));
console.log("The decimal of DAI token is: ", ethers.formatUnits(daiDecimal));
}
daiDetails2();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment