什么是铸造账户
铸造账户在 Solana 上定义并唯一标识一个代币,并存储适用于该铸造账户下所有代币账户的共享状态。
Token Program 将 Mint 账户类型定义为:
Mint Account Type
/// Mint data.#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq)]pub struct Mint {/// Optional authority used to mint new tokens. The mint authority may only/// be provided during mint creation. If no mint authority is present/// then the mint has a fixed supply and no further tokens may be/// minted.pub mint_authority: COption<Pubkey>,/// Total supply of tokens.pub supply: u64,/// Number of base 10 digits to the right of the decimal place.pub decimals: u8,/// Is `true` if this structure has been initializedpub is_initialized: bool,/// Optional authority to freeze token accounts.pub freeze_authority: COption<Pubkey>,}
每个代币都有一个铸造账户,铸造地址是该代币在钱包、应用程序和浏览器中的唯一标识符。
例如,USD Coin (USDC) 的铸造地址为
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v。该铸造地址在整个 Solana 生态系统中唯一标识 USDC。您可以在
Solana Explorer
上查看此铸造账户。
如何创建铸造账户
创建铸造账户需要两个指令:
- System Program 的
CreateAccount指令创建一个新的免租金账户,并将 Token Program 指定为新账户的程序所有者。 - Token Program 的
InitializeMint或InitializeMint2指令将新账户初始化为铸造账户。
在同一笔交易中包含 CreateAccount 指令和铸造初始化指令。
在铸造初始化期间,Token
Program 检查铸造账户是否尚未初始化且已免除租金。然后 Token
Program 将铸造权限、冻结权限、小数位数和 is_initialized
标志写入铸造账户数据中。
源代码参考
| 项目 | 描述 | Token Program | Token Extensions Program |
|---|---|---|---|
Mint | 存储在每个铸造账户中的基础铸造状态。 | 源代码 | 源代码 |
InitializeMint | 铸造初始化指令,需要在其账户列表中包含租金系统变量账户。 | 源代码 | 源代码 |
InitializeMint2 | 铸造初始化指令,不需要在其账户列表中包含租金系统变量账户。 | 源代码 | 源代码 |
_process_initialize_mint | 铸造初始化的共享处理器逻辑。 | 源代码 | 源代码 |
process_initialize_mint | InitializeMint 的公共处理程序。 | 源代码 | 源代码 |
process_initialize_mint2 | InitializeMint2 的公共处理程序。 | 源代码 | 源代码 |
Typescript
以下 Kit 示例展示了使用 @solana/kit 的推荐方法。同时包含了使用
@solana/web3.js 的旧版示例供参考。
Kit
import { generateKeyPairSigner } from "@solana/kit";import { createLocalClient } from "@solana/kit-client-rpc";import { tokenProgram } from "@solana-program/token";const client = await createLocalClient().use(tokenProgram());const mint = await generateKeyPairSigner();const result = await client.token.instructions.createMint({newMint: mint, // New mint account to create.decimals: 9, // Decimals to define on the mint account.mintAuthority: client.payer.address, // Authority allowed to mint new tokens.freezeAuthority: client.payer.address // Authority allowed to freeze token accounts.}).sendTransaction();const mintAccount = await client.token.accounts.mint.fetch(mint.address);console.log("Mint Address:", mint.address);console.log("Mint Account:", mintAccount.data);console.log("\nTransaction Signature:", result.context.signature);
Console
Click to execute the code.
Web3.js
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";import { createMint, getMint, TOKEN_PROGRAM_ID } from "@solana/spl-token";const mintPubkey = await createMint(connection,feePayer,feePayer.publicKey, // Authority allowed to mint new tokens.feePayer.publicKey, // Authority allowed to freeze token accounts.9, // Decimals to define on the mint account.Keypair.generate(), // New mint account to create.{commitment: "confirmed"},TOKEN_PROGRAM_ID);const mintAccount = await getMint(connection,mintPubkey,"confirmed",TOKEN_PROGRAM_ID);console.log("Mint Address:", mintPubkey.toBase58());console.log("Mint Account:", mintAccount);
Console
Click to execute the code.
Rust
Rust
use anyhow::Result;use solana_client::nonblocking::rpc_client::RpcClient;use solana_commitment_config::CommitmentConfig;use solana_sdk::{program_pack::Pack,signature::{Keypair, Signer},transaction::Transaction,};use solana_system_interface::instruction::create_account;use spl_token_interface::{id as token_program_id, instruction::initialize_mint, state::Mint};#[tokio::main]async fn main() -> Result<()> {let client = RpcClient::new_with_commitment(String::from("http://localhost:8899"),CommitmentConfig::confirmed(),);let latest_blockhash = client.get_latest_blockhash().await?;let transaction = Transaction::new_signed_with_payer(&[create_account(&fee_payer.pubkey(), // Account funding account creation.&mint.pubkey(), // New mint account to create.mint_rent, // Lamports funding the new account rent.Mint::LEN as u64, // Account size in bytes.&token_program_id(), // Program that owns the new account.),initialize_mint(&token_program_id(),&mint.pubkey(), // Mint account to initialize.&fee_payer.pubkey(), // Authority allowed to mint new tokens.Some(&fee_payer.pubkey()), // Authority allowed to freeze token accounts.9, // Decimals to define on the mint account.)?,],Some(&fee_payer.pubkey()),&[&fee_payer, &mint],latest_blockhash,);let transaction_signature = client.send_and_confirm_transaction(&transaction).await?;let mint_account = client.get_account(&mint.pubkey()).await?;let mint_data = Mint::unpack(&mint_account.data)?;println!("Mint Address: {}", mint.pubkey());println!("Mint Account: {:#?}", mint_data);println!("\nTransaction Signature: {}", transaction_signature);Ok(())}
Console
Click to execute the code.
Python
Python
#!/usr/bin/env python3import asyncioimport jsonfrom solana.rpc.async_api import AsyncClientfrom solders.keypair import Keypairfrom solders.message import Messagefrom solders.system_program import create_account, CreateAccountParamsfrom solders.transaction import Transactionfrom spl.token.async_client import AsyncTokenfrom spl.token.instructions import initialize_mint, InitializeMintParamsfrom spl.token.constants import MINT_LEN, TOKEN_PROGRAM_IDDECIMALS = 9async def main():rpc = AsyncClient("http://localhost:8899")async with rpc:create_mint_instructions = [create_account(CreateAccountParams(from_pubkey=fee_payer.pubkey(), # Account funding account creation.to_pubkey=mint.pubkey(), # New mint account to create.lamports=mint_rent, # Lamports funding the new account rent.space=MINT_LEN, # Account size in bytes.owner=TOKEN_PROGRAM_ID, # Program that owns the new account.)),initialize_mint(InitializeMintParams(program_id=TOKEN_PROGRAM_ID, # Token program to invoke.mint=mint.pubkey(), # Mint account to initialize.decimals=DECIMALS, # Decimals to define on the mint account.mint_authority=fee_payer.pubkey(), # Authority allowed to mint new tokens.freeze_authority=fee_payer.pubkey(), # Authority allowed to freeze token accounts.)),]latest_blockhash = await rpc.get_latest_blockhash()transaction = Transaction([fee_payer, mint],Message(create_mint_instructions, fee_payer.pubkey()),latest_blockhash.value.blockhash,)result = await rpc.send_transaction(transaction)token = AsyncToken(rpc, mint.pubkey(), TOKEN_PROGRAM_ID, fee_payer)mint_info = await token.get_mint_info()mint_account = {"mint_authority": None if mint_info.mint_authority is None else str(mint_info.mint_authority),"supply": mint_info.supply,"decimals": mint_info.decimals,"is_initialized": mint_info.is_initialized,"freeze_authority": None if mint_info.freeze_authority is None else str(mint_info.freeze_authority),}print("Mint Address:", mint.pubkey())print("Mint Account:")print(json.dumps(mint_account, indent=2))print("\nTransaction Signature:", result.value)if __name__ == "__main__":asyncio.run(main())
Console
Click to execute the code.
如何添加元数据
mint account 仅存储基本的代币信息(供应量、小数位数、权限)。要为您的代币添加名称、符号和图像等人类可读的元数据,您有两个选择:
Is this page helpful?