Learn how to transfer the entire balance from an account using web3.js.
Overview
Environment setup
npm install web3
Get your Chainstack endpoint
The same code will work with any EVM-compatible chain.Sign up with Chainstack. Deploy a node. View node access and credentials.
The code
Initialization
sendEntireBalance Function
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
Transaction Preparation
Calculating the Transfer Amount
Transaction Signing and Sending
Error Handling and Retries
MAX_RETRIES
) if an error occurs. After each failed attempt, it waits for a cooldown period (COOLDOWN
) before retrying.Logging
Run the code
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.