Xec
Xec

Reputation: 63

Transfer error using Phantom Wallet when using signAndSendTransaction function

Does anyone know what's wrong with this code?

    await window.solana.connect();

    let fromWallet = window.solana.publicKey;
    let toWallet = new PublicKey("<KEY>");   
    
    let transaction = new Transaction();

    transaction.add(
      SystemProgram.transfer({
        fromPubKey: fromWallet,
        toPubKey: toWallet,
        lamports: LAMPORTS_PER_SOL
      })
    );

    transaction.feePayer = fromWallet;
    const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
    let bk = await connection.getLatestBlockhash();
    transaction.recentBlockhash = bk.blockhash;

    const signature = await window.solana.signAndSendTransaction(await transaction);        
    await connection.confirmTransaction(signature);
    console.log(signature);

It throws an error at line

const signature = await window.solana.signAndSendTransaction(await transaction)

Something about converting undefined to base58.

I have checked the keys, they are both fine.

Here is the error log:

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'toBase58')
    at eval (index.browser.esm.js?64b9:2451:1)
    at Array.sort (<anonymous>)
    at Transaction.compileMessage (index.browser.esm.js?64b9:2450:1)
    at Transaction._compile (index.browser.esm.js?64b9:2563:1)
    at Transaction.serializeMessage (index.browser.esm.js?64b9:2585:1)
    at ia (inpage.js:141:130205)
    at inpage.js:141:137033
    at c (inpage.js:2:47880)
    at Generator._invoke (inpage.js:2:47668)
    at Generator.next (inpage.js:2:48309)

Any ideas?

Upvotes: 1

Views: 1661

Answers (2)

Xec
Xec

Reputation: 63

Oh dear lord,

I fixed the issue by changing the code:

 transaction.add(
  SystemProgram.transfer({
    fromPubKey: fromWallet,
    toPubKey: toWallet,
    lamports: LAMPORTS_PER_SOL
  })
);

to the following:

  const instruction = SystemProgram.transfer({
    fromPubkey: fromWallet,
    toPubkey: toWallet,
    lamports: LAMPORTS_PER_SOL,
  });
  transaction.add(instruction);

I still don't understand why it works, but hey it solved my issue.

Upvotes: 1

Jon C
Jon C

Reputation: 8412

The error TypeError: Cannot read properties of undefined (reading 'toBase58') typically means that there's an invalid PublicKey somewhere.

Assuming that the connection to the wallet is correct, there's probably an issue with the line:

let toWallet = new PublicKey("<KEY>");

First, be sure that the result of that call is correct, by logging it, ie.:

console.log(toWallet.toBase58());

If that works, then there's likely an issue with the wallet connection.

Upvotes: 0

Related Questions