使用@solana/spl-token创建代币时遇TypeError: x.pubkey.toBase58错误
错误原因分析
- 参数类型不匹配:
mintTo函数的第四个参数要求传入代币账户的PublicKey实例,但你传入了getOrCreateAssociatedTokenAccount返回的完整代币账户对象。函数内部期望直接处理PublicKey类型,导致调用toBase58()方法时触发类型错误。 - 数量计算逻辑错误:代码中
100 * (10 ^ 9)使用了位异或运算符^,这会得到错误的计算结果(实际为109),正确的指数运算应该使用**运算符来计算代币最小单位数量(对应9位精度)。
解决方案
修改mintTo的参数传递方式,传入代币账户的publicKey,并修正数量计算逻辑:
await mintTo( connection, payer, mint, tokenAccount.publicKey, // 改为传入代币账户公钥 mintAuthority, 100 * (10 ** 9) // 用**代替^执行指数运算 );
同时,后续getAccount调用也需要传入代币账户公钥,否则会触发相同类型错误:
const tokenAccountInfo = await getAccount(connection, tokenAccount.publicKey);
修改后的完整代码
import { getOrCreateAssociatedTokenAccount, mintTo, getAccount, getMint, createMint, } from "@solana/spl-token"; import { Keypair, Connection, clusterApiUrl, LAMPORTS_PER_SOL, } from "@solana/web3.js"; const payer = Keypair.generate(); const mintAuthority = payer; const connection = new Connection(clusterApiUrl("devnet"), "confirmed"); const airdropSignature = await connection.requestAirdrop( payer.publicKey, LAMPORTS_PER_SOL ); await connection.confirmTransaction(airdropSignature); const mint = await createMint( connection, payer, mintAuthority.publicKey, mintAuthority.publicKey, 9 ); const tokenAccount = await getOrCreateAssociatedTokenAccount( connection, payer, mint, mintAuthority.publicKey ); // 修正后的mintTo调用 await mintTo( connection, payer, mint, tokenAccount.publicKey, mintAuthority, 100 * (10 ** 9) ); const mintInfo = await getMint(connection, mint); console.log(`Mint supply: ${mintInfo.supply}`); // 修正后的getAccount调用 const tokenAccountInfo = await getAccount(connection, tokenAccount.publicKey); console.log(`Token account amount: ${tokenAccountInfo.amount}`);
内容的提问来源于stack exchange,提问作者denimcodes
相关产品推荐
相关产品推荐

