How to transfer the entire account balance using web3.js
Learn how to transfer the entire balance from an account using web3.js.
Overview
Overview
In this recipe, we dive into the practical use of the web3.js library to execute a critical and often necessary operation within the Ethereum ecosystem: sending the entire balance from one account to another.
Environment setup
Environment setup
Install node.js if it has not been installed yet.
Create a new directory for your project, then install the web3.js library:
npm install web3
Get your Chainstack endpoint
Get your Chainstack endpoint
To run this code, you will need a Chainstack account and an Ethereum Sepolia node.
The same code will work with any EVM-compatible chain.
Sign up with Chainstack. Deploy a node. View node access and credentials.
The code
The code
Here’s a step-by-step explanation of how it operates and its functionalities:
Initialization
The script starts by importing the web3.js library and initializing a Web3 instance with an HTTP provider. This provider is a connection to an Ethereum node, specified by “YOUR_CHAINSTACK_RPC_NODE”.
sendEntireBalance Function
This is the core function of the script. It accepts two parameters:
secretKey
: The private key of the sender’s account. This key is necessary for signing transactions, allowing the blockchain to verify that the sender has authorized the transaction.to
: The recipient’s Ethereum address. This address will receive the entire balance of the sender’s account.
Account Setup
Using the sender’s private key, the script creates an account object and adds it to the web3 wallet. This step is necessary for the web3 instance to manage transactions from this account.
Transaction Preparation
The script fetches the sender’s account balance and the network’s current gas price.
- It then estimates the gas limit for the transaction, which is the maximum amount of gas the transaction can consume.
- With the gas price and gas limit, the script calculates the total gas cost of the transaction.
Calculating the Transfer Amount
The script calculates the amount of Ether (in Wei, the smallest unit of Ether) to be sent by subtracting the gas cost from the account’s total balance. It ensures the transaction fees are covered while transferring the maximum possible balance.
Transaction Signing and Sending
- A transaction object is created with the recipient address, the amount to send, the gas limit, the gas price, and the nonce (which ensures transactions are processed in order).
- The transaction is signed with the sender’s private key. This signature proves that the sender indeed created the transaction.
- The signed transaction is then broadcast to the Ethereum network.
Error Handling and Retries
The script includes error handling to manage failed transactions. It implements a retry mechanism, attempting to resend the transaction to a maximum number of retries (MAX_RETRIES
) if an error occurs. After each failed attempt, it waits for a cooldown period (COOLDOWN
) before retrying.
Logging
Throughout the process, the script logs various information to the console, including the attempt to send the balance, the current balance, gas prices, gas limits, the amount to send, and the transaction status. If the transaction is successful, it logs the transaction hash and provides a URL to view the transaction on the blockchain explorer.
Run the code
Run the code
You can get your endpoint and paste it into the endpoint const. Also, add your private key and destination.
The private key needs to start with
0x
.
Then, you can run it with node YOUR_SCRIPT_NAME.js
.
The console will log the process.