1

i am trying to pay for a transaction to post a title to my anchor code, but we get the error Error: failed to send transaction: Transaction simulation failed: Attempt to debit an account but found no record of a prior credit, which is strange since i do have 4 sol on the author.publicKey so it should have enough sol to pay for the transaction. this is my react code

import * as Web3 from '@solana/web3.js';
import * as fs from 'fs';
import dotenv from 'dotenv';
dotenv.config();

const PROGRAM_ID = new Web3.PublicKey("ChT1B39WKLS8qUrkLvFDXMhEJ4F1XZzwUNHUt4AU9aVa")
const PROGRAM_DATA_PUBLIC_KEY = new Web3.PublicKey("Ah9K7dQ8EHaZqcAsgBW8w37yN2eAy3koFmUn4x3CJtod")


const TWEET_ACCOUNT_FILE = 'tweet_account.json';
const author_ACCOUNT_FILE = 'author_account.json';
async function pingProgram(
  connection: Web3.Connection,
  tweet: Web3.Keypair,
  author: Web3.Keypair
) {
  const transaction = new Web3.Transaction();
  // console.log(tweet.publicKey.toString());
  const tweetTitle = "My first tweet!";
  const instruction = new Web3.TransactionInstruction({
    keys: [
      { pubkey: tweet.publicKey, isSigner: false, isWritable: true },
      { pubkey: author.publicKey, isSigner: true, isWritable: false },
      { pubkey: PROGRAM_DATA_PUBLIC_KEY, isSigner: false, isWritable: false },
    ],
    programId: PROGRAM_ID,
  });
  
  const authorSecret = author.secretKey
  transaction.add(instruction);
  
  const transactionSignature = await Web3.sendAndConfirmTransaction(
    connection,
    transaction,
    [author], // add author as payer to signers
    { commitment: 'singleGossip', preflightCommitment: 'singleGossip' },
  );

  console.log(
    `Transaction https://explorer.solana.com/tx/${transactionSignature}?cluster=testnet`
  );
}



async function main() {
  const connection = new Web3.Connection(Web3.clusterApiUrl('testnet'));
  // const signer = await Web3.Keypair.generate();
  let author;
  if (!process.env.PRIVATE_KEY) {
    console.log('Generating new keypair');
    author = Web3.Keypair.generate();
    fs.writeFileSync('.env', `PRIVATE_KEY=[${author.secretKey.toString()}]`);
  } else {
    console.log('Using existing keypair');
    const privateKeyArray = process.env.PRIVATE_KEY.split(',').map(s => parseInt(s));
    const privateKeyUint8Array = new Uint8Array(privateKeyArray);
    author = new Web3.Keypair({ publicKey: privateKeyUint8Array.slice(32), secretKey: privateKeyUint8Array });
  }  
  
  let tweet = Web3.Keypair.generate();
  const balance = await connection.getBalance(author.publicKey);
  console.log('Current balance is', balance / Web3.LAMPORTS_PER_SOL, 'SOL');

  // 1 SOL should be enough for almost anything you wanna do
  if (balance / Web3.LAMPORTS_PER_SOL < 3) {
    // You can only get up to 2 SOL per request 
    console.log('Airdropping 1 SOL');
    const airdropSignature = await connection.requestAirdrop(
      author.publicKey,
      Web3.LAMPORTS_PER_SOL
    );

    const latestBlockhash = await connection.getLatestBlockhash();

    await connection.confirmTransaction({
      blockhash: latestBlockhash.blockhash,
      lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
      signature: airdropSignature,
    });

    const newBalance = await connection.getBalance(author.publicKey);
    console.log('New balance is', newBalance / Web3.LAMPORTS_PER_SOL, 'SOL');
  }
  // console.log("New bbaalance is", newBalance / Web3.LAMPORTS_PER_SOL)
  await pingProgram(connection, author, tweet);
}


main()
  .then(() => {
    console.log('Finished successfully');
    process.exit(0);
  })
  .catch((error) => {
    console.log('Error:', error.message);
    console.log('Stack trace:', error.stack);
    process.exit(1);
  });

And this is my anchor code if needed

use anchor_lang::prelude::*;
use anchor_lang::solana_program::system_program;
use solana_program::entrypoint::ProgramResult;

declare_id!("FS1yZFS9Vjbv77rqXBk46eGUdTgUXP7esZwKxtQFW8Ku");

#[program]
pub mod solana_twitter {
    use super::*;
    pub fn send_tweet(ctx: Context<SendTweet>, title: String) -> ProgramResult {
        let tweet: &mut Account<Tweet> = &mut ctx.accounts.tweet;
        let author: &Signer = &ctx.accounts.author;
        tweet.title = title.to_string();
        Ok(())
    }
}

#[derive(Accounts)]
pub struct SendTweet<'info> {
    #[account(init, payer = author, space = 100)]
    pub tweet: Account<'info, Tweet>,
    #[account(mut)]
    pub author: Signer<'info>,
    #[account(address = system_program::ID)]
    pub system_program: AccountInfo<'info>,
}

#[account]
pub struct Tweet {
    pub author: Pubkey,
    pub title: String,
}

The Terminal output if needed


Using existing keypair
Current balance is 2 SOL
Airdropping 1 SOL
New balance is 4 SOL
Error: failed to send transaction: Transaction simulation failed: Attempt to debit an account but found no record of a prior credit.
Stack trace: Error: failed to send transaction: Transaction simulation failed: Attempt to debit an account but found no record of a prior credit.
    at Connection.sendEncodedTransaction (/Users/test/anchor/sol-tutorial/solana-intro-client/node_modules/@solana/web3.js/src/connection.ts:5791:13)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Connection.sendRawTransaction (/Users/test/anchor/sol-tutorial/solana-intro-client/node_modules/@solana/web3.js/src/connection.ts:5750:20)
    at async Connection.sendTransaction (/Users/test/anchor/sol-tutorial/solana-intro-client/node_modules/@solana/web3.js/src/connection.ts:5738:12)
    at async Object.sendAndConfirmTransaction (/Users/test/anchor/sol-tutorial/solana-intro-client/node_modules/@solana/web3.js/src/utils/send-and-confirm-transaction.ts:35:21)

1 Answer 1

1

You've mixed up your parameters. The function is defined as

async function pingProgram(
  connection: Web3.Connection,
  tweet: Web3.Keypair,
  author: Web3.Keypair
) {

and you're calling

  await pingProgram(connection, author, tweet);

So you're trying to pay with the tweet account, which doesn't have any SOL. Change up the params and you should be good to go!

2
  • That did not work. the author is the payer so i changed the await the pingProgram(connection,tweet,author) so the author as the last parameter but we now get this error Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x64 Stack trace: Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x64
    – Solanaly
    Commented May 10, 2023 at 14:43
  • Unfortunately, we can only solve one problem at a time! feel free to submit another question
    – Jon C
    Commented May 11, 2023 at 14:15

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.