Skip to content

Instantly share code, notes, and snippets.

@Daltonic
Created February 8, 2023 01:52
Show Gist options
  • Save Daltonic/bc4f985537de2bd700eef8289a3617a1 to your computer and use it in GitHub Desktop.
Save Daltonic/bc4f985537de2bd700eef8289a3617a1 to your computer and use it in GitHub Desktop.
Send Ethers Programmatically
const { ethers } = require('hardhat')
const toWei = (num) => ethers.utils.parseEther(num.toString())
const fromWei = (num) => ethers.utils.formatEther(num)
const sendEthers = async (recipientAddress, amountInWei) => {
return new Promise(async (resolve, reject) => {
const privateKey =
'0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80'
const provider = new ethers.providers.JsonRpcProvider(
'http://localhost:8545',
)
const wallet = new ethers.Wallet(privateKey, provider)
const gasPrice = provider.getGasPrice()
const nonce = provider.getTransactionCount(wallet.address, 'latest')
const transaction = {
to: recipientAddress,
value: amountInWei,
gasPrice,
gasLimit: ethers.utils.hexlify(100000),
nonce,
}
await wallet
.sendTransaction(transaction)
.then((transactionHash) => resolve(transactionHash))
.catch((error) => reject(error))
})
}
const getBalance = async (walletAddress) => {
return new Promise(async (resolve, reject) => {
const provider = new ethers.providers.JsonRpcProvider(
'http://localhost:8545',
)
await provider
.getBalance(walletAddress)
.then((balanceInWei) => resolve(balanceInWei))
.catch((error) => reject(error))
})
}
async function main() {
;[sender, receiver] = await ethers.getSigners()
const amountInWei = toWei(4.7)
console.log('\n')
let balance = await getBalance(sender.address)
console.log('Sender balance before transfer: ', fromWei(balance))
balance = await getBalance(receiver.address)
console.log('Receiver balance before transfer: ', fromWei(balance))
console.log('\n')
await sendEthers(receiver.address, amountInWei).then((data) =>
console.log('Transaction Details: ', data),
)
console.log('\n')
balance = await getBalance(sender.address)
console.log('Sender balance after transfer: ', fromWei(balance))
balance = await getBalance(receiver.address)
console.log('Receiver balance after transfer: ', fromWei(balance))
console.log('\n')
}
main().catch((error) => {
console.error(error)
process.exitCode = 1
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment