I'm trying to send all SOL from one wallet to another. My main problem is that I have many wallets with a small amount of SOL so I want to save as much SOL as I can.

async function transferToMain(){
  const fromKeypair = Keypair.generate();
  const toKeypair = Keypair.generate();
  const gasFee = 0; // Is there a safe amount?
  const lamports =  await connection.getBalance(fromKeypair.publicKey) - gasFee; 
  console.log(`FROM ${fromKeypair} TO ${toKeypair} AMOUNT ${lamports} BALANCE ${lamports + gasFee}`)
  const transaction = new Transaction().add(SystemProgram.transfer({
    fromPubkey: fromKeypair.publicKey,
    toPubkey: toKeypair.publicKey,
    lamports: lamports
  const signature = await sendAndConfirmTransaction(
  console.log('SIGNATURE: '+ signature)

Trying to send SOL exactly equal to balance will yield

SendTransactionError: failed to send transaction: Transaction simulation failed: Transaction leaves an account with a lower balance than rent-exempt minimum

I've tried to add a small amount for transfer fee, but it is prone to failure because gas fee fluctuates. The source code shows that it just takes BigInt/ number type for the lamport argument - and doesn't handle special input : transfer, transferParams.

On the CLI, we can do something like

$solana transfer --from <FROM_ADDRESS> <RECIPIENT_ADDRESS> ALL

I'm wondering if there is a similar way to do it on the JS API?

1 Answer 1



  1. https://solana-labs.github.io/solana-web3.js/classes/Connection.html#getAccountInfoAndContext and get the size of the account.

  2. https://solana-labs.github.io/solana-web3.js/classes/Connection.html#getMinimumBalanceForRentExemption to see how much needed for rent exempt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.