I'm facing an issue while attempting to send Solana on the testnet using JavaScript. The problem is that I'm getting an error in my console, and I also display an alert message saying 'Failed to send Solana: [error message]'. However, when I check on the Solana Explorer, it shows that the transaction was successful. I've tried several solutions, but I'm unable to resolve this issue. Any help would be greatly appreciated.

Here's the function I'm using:

const sendSolana = async () => {
  if (walletAddress && amountToSend && receiverWalletAddress) {
    const amount = BigInt(Math.floor(Number(amountToSend) * LAMPORTS_PER_SOL));
    const testnetConnection = new solanaWeb3.Connection(
      "https://api.testnet.solana.com",
    );
    const recentBlockhash = await testnetConnection.getLatestBlockhash();
    const senderPublicKey = new solanaWeb3.PublicKey(walletAddress);
    const receiverPublicKey = new solanaWeb3.PublicKey(receiverWalletAddress);
    const transaction = new solanaWeb3.Transaction({
      recentBlockhash: recentBlockhash.blockhash,
    });
    transaction.add(
      solanaWeb3.SystemProgram.transfer({
        fromPubkey: senderPublicKey,
        toPubkey: receiverPublicKey,
        lamports: amount,
      }),
    );
    transaction.sign(keyPair);
    try {
      const signature = await solanaWeb3.sendAndConfirmTransaction(
        testnetConnection,
        transaction,
        [keyPair],
      );
      console.log("SIGNATUREEEEE ", signature);
      const response = await testnetConnection.sendRawTransaction(signature);
      console.log(response);
      if (response.txid) {
        alert("Solana sent successfully!");
      } else {
        alert("Failed to send Solana!");
      }
    } catch (error) {
      console.error("Error sending Solana:", error);
      alert("Failed to send Solana: " + error.message);
    }
  } else {
    alert("Insufficient data!");
  }
};
If you've encountered a similar issue or have any insights, please share your thoughts. Thank you!
1

There are 1 answers

3
Jon C On BEST ANSWER

You're sending the transaction twice: first with sendAndConfirmTransaction, and again with sendRawTransaction.

That first transaction is correct and getting processed during the first call, and the second one is failing because you're only providing a signature, and not a serialized transaction.

To resolve this, simply get rid of the call to sendRawTransaction