Search code examples
node.jssolanasolana-web3js

How to pay rent fee when creating solana wallet in nodejs


hello I create solana wallet with the following code on my nodejs server.

const SolanaWeb3 = require("@solana/web3.js"); 
SolanaWeb3.Keypair.generate();

I don't think this is an active wallet. Because I haven't paid the rent fee for this account.

**So I want to know when is the moment when this inactive account pays the rent fee. (I want to know if it is activated when a transaction in which sol is deposited into this account occurs, or whether this account should generate a transaction that sends solana to another place.)

And I want to know if there is a javascript function that gives rent fee when account is created.**

thank you for your reply.


Solution

  • To your second question

    And I want to know if there is a javascript function that gives rent fee when account is created

    Yes there is. Assuming you just want a system account that holds SOL versus an account that has data:

      // amount of space to reserve for the account. system accounts are 0 space
      const space = 0;
    
      // Get the rent, in lamports, for exemption
      const rentExemptionAmount =
        await connection.getMinimumBalanceForRentExemption(space);
    

    To your first question

    If you already have a funded account (fromKeyPair), you can use that accounts public key to fund the new account you want to create:

      const newAccountKeypair = SolanaWeb3.Keypair.generate();
    
      const createAccountParams = {
        fromPubkey: fromKeyPair.publicKey,
        newAccountPubkey: newAccountKeypair.publicKey,
        lamports: rentExemptionAmount,
        space,
        programId: SolanaWeb3.SystemProgram.programId,
      };
    
    
      const createAccountTransaction = new SolanaWeb3.Transaction().add(
        SolanaWeb3.SystemProgram.createAccount(createAccountParams)
      );
    
      await SolanaWeb3.sendAndConfirmTransaction(connection, createAccountTransaction, [
        fromKeyPair,
        newAccountKeypair,
      ]);