/
03_write_transactions
54 lines (35 loc) · 2.07 KB
/
03_write_transactions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// this is baased on using known private keys to send transactions. there are 3 other methods of doing this (using random private key, using mnemonics and using a JSON file)
const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider(`https://sepolia.infura.io/v3/8b9750710d56460d940aeff47967c4ba`)
const account1 ='0xD616f5A49571e7BCb1BB5326031bC8078BDA9Faa' //sender
const account2 = '0x70e8dE73cE538DA2bEEd35d14187F6959a8ecA96' //recipient
const privateKey1 = 'cd82a7d0d6e528322e8c26f9ccbc18767543786d073c48ef38a753f29b1e8f39' //sender private key
const wallet = new ethers.Wallet(privateKey1, provider)
const main = async() => {
//show account 1 balance before transfer
const senderBalanceBefore = await provider.getBalance(account1)
//show account 2 balance before transfer
const receiverBalanceBefore = await provider.getBalance(account2)
console.log(`\nSender balance before: ${ethers.formatEther(senderBalanceBefore)}\n`)
console.log(`\nReceiver balance before: ${ethers.formatEther(receiverBalanceBefore)}\n`)
// send ether
const tx = await wallet.sendTransaction({
to: account2,
value: ethers.parseEther("0.025")
})
// fetch transaction or wait for transaction to be mined
await tx.wait()
console.log(tx)
//show account 1 balance after transfer
const senderBalanceAfter = await provider.getBalance(account1)
//show account 2 balance after transfer
const receiverBalanceAfter = await provider.getBalance(account2)
console.log(`\nSender balance before: ${ethers.formatEther(senderBalanceAfter)}\n`)
console.log(`\nReceiver balance before: ${ethers.formatEther(receiverBalanceAfter)}\n`)
}
main()
// this allows you to generate a random wallet with a private key and mnemonics
const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider(`https://sepolia.infura.io/v3/8b9750710d56460d940aeff47967c4ba`)
const randomWallet = ethers.Wallet.createRandom();
console.log(randomWallet);