You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@solana/spl-token创建代币时遇TypeError: x.pubkey.toBase58错误

错误原因分析
  1. 参数类型不匹配:mintTo函数的第四个参数要求传入代币账户的PublicKey实例,但你传入了getOrCreateAssociatedTokenAccount返回的完整代币账户对象。函数内部期望直接处理PublicKey类型,导致调用toBase58()方法时触发类型错误。
  2. 数量计算逻辑错误:代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:15:35