solana-labs / solana-program-library

A collection of Solana programs maintained by Solana Labs
https://solanalabs.com
Apache License 2.0
3.5k stars 2.04k forks source link

Solana Web3. How to close token account? #2682

Closed digaev closed 2 years ago

digaev commented 2 years ago

Hi, I'm new to Solana and I'm trying to create and close a token account. When I do it in the same transaction, everything works, but when I try to close the token account later in a separate transaction, it says SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: invalid account data for instruction.

Here is the code:

async function createAndCloseAccount() {
  const payer = payerKeypair(); // This is the main and the only account I use

  const tokenAccount = new solanaWeb3.Keypair();
  const tokenAccountIx = await connection.getMinimumBalanceForRentExemption(solanaSplToken.AccountLayout.span)
    .then((lamports) => solanaWeb3.SystemProgram.createAccount({
      fromPubkey: payer.publicKey,
      newAccountPubkey: tokenAccount.publicKey,
      lamports,
      space: solanaSplToken.AccountLayout.span,
      programId: solanaSplToken.TOKEN_PROGRAM_ID,
    }));

  const initAccTx = new solanaWeb3.Transaction({ feePayer: payer.publicKey });

  initAccTx.add(
    tokenAccountIx,
    solanaSplToken.Token.createInitAccountInstruction(
      solanaSplToken.TOKEN_PROGRAM_ID,
      solanaSplToken.NATIVE_MINT, // Native for now, but I plan to use my own nft program that call spl-token instuctions
      tokenAccount.publicKey,
      payer.publicKey,
    ),

    // solanaSplToken.Token.createCloseAccountInstruction(
    //   solanaSplToken.TOKEN_PROGRAM_ID,
    //   tokenAccount.publicKey,
    //   payer.publicKey,
    //   payer.publicKey,
    //   [],
    // ),
  );

  await connection.sendTransaction(initAccTx, [tokenAccount, payer], { skipPreflight: false, preflightCommitment: 'confirmed' });

  // Trying to close the token account
  const closeAccTx = new solanaWeb3.Transaction({ feePayer: payer.publicKey });

  closeAccTx.add(
    solanaSplToken.Token.createCloseAccountInstruction(
      solanaSplToken.TOKEN_PROGRAM_ID,
      tokenAccount.publicKey,
      payer.publicKey,
      payer.publicKey,
      [],
    ),
  );

  await connection.sendTransaction(closeAccTx, [payer, payer], { skipPreflight: false, preflightCommitment: 'confirmed' });
}

Can anyone please tell me what I'm doing wrong?

t-nelson commented 2 years ago

Hi! We don't use github for support. Please join us in #developer-support on https://solana.com/discord