Tutorial

How to send Ether between adresses with Web3.js and Node.js

This is (or should be) a working example of sending some Ether between two addresses.

Requirements are:

  • Basic knowledge of Javascript
  • Basic knowledge of how Ethereum Blockchain works
  • Node.js installed in your device
  • Hardhat installed with npm in your device
  • Having an Alchemy account and API keys

Also, this tutorial should perfectly work in chains similar to Ethereum, like Binance Smart Chain and others.

We will be sending Ether only theoretically on frozen fork of Alchemy chain, so you do not need to worry about sending real Ether at all in learning. But also for the purpose of this tutorial do not use your real mnemonic phrase or private key but rather create a new wallet.

Pridal/a lubo dňa St, 10/13/2021 - 05:23
Prepare your enviroment

Since we are developers and we are poor, we do not want to spend a single penny on developing our application yet, there are tools designed to help us fork the chain and work on our local machine.

Installing Node.js

Install Node.js on your device, it is as easy as downloading latest version from their website.

Register on Alchemy website and get API keys

Alchemy provides easy access to forking mainnet with JSON-RPC endpoint available for you for testing whatever you wish. They are really awesome!

Setting up Hardhat

Set up Hardhat with NPM with a following command in powershell:

npm install --save-dev hardhat
Running local fork of Alchemy node through Hardhat

Run Hardhat with the following command in your powershell window

npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/<alchemy_api_key> 

Now your environment should be ready with JSON-RPC endpoint on port :8545

Important note

Whatever you will be doing on Alchemy Node set up with hardhat is for testing only, you do not operate with real ETH, once you close the powershell window, your Alchemy node will reset to its initial state and all the changes you have made will be forever erased. You do not need to fear running any transaction, and can test how much you wish (alchemy has its limits but for a small developer starting to learn web3 it is completely free)

Install necessary libraries

We need those libraries set up in order to use them. Web3 is used to communicate easily with blockchain and BigNumber is a javascript library used for really big numbers. Since most of the tokens have 18 decimals, javascript integer handling would overflow. This is where BigNumber library comes in handy.

npm install web3
npm install bignumber

 

Create index.js file in your Hardhat folder

So we have a file available to write into and later run a Node.js on.

Also place inside our requires for libraries:

const Web3 = require("web3");
const BigNumber = require("bignumber.js");

 

Connecting to JSON-RCP endpoint with Web3 library

Start with those lines to connect to JSON-RPC endpoint on port 8545 with Web3:

const provider = new Web3.providers.HttpProvider("http://127.0.0.1:8543"); // Our HardHat endpoint

const web3 = new Web3(provider);

 

Create main Async function
async function main() {

// our code will go here, all the other steps goes here

}

main();

 

Set up some ETH for our faucet account

We need to have some ETH in our main account in order to send some from it. We can use hardhat's built-in functions to set up some ETH initially when the code runs like that:

await provider.send("hardhat_setBalance", [
	  "0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199", // Replace this with your 0x address
	  "0x2000", // This is a HEX number, so if we want to fund our account with 20 ETH it will be 0x3130303030303030303030303030303030303030
]);
console.log("set up!");

In the code above, we are using hardhat's hardhat_setBalance function which allows us to fund our account when the code runs.

Send some ETH from our wallet to another

If we want to send some ETH, we need to sign the transaction with our private key. Prepare your private key and tell Web3 to use it in our transactions like this:

var WALLET_PRIVATE_KEY = "0x...<YOUR PRIVATE KEY HERE>";
var WALLET = web3.eth.accounts.privateKeyToAccount(WALLET_PRIVATE_KEY); // This results at your public 0x account

// Now we send 1 ETH na some other wallet
var rawTransaction = {
	from: WALLET,
	to: ANOTHER_WALLET_0x, // use 0x.. address of other wallet
	value: 1000000000000000000, // This is the value in WEI. Ether has 18 decimals, so 1*10**18
	gas: 200000, // Gas needed to send the ether, most likely it will be 21004
	data: "0x00" // Data is used when transfering tokens, since we are senting ETH, we pass 0, no data
};

await WALLET.signTransaction(rawTransaction)
.then(
	function(signedTx) {
		return web3.eth.sendSignedTransaction(signedTx.rawTransaction);
	}
)
.then(
	function(receipt) {
		return console.log("Transaction receipt: ", receipt);
	}
)
.catch(err => console.error(err));

 

Checking the balance of other wallet afterwards

If you are interested, if your transaction actually made it and want to check balance of other wallet, use this code:

// balance after 1 ETH send
var starting_balance = await web3.eth.getBalance(ANOTHER_WALLET_0x, function(err, result) {
  if (err) {
	console.log(err)
  } else {
	console.log("Compromised Wallet Balance: " + web3.utils.fromWei(result, "ether") + " ETH")
  }
});

 

Done!

Now you are ready to do some harder things. Or check our other tutorials on Ethereum and other beautiful chains!

Might interest you

Tutorial
Getting TypeError: $(...).once is not a function in your Drupal 8 site? Easily fixed.
Tutorial
Does not your Contact Form 7 work properly anymore after plugin or theme update? Check your console to see any error messages. Today I…

Recommended

Article
32 views
For the past few days I am trying to comprehend why / how this blockchain even gained it'…
Tutorial
95 views
This sketch is quite easy, I used Arduino Nano with OLED 0.96″ display 128×64 resolution…
Tutorial
157 views
While working on a fairly complex website with very complex views setup, including tens…
Tutorial
14 views
In this case we have two options, either we use hook_user_presave() or we can create new…
Tutorial
15 views
When using Swiftmailer under Drupal 8 / 9 it automatically sets the headers for sender to…
Tutorial
7 views
Yes, IOS / Safari is the new internet explorer. Amount of time I spend on debugging…
Tutorial
43 views
There is a very handy function in Drupal 8 / 9, allowing developers refresh view when…
Tutorial
22 views
Often, when doing SEO checkups, SEO specialist come up with adding Schema.org…
Tutorial
174 views
I needed to test my contracts against USDC contract, specifically I needed ERC-721 mint…
Tutorial
85 views
If you are a newbie like I am and struggling with setting the proper MYSQL my.cnf config…
Tutorial
25 views
I had trouble to set this up properly, because documentation is quite misleading or often…
Article
72 views
As the title says, DO NOT in any circumstances install ANY bitcoin price extension to ANY…
Tutorial
278 views
This is (or should be) a working example of sending some Ether between two addresses.…
Module
45 views
This list was fetched from Zapper, with their /v1/token-list endpoint. Which you can…
Tutorial
143 views
In the last months I am being pretty much bombarded by my clients with asking what…