Created
March 21, 2022 16:42
-
-
Save duanescarlett/86a4ffac8b0cc5ffe269cb2db0f0d0bf to your computer and use it in GitHub Desktop.
Get ether and erc-20 token balances in a wallet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ethers = require('ethers') | |
const { toChecksumAddress } = require('ethereum-checksum-address') | |
require('dotenv').config() | |
const main = async () => { | |
// Connect to an EVM network | |
const provider = new ethers.providers.JsonRpcProvider(`https://polygon-mainnet.g.alchemy.com/v2/${process.env.RPC_KEY}`) | |
// Create a wallet | |
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY) | |
// Get a signer | |
const signer = wallet.connect(provider) | |
// Get the Ether balance in wallet | |
const balance = await provider.getBalance(wallet.address) | |
console.log(balance.toString()) | |
// Create an erc-20 abi | |
const IERC20 = [ | |
'function name() external pure returns(string memory)', | |
'function symbol() external pure returns(string mamory)', | |
'function totalSupply() external view returns(uint256)', | |
'function balanceOf(address owner) external view returns (uint256)', | |
'function allowance(address owner, address spender) external view returns (uint256)', | |
'function approve(address spender, uint256 value) external returns (bool)', | |
'function transfer(address to, uint256 value) external returns (bool)', | |
'function transferFrom(address from, address to, uint256 value) external returns (bool)' | |
] | |
// Checksum the token address | |
let address = toChecksumAddress('0x385Eeac5cB85A38A9a07A70c73e0a3271CfB54A7') | |
// Make a js obj of a token contract | |
const token = new ethers.Contract(address, IERC20, signer) | |
// Get the token erc-20 token balance | |
let ercBalance = await token.balanceOf(wallet.address) | |
console.log(ercBalance.toString()) | |
} | |
main() | |
.then(() => process.exit(0)) | |
.catch((err) => { | |
console.error(err) | |
process.exit(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment