Created
December 16, 2023 21:51
-
-
Save rezaiyan/e576a0bfdded9b5513d0cac1ab1fc83f to your computer and use it in GitHub Desktop.
This is a script for creating and sending an Ethereum transaction using the Web3 library and EthereumJS. It demonstrates how to set up the transaction parameters, sign it with a private key, and send it using Ganache, a local Ethereum blockchain emulator. Feel free to use and modify this code for your Ethereum-related projects.
This file contains hidden or 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 { Web3 } = require('web3'); | |
const EthereumTransaction = require('ethereumjs-tx').Transaction; | |
// Step 1: Set up the appropriate configuration | |
const web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545')); | |
async function transfer() { | |
// Step 2: Set the sending and receiving addresses for the transaction | |
const sendingAddress = 'sendingAddress'; | |
const receivingAddress = 'receivingAddress'; | |
// Step 3: Check the balances of each address | |
const checkBalance = async (address) => { | |
const balance = await web3.eth.getBalance(address); | |
console.log(`Balance of ${address}: ${balance}`); | |
}; | |
await Promise.all([checkBalance(sendingAddress), checkBalance(receivingAddress)]); | |
// Step 4: Create a transaction | |
const nonce = await web3.eth.getTransactionCount(sendingAddress, 'latest'); | |
console.log('Nonce:', nonce); | |
const transaction = { | |
to: receivingAddress, | |
value: web3.utils.toWei('1', 'ether'), | |
gasPrice: 765625000, // Gas price from network info | |
gasLimit: 30000, // Gas limit from network info | |
nonce: nonce, | |
data: web3.utils.toHex('Test') | |
}; | |
const privateKey = 'privateKey'; | |
const signedTx = await web3.eth.accounts.signTransaction(transaction, privateKey); | |
const rawTransaction = signedTx.rawTransaction; | |
console.log(`Nonce for address ${sendingAddress} is: ${nonce}`); | |
console.log('Raw transaction:', rawTransaction); | |
web3.eth.sendSignedTransaction(rawTransaction, (error, hash) => { | |
if (!error) { | |
console.log(`The hash of your transaction is: ${hash}\nCheck Transactions tab in Ganache to view your transaction!`); | |
} else { | |
console.log('Something went wrong while submitting your transaction:', error); | |
} | |
}); | |
} | |
transfer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment