Skip to main content

Command Palette

Search for a command to run...

Task 1 铸造 SPL Token

Published
3 min readView as Markdown
C
酷愛計算機技術Ardently Love Computer Technology 長期關註反洗錢反欺詐Long-term Focus on Anti-Money Laundering and Anti-Fraud 精通支付結算的技術、系統、流程和製度Proficient in the Technology, System, Process and Institution of Payment and Settlement

按照教程提示 https://github.com/Tools-touch/Task-/tree/main

以 root 身份,在 /home/username 目录下的 .bashrc 文件末尾添加

export PATH="/root/.local/share/solana/install/active_release/bin:$PATH"

再 source 使其生效,以后就不用每次设置环境变量,直接运行 solana ,不再报错

直接创建私钥文件,粘贴

# cat /root/.config/solana/id.json 
[212,78,160,231,242,42,172,91,83,17,233,55,206,42,189,225,187,131,172,31,88,63,176,201,23,219,226,234,43,139,216,37,50,35,228,80,250,174,213,250,188,163,128,35,116,74,121,1,92,144,198,145,189,40,59,239,215,92,113,103,90,26,114,235]

从 id.json 文件转化为私钥字符串

# node --input-type=module -e "import fs from 'fs'; import os from 'os'; import bs58 from 'bs58'; const p=os.homedir()+'/.config/solana/id.json'; const arr=Uint8Array.from(JSON.parse(fs.readFileSync(p,'utf8'))); console.log(arr.length); console.log(bs58.encode(arr));"

64
5FCAsErz4kUUSJ3Rjy5NNabnRVmFFpC1DXxoEtQ7uVZ7dbzL7kAWkHradz49mcacP1tK71SiStNvB5UfVHYBbnrn

配置测试网 RPC

# solana config get
Config File: /root/.config/solana/cli/config.yml
RPC URL: https://devnet.helius-rpc.com/?api-key=4114aeed-18a7-4c53-a71c-325ed42823a4 
WebSocket URL: wss://devnet.helius-rpc.com/?api-key=4114aeed-18a7-4c53-a71c-325ed42823a4 (computed)
Keypair Path: /root/.config/solana/id.json 
Commitment: confirmed

创建项目文件夹 task1 ,安装项目所需要的库

$ mkdir task1

$ cd task1

$ npm i -D typescript ts-node @types/node

$ npm i @solana/web3.js @solana/spl-token bs58 dotenv

在项目目录下创建 .env 文件

$ cat .env
#RPC_ENDPOINT=https://api.devnet.solana.com

RPC_ENDPOINT=https://devnet.helius-rpc.com/?api-key=4114aeed-18a7-4c53-a71c-325ed42823a4

SECRET=5FCAsErz4kUUSJ3Rjy5NNabnRVmFFpC1DXxoEtQ7uVZ7dbzL7kAWkHradz49mcacP1tK71SiStNvB5UfVHYBbnrn

配置 package.json,在里面添加

  "type": "module",
  "scripts": {
    "mint": "node mint.ts"
  },

创建 mint.ts 文件,复制代码

import {
  Keypair,
  Connection,
  sendAndConfirmTransaction,
  SystemProgram,
  Transaction,
} from "@solana/web3.js";

import {
  createAssociatedTokenAccountInstruction,
  createInitializeMint2Instruction,
  createMintToCheckedInstruction,
  getAssociatedTokenAddressSync,
  getMinimumBalanceForRentExemptMint,
  MINT_SIZE,
  TOKEN_PROGRAM_ID,
  ASSOCIATED_TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import "dotenv/config";

import bs58 from "bs58";
console.log("RPC_ENDPOINT =", process.env.RPC_ENDPOINT);

const feePayer = Keypair.fromSecretKey(
  bs58.decode(process.env.SECRET || "")
);

const connection = new Connection(process.env.RPC_ENDPOINT || "", "confirmed");

async function main() {
  try {
    const mint = Keypair.generate();
    const mintRent = await getMinimumBalanceForRentExemptMint(connection);

    // 1) Create mint account (SystemProgram.createAccount)
    const createAccountIx = SystemProgram.createAccount({
      fromPubkey: feePayer.publicKey,
      newAccountPubkey: mint.publicKey,
      space: MINT_SIZE,
      lamports: mintRent,
      programId: TOKEN_PROGRAM_ID,
    });

    // 2) Initialize mint (decimals=6, mintAuthority=feePayer, freezeAuthority=feePayer)
    const decimals = 6;
    const initializeMintIx = createInitializeMint2Instruction(
      mint.publicKey,
      decimals,
      feePayer.publicKey,
      feePayer.publicKey,
      TOKEN_PROGRAM_ID
    );

    // 3) Create ATA for feePayer
    const associatedTokenAccount = getAssociatedTokenAddressSync(
      mint.publicKey,
      feePayer.publicKey,
      false,
      TOKEN_PROGRAM_ID,
      ASSOCIATED_TOKEN_PROGRAM_ID
    );

    const createAssociatedTokenAccountIx = createAssociatedTokenAccountInstruction(
      feePayer.publicKey,          // payer
      associatedTokenAccount,       // ata
      feePayer.publicKey,          // owner
      mint.publicKey,              // mint
      TOKEN_PROGRAM_ID,
      ASSOCIATED_TOKEN_PROGRAM_ID
    );

    // 4) Mint 21,000,000 tokens to ATA (checked)
    const mintAmount = BigInt(21_000_000) * BigInt(10 ** decimals);

    const mintToCheckedIx = createMintToCheckedInstruction(
      mint.publicKey,              // mint
      associatedTokenAccount,       // destination
      feePayer.publicKey,          // authority (mintAuthority)
      mintAmount,                  // amount (base units)
      decimals,                    // decimals
      [],                          // multiSigners
      TOKEN_PROGRAM_ID
    );

    const recentBlockhash = await connection.getLatestBlockhash("confirmed");

    const transaction = new Transaction({
      feePayer: feePayer.publicKey,
      blockhash: recentBlockhash.blockhash,
      lastValidBlockHeight: recentBlockhash.lastValidBlockHeight,
    }).add(
      createAccountIx,
      initializeMintIx,
      createAssociatedTokenAccountIx,
      mintToCheckedIx
    );

    // 5) Signers: feePayer pays + signs mintTo authority, mint signs account creation
    const transactionSignature = await sendAndConfirmTransaction(
      connection,
      transaction,
      [feePayer, mint]
    );

    console.log("Mint Address:", mint.publicKey.toBase58());
    console.log("ATA Address:", associatedTokenAccount.toBase58());
    console.log("Transaction Signature:", transactionSignature);
  } catch (error) {
    console.error(`Oops, something went wrong: ${error}`);
  }
}

main();

运行 mint.ts ,铸造成功。但有个连接错误

$ npm run mint

> mint
> node mint.ts

RPC_ENDPOINT = https://devnet.helius-rpc.com/?api-key=4114aeed-18a7-4c53-a71c-325ed42823a4
Mint Address: FR2rPLNJPd8pXB1XoKUQJg99JyEFFhbY3RiLtNbwq8g8
ATA Address: 48W8xbfh8ARfi23YhZKSBKJF16Z9pmXWcxNPqKdUe7Hs
Transaction Signature: 3eZKFMqUUMi3MAwNYWbkWkkEw8xXW7dptVX87itLhemWpts7Bh4mZbgTcMrKau6ouax1UBeRtpKfxrWu3CJCS2ue
node:internal/deps/undici/undici:15845
      Error.captureStackTrace(err);
            ^

TypeError: fetch failed
    at node:internal/deps/undici/undici:15845:13
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async ClientBrowser.callServer (/home/zhangyu/桌面/task1/node_modules/@solana/web3.js/lib/index.cjs.js:5061:17) {
  [cause]: ConnectTimeoutError: Connect Timeout Error (attempted addresses: 104.18.36.169:443, timeout: 10000ms)
      at onConnectTimeout (node:internal/deps/undici/undici:1690:23)
      at Immediate._onImmediate (node:internal/deps/undici/undici:1671:11)
      at process.processImmediate (node:internal/timers:504:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

Node.js v24.12.0

在浏览器里看该交易哈希,能够查询到,与命令行回显一致

https://solscan.io/tx/3eZKFMqUUMi3MAwNYWbkWkkEw8xXW7dptVX87itLhemWpts7Bh4mZbgTcMrKau6ouax1UBeRtpKfxrWu3CJCS2ue?cluster=devnet

查看当前 solana 公钥地址和余额

# solana address
4Nj8R2UQiec3Sp5UWtWbrYAhuhgcKaxDcW7tsRziaSPL

# solana balance
1.99648912 SOL

More from this blog

Penetration Test、Python、Weaponization

721 posts

微信 smartcat9999 反欺詐Anti-Fraud 反洗錢Anti-Money Laundering 反逃稅Anti-Tax Evasion 滲透測試Penetration Test 武器化Weaponization