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

使用spl js库铸造SPL代币失败:TypeError报错求助

Solana Devnet铸造SPL代币TypeError问题解决

问题场景

尝试使用spl js库在Solana Devnet铸造SPL代币,代码如下:

(async () => {
  const connection = new web3.Connection(web3.clusterApiUrl("devnet"));

  let secretKey = Uint8Array.from([
    186, 104, 237, 47, 123, 227, 2, 226, 150, 7, 169, 40, 252, 67, 161, 86, 198,....
    183, 130, 31, 174, 135, 153, 46, 227, 154, 125, 20, 79, 209,
  ]);

  const myKeypair = web3.Keypair.fromSecretKey(secretKey);

  console.log(myKeypair.publicKey);
  
  mint = await splToken.createMint(
    connection,
    myKeypair,
    myKeypair.publicKey,
    null,
    9,
    splToken.TOKEN_PROGRAM_ID
  );

  console.log("mint:"+mint);
})();

运行后触发错误:

solana/node_modules/@solana/web3.js/lib/index.cjs.js:1791
const key = signer.publicKey.toString();
^
TypeError: Cannot read properties of undefined (reading 'toString')
at Transaction.sign solana/node_modules/@solana/web3.js/lib/index.cjs.js:1791:36)
at Connection.sendTransaction solana/node_modules/@solana/web3.js/lib/index.cjs.js:9676:21)

问题原因

  1. SecretKey长度无效:Solana密钥对的secretKey必须是64字节的数组,原代码中secretKey被省略后长度不足,导致生成的Keypair对象异常,签名交易时signer.publicKey为undefined。
  2. 变量未显式声明:mint变量未用let/const声明,存在全局变量污染风险。
  3. 账户余额不足(潜在问题):铸造代币需要支付链上手续费,若payer账户无足够Devnet SOL,后续可能触发其他错误。

修复方案

修复后的完整代码

const web3 = require('@solana/web3.js');
const splToken = require('@solana/spl-token');

(async () => {
  // 连接Solana Devnet节点
  const connection = new web3.Connection(web3.clusterApiUrl("devnet"));

  // 替换为完整的64字节SecretKey
  const secretKey = Uint8Array.from([
    186, 104, 237, 47, 123, 227, 2, 226, 150, 7, 169, 40, 252, 67, 161, 86,
    198, 121, 45, 201, 33, 14, 207, 19, 241, 177, 222, 103, 212, 109, 176, 23,
    183, 130, 31, 174, 135, 153, 46, 227, 154, 125, 20, 79, 209, 55, 112, 88,
    14, 201, 99, 178, 210, 13, 22, 67, 189, 12, 34, 76, 190, 200
  ]);

  // 生成有效Keypair
  const myKeypair = web3.Keypair.fromSecretKey(secretKey);
  console.log("钱包地址:", myKeypair.publicKey.toString());

  // 为账户申请Devnet SOL空投(确保有手续费)
  const airdropTx = await connection.requestAirdrop(
    myKeypair.publicKey,
    web3.LAMPORTS_PER_SOL // 1 SOL
  );
  await connection.confirmTransaction(airdropTx);

  // 铸造SPL代币
  const mint = await splToken.createMint(
    connection,
    myKeypair, // 支付手续费的账户
    myKeypair.publicKey, // 代币发行权限账户
    null, // 冻结权限账户(设为null则无冻结权限)
    9, // 代币小数位数
    splToken.TOKEN_PROGRAM_ID
  );

  console.log("Mint地址:", mint.toString());
})();

关键修复点

  • 确保secretKey是64字节的完整数组,可从Solana钱包导出获取。
  • 显式声明所有变量(如const secretKey、const mint),避免全局变量问题。
  • 添加空投逻辑,确保payer账户有足够的Devnet SOL支付手续费。

依赖版本匹配

若仍有问题,建议安装兼容版本的依赖:

npm install @solana/web3.js@1.78.5 @solana/spl-token@0.3.8

内容的提问来源于stack exchange,提问作者S M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:01:04