有人知道这段代码出了什么问题吗?
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);
它在线上抛出一个错误
const signature = await window.solana.signAndSendTransaction(await transaction)
关于将undefined转换为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)
有什么想法吗?
天哪,
我通过更改代码解决了这个问题:
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);
我仍然不明白为什么它有效,但嘿,它解决了我的问题。
错误TypeError: Cannot read properties of undefined (reading 'toBase58')
通常意味着某个地方存在无效的PublicKey
。
假设与钱包的连接是正确的,那么这条线路可能有问题:
let toWallet = new PublicKey("<KEY>");
首先,通过记录它来确保该调用的结果是正确的,即:
console.log(toWallet.toBase58());
如果这样做有效,那么钱包连接可能会出现问题。