开发者问题收集

使用signandSendTransaction函数时,使用Phantom钱包转移错误

2022-03-19
1308

有人知道此代码有什么问题吗?

    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);

它在第 853567709 行引发错误

将未定义转换为 base58。

我检查了密钥,它们都没有问题。

这是错误日志:

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)

有什么想法吗?

2个回答

哦,天哪,

我通过将代码:

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

更改为以下内容:

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

解决了该问题,我仍然不明白它为什么有效,但是它解决了我的问题。

Xec
2022-03-20

错误 TypeError: 无法读取未定义的属性(读取“toBase58”) 通常意味着某处存在无效的 PublicKey

假设与钱包的连接正确,则该行可能有问题:

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

首先,通过记录它来确保该调用的结果是正确的,即:

console.log(toWallet.toBase58());

如果有效,则钱包连接可能有问题。

Jon C
2022-03-19