To send ETH using NodeJS, you can utilize the web3.js library. Here’s a basic example that demonstrates how to send ETH from one account to another:
First, make sure to install the necessary libraries:
1 | npm install web3 |
npm install web3
Here’s a basic NodeJS script to send ETH:
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 | const Web3 = require('web3'); const INFURA_ENDPOINT = 'YOUR_INFURA_ENDPOINT'; // Get this from Infura.io after registering for a free account const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_ENDPOINT)); const senderPrivateKey = 'YOUR_PRIVATE_KEY'; // Ensure this private key is kept secure! const senderAddress = 'SENDER_ADDRESS'; // This should match the address derived from the private key const recipientAddress = 'RECIPIENT_ADDRESS'; const sendEther = async () => { const nonce = await web3.eth.getTransactionCount(senderAddress, 'latest'); // Get the nonce for the sender const tx = { from: senderAddress, to: recipientAddress, value: web3.utils.toWei('1', 'ether'), // Sending 1 ETH gas: 21000, // Gas limit for a simple ETH transfer gasPrice: web3.utils.toWei('20', 'gwei'), // Gas price set to 20 Gwei nonce: nonce }; // Sign the transaction const signedTx = await web3.eth.accounts.signTransaction(tx, senderPrivateKey); // Send the transaction web3.eth.sendSignedTransaction(signedTx.rawTransaction) .on('receipt', receipt => { console.log('Transaction receipt:', receipt); }) .on('error', err => { console.error('Error sending transaction:', err); }); }; |
const Web3 = require('web3'); const INFURA_ENDPOINT = 'YOUR_INFURA_ENDPOINT'; // Get this from Infura.io after registering for a free account const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_ENDPOINT)); const senderPrivateKey = 'YOUR_PRIVATE_KEY'; // Ensure this private key is kept secure! const senderAddress = 'SENDER_ADDRESS'; // This should match the address derived from the private key const recipientAddress = 'RECIPIENT_ADDRESS'; const sendEther = async () => { const nonce = await web3.eth.getTransactionCount(senderAddress, 'latest'); // Get the nonce for the sender const tx = { from: senderAddress, to: recipientAddress, value: web3.utils.toWei('1', 'ether'), // Sending 1 ETH gas: 21000, // Gas limit for a simple ETH transfer gasPrice: web3.utils.toWei('20', 'gwei'), // Gas price set to 20 Gwei nonce: nonce }; // Sign the transaction const signedTx = await web3.eth.accounts.signTransaction(tx, senderPrivateKey); // Send the transaction web3.eth.sendSignedTransaction(signedTx.rawTransaction) .on('receipt', receipt => { console.log('Transaction receipt:', receipt); }) .on('error', err => { console.error('Error sending transaction:', err); }); };
Important Notes:
- The INFURA_ENDPOINT should be the link to your Ethereum endpoint on Infura (or any other Ethereum node provider). You get this after registering on Infura.io.
- Never expose your private key in the code for security reasons. Always store them securely, and preferably use environment variables or secure vaults.
- The gas and gasPrice are just estimates. Depending on the network’s status, you might need to adjust these values.
- Always test your code on a testnet before sending transactions on the mainnet to prevent losing funds due to any potential issues.
- Ensure your account has enough ETH to cover the transaction cost (value + gas * gasPrice).
Another popular approach to interact with the Ethereum blockchain from Node.js is using the ethers.js library, which provides a simpler and compact way to deal with Ethereum transactions.
Here’s how you can send ETH using ethers.js:
1 | npm install ethers |
npm install ethers
Use the following code to send ETH:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | const { Wallet, providers } = require('ethers'); const INFURA_PROJECT_ID = 'YOUR_INFURA_PROJECT_ID'; // Get this from Infura.io const provider = new providers.InfuraProvider('mainnet', INFURA_PROJECT_ID); const senderPrivateKey = 'YOUR_PRIVATE_KEY'; // Make sure to store this securely const senderWallet = new Wallet(senderPrivateKey, provider); const recipientAddress = 'RECIPIENT_ADDRESS'; const sendEther = async () => { const tx = { to: recipientAddress, value: ethers.utils.parseEther('1.0') // Sending 1 ETH }; const txResponse = await senderWallet.sendTransaction(tx); console.log(`Transaction hash: ${txResponse.hash}`); const receipt = await txResponse.wait(); console.log('Transaction was mined in block', receipt.blockNumber); }; |
const { Wallet, providers } = require('ethers'); const INFURA_PROJECT_ID = 'YOUR_INFURA_PROJECT_ID'; // Get this from Infura.io const provider = new providers.InfuraProvider('mainnet', INFURA_PROJECT_ID); const senderPrivateKey = 'YOUR_PRIVATE_KEY'; // Make sure to store this securely const senderWallet = new Wallet(senderPrivateKey, provider); const recipientAddress = 'RECIPIENT_ADDRESS'; const sendEther = async () => { const tx = { to: recipientAddress, value: ethers.utils.parseEther('1.0') // Sending 1 ETH }; const txResponse = await senderWallet.sendTransaction(tx); console.log(`Transaction hash: ${txResponse.hash}`); const receipt = await txResponse.wait(); console.log('Transaction was mined in block', receipt.blockNumber); };
- ethers.js automatically handles gas estimation if you don’t provide gas limits or prices, but you can still set them manually if desired.
- As before, always test on a testnet first to ensure that everything works as expected.
- Secure your private key. Never expose it directly in your source code. Use environment variables or other secure methods for production applications.
- As with the previous example, you’ll need an Infura project ID. Infura provides access to Ethereum nodes, allowing your application to communicate with the Ethereum network without running a full node.
Always remember that using an Infura Project ID or a private key directly in your codebase (especially if it’s public) is a security risk. Always use environment variables or other secret management tools to handle sensitive data in production environments.
You can wrap the sendSignedTransaction function inside a promise and then use async/await to handle it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | async function sendTransaction() { try { const receipt = await new Promise((resolve, reject) => { web3.eth.sendSignedTransaction(signedTx.rawTransaction) .on('receipt', resolve) .on('error', reject); }); console.log('Transaction receipt:', receipt); } catch (err) { console.error('Error sending transaction:', err); } } // Later in your code, you can call this function (async () => { await sendTransaction(); })(); |
async function sendTransaction() { try { const receipt = await new Promise((resolve, reject) => { web3.eth.sendSignedTransaction(signedTx.rawTransaction) .on('receipt', resolve) .on('error', reject); }); console.log('Transaction receipt:', receipt); } catch (err) { console.error('Error sending transaction:', err); } } // Later in your code, you can call this function (async () => { await sendTransaction(); })();
With this setup, the sendTransaction function will await the result of the transaction. If the transaction is successful, it will log the receipt. If there’s an error, it will log the error message.
To make the sendEther function return a promise of sendSignedTransaction, you can wrap the transaction sending process inside a new promise. The promise will resolve when you receive the receipt and reject if there’s an error.
Here’s the modified sendEther function:
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 | const sendEther = async (senderAddress, senderPrivateKey, recipientAddress, amount, gwei, network = "goerli" /* or "mainnet" */) => { const INFURA_MAIN_ENDPOINT = `https://${network}.infura.io/v3/.......................`; const web3 = new Web3(INFURA_MAIN_ENDPOINT); const nonce = await web3.eth.getTransactionCount(senderAddress, 'latest'); const tx = { from: senderAddress, to: recipientAddress, value: web3.utils.toWei(amount.toString(), 'ether'), // Sending amount ETH gas: 21000, // Gas limit for a simple ETH transfer gasPrice: web3.utils.toWei(gwei.toString(), 'gwei'), // Gas price nonce: nonce }; // Sign the transaction const signedTx = await web3.eth.accounts.signTransaction(tx, senderPrivateKey); // Send the transaction and return the promise return new Promise((resolve, reject) => { web3.eth.sendSignedTransaction(signedTx.rawTransaction) .on('receipt', receipt => { console.log('Transaction receipt:', receipt); resolve(receipt); }) .on('error', err => { console.error('Error sending transaction:', err); reject(err); }); }); }; // Example usage: (async () => { try { const receipt = await sendEther(senderAddress, senderPrivateKey, recipientAddress, amount, gwei, network); console.log('Transaction was successful:', receipt); } catch (err) { console.error('Transaction failed:', err); } })(); |
const sendEther = async (senderAddress, senderPrivateKey, recipientAddress, amount, gwei, network = "goerli" /* or "mainnet" */) => { const INFURA_MAIN_ENDPOINT = `https://${network}.infura.io/v3/.......................`; const web3 = new Web3(INFURA_MAIN_ENDPOINT); const nonce = await web3.eth.getTransactionCount(senderAddress, 'latest'); const tx = { from: senderAddress, to: recipientAddress, value: web3.utils.toWei(amount.toString(), 'ether'), // Sending amount ETH gas: 21000, // Gas limit for a simple ETH transfer gasPrice: web3.utils.toWei(gwei.toString(), 'gwei'), // Gas price nonce: nonce }; // Sign the transaction const signedTx = await web3.eth.accounts.signTransaction(tx, senderPrivateKey); // Send the transaction and return the promise return new Promise((resolve, reject) => { web3.eth.sendSignedTransaction(signedTx.rawTransaction) .on('receipt', receipt => { console.log('Transaction receipt:', receipt); resolve(receipt); }) .on('error', err => { console.error('Error sending transaction:', err); reject(err); }); }); }; // Example usage: (async () => { try { const receipt = await sendEther(senderAddress, senderPrivateKey, recipientAddress, amount, gwei, network); console.log('Transaction was successful:', receipt); } catch (err) { console.error('Transaction failed:', err); } })();
With this modification, you can now use await with sendEther to obtain the transaction receipt or catch any error that occurs during the transaction. Please note that if the gas price is set low or the price fee is not enough, the transaction may be stuck – and you might need to replace the previous transaction by increasing the gas price by at least 10%, see this: How to Fix “Returned Error: replacement transaction underpriced” when Sending the ETH on Ethereum Blockchain?
Ethereum Blockchain
- How to Fix "Returned Error: replacement transaction underpriced" when Sending the ETH on Ethereum Blockchain?
- How to Transfer or Send ETH to Another Wallet on Ethereum Blockchain?
- How to Check the Balance of a Ethereum Wallet Address?
- How to Check if a Given String is a Valid Ethereum Wallet Address?
- How to Get the Gas Price and Gas Fee on Ethereum Blockchain?
- How to Get the Latest Block Number (Head Block) on Ethereum Blockchain?
- Today.. Gas Fee was High
- Gas Fee is Fixed Regardless the Amount of ETH to Send
- The Simple Way to Watch the Transactions of an ETH Account
- Watch Gas Price Before You Send Steem to Swap ETH
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Compute Sum of 1/(1+2+..N) Using Math and Python
Next Post: The Known Public Free DNS Servers