3

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(
    connection,
    transaction,
    [fromKeypair]
  )
  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

Try:

  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.

1
  • OP is asking to transfer it TOGETHER with the rent-exemption. You can clearly see they know how to just transfer any amount, but are being stopped by the rent-exemption error. Commented Jul 19 at 18:58

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.