Skip to content

Instantly share code, notes, and snippets.

@0fuz
Last active June 7, 2022 11:43
Show Gist options
  • Save 0fuz/fb2cd39a81b45877ee0240a4327a7bcb to your computer and use it in GitHub Desktop.
Save 0fuz/fb2cd39a81b45877ee0240a4327a7bcb to your computer and use it in GitHub Desktop.
Template of using ETH wallet for transfering native and ERC20 funds. Same for EVM-compatible chains like BSC,FTM,MATIC.
npm init -y
npm i ethers

Set provider

let provider = new ethers.providers.JsonRpcProvider("https://bscrpc.com", 56) // bsc
// let provider = new ethers.providers.WebSocketProvider("wss://..........", 56) // bsc

Wallet create sample

const ethers = require('ethers')
let wallet = ethers.Wallet.createRandom()
wallet.connect(provider)
console.log('address   ', wallet.address)
console.log('mnemonic  ', wallet.mnemonic.phrase)
console.log('privateKey', wallet.privateKey)

Wallet import sample

let wallet = new ethers.Wallet("0x_privKey", provider)
let wallet = ethers.Wallet.fromMnemonic(wallet.mnemonic.phrase, provider)
// https://docs.ethers.io/v5/api/signer/#Wallet

Sample of sending native token (ETH or BNB to themselves)

const overrides = { // https://docs.ethers.io/v5/api/contract/contract/#contract-functionsSend
    gasLimit: 1200000,
    gasPrice: 5000000100, // gwei 5.0000001. Its usual gwei price for BSC chain
}

const WBNB = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
const amountToSend = ethers.utils.parseEther('0.05'); // 0.05 BNB

// .balanceOf(address)                   // read operation, free
// .transfer(destinationAddress, amount) // write operation, cost
const BEP20Abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Withdrawal","type":"event"}]

async function getBNBBalance(address) {
    return await provider.getBalance(address);
}

async function sendBnb(wallet, to, amountWei) {
    const tx = {
        from : wallet.address,
        to : to,
        value : amountWei,
        nonce : await provider.getTransactionCount(wallet.address, 'pending'),
        gasLimit : overrides.gasLimit,
        gasPrice : overrides.gasPrice
    }

    let tx = await wallet.sendTransaction(tx)
    console.log("Pending .transfer() tx:", tx.hash)
    await tx.wait();
    return response
}

async function getBep20Balance(address, tokenAddress = WBNB) {
    let c = new Contract(tokenAddress, BEP20Abi, provider);
    let balance = await c.balanceOf(address);
    return balance;
}

async function sendBep20(wallet, to, amountWei, tokenAddress) {
    let c = new Contract(tokenAddress, BEP20Abi, provider);
    c = c.connect(wallet)

    let tx = await c.transfer(to, amountWei, overrides) // https://docs.ethers.io/v5/api/contract/contract/#Contract--write
    console.log("Pending erc20.transfer tx:", tx.hash)
    await tx.wait();
    return tx
}

(async function () {
    let balanceBnb = await getBNBBalance(wallet.address)
    console.log("bnb balance (human format)     ", ethers.utils.formatEther(balance2))
    console.log("bnb balance (18decimals format)", balance2.String())

    let response1 = await sendBnb(wallet, wallet.address, amountToSend) // send Bnb to themselves
    console.log("Tx done:", response1.hash)
    
    let balanceWBNB = await getBep20Balance(wallet.address, WBNB)
    console.log("bep20 balance (human format)     ", ethers.utils.formatEther(balance))
    console.log("bep20 balance (18decimals format)", balance.String())
    
    let response2 = await sendBep20(wallet, wallet.address, balanceWBNB, WBNB) // send Bep20 to themselves
    console.log("Tx done:", response2.hash)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment