-
-
Save Daltonic/bc4f985537de2bd700eef8289a3617a1 to your computer and use it in GitHub Desktop.
Send Ethers Programmatically
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('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