Skip to content

Instantly share code, notes, and snippets.

@duanescarlett
Last active January 5, 2023 23:49
Show Gist options
  • Save duanescarlett/e0c60ca691e541a64501205fc59ebec6 to your computer and use it in GitHub Desktop.
Save duanescarlett/e0c60ca691e541a64501205fc59ebec6 to your computer and use it in GitHub Desktop.
Send ERC-20 tokens to another wallet
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 transaction params
const txParams = {
gasLimit: 3000000,
gasPrice: ethers.utils.parseUnits('100', 'gwei'),
}
// Create an ERC20 interface for ethersJS
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 tokenAddress = toChecksumAddress('0x385Eeac5cB85A38A9a07A70c73e0a3271CfB54A7')
// Checksum the recipient address
let recipient = toChecksumAddress('0xC96146959790EfB2e354802f664090fCc75296D6')
// Make a js obj of a token contract
const token = new ethers.Contract(tokenAddress, IERC20, signer)
// Get the token erc-20 token balance
let ercBalance = await token.balanceOf(wallet.address)
console.log('Token Balance: => ', ercBalance.toString())
// Send token to another wallet
const tx = await token.transfer(recipient, ercBalance, txParams)
console.log(tx)
}
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