Mint Account Là Gì
Một mint account định nghĩa và xác định duy nhất một token trên Solana, đồng thời lưu trữ trạng thái chung áp dụng cho tất cả các token account của mint đó.
Token Program định nghĩa kiểu tài khoản Mint như sau:
/// 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>,}
Mỗi token có một mint account, và địa chỉ mint là định danh duy nhất của token trên các ví, ứng dụng và trình khám phá.
Ví dụ, USD Coin (USDC) có địa chỉ mint là
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v. Địa chỉ mint xác định duy nhất
USDC trong toàn bộ hệ sinh thái Solana. Bạn có thể xem mint này trên
Solana Explorer.
Cách Tạo Mint Account
Việc tạo mint yêu cầu hai lệnh:
- Lệnh
CreateAccountcủa System Program tạo một tài khoản mới được miễn rent và gán Token Program làm chương trình sở hữu của tài khoản mới. - Lệnh
InitializeMinthoặcInitializeMint2của Token Program khởi tạo tài khoản mới làm mint.
Bao gồm lệnh CreateAccount và lệnh khởi tạo mint trong cùng một giao dịch.
Trong quá trình khởi tạo mint, Token Program kiểm tra xem mint account chưa được
khởi tạo và đã được miễn rent. Token Program sau đó ghi quyền mint, quyền đóng
băng, số thập phân và cờ is_initialized vào dữ liệu của mint account.
Tham Chiếu Mã Nguồn
| Mục | Mô tả | Token Program | Token Extensions Program |
|---|---|---|---|
Mint | Trạng thái mint cơ bản được lưu trữ trong mọi mint account. | Nguồn | Nguồn |
InitializeMint | Lệnh khởi tạo mint yêu cầu tài khoản rent sysvar trong danh sách tài khoản của nó. | Nguồn | Nguồn |
InitializeMint2 | Lệnh khởi tạo mint không yêu cầu tài khoản rent sysvar trong danh sách tài khoản của nó. | Nguồn | Nguồn |
_process_initialize_mint | Logic xử lý chung cho khởi tạo mint. | Nguồn | Nguồn |
process_initialize_mint | Bộ xử lý công khai cho InitializeMint. | Nguồn | Nguồn |
process_initialize_mint2 | Bộ xử lý công khai cho InitializeMint2. | Nguồn | Nguồn |
Typescript
Các ví dụ dưới đây cho thấy cách tiếp cận được khuyến nghị sử dụng Kit. Các ví
dụ cũ sử dụng @solana/kit được bao gồm để tham khảo.
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);
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);
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(())}
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())
Cách Thêm Metadata
Mint account chỉ lưu trữ thông tin token cơ bản (nguồn cung, số thập phân, quyền hạn). Để thêm metadata dễ đọc như tên, ký hiệu và hình ảnh cho token của bạn, bạn có hai tùy chọn:
Metaplex Token Metadata
Thêm metadata bằng cách sử dụng Metaplex Token Metadata Program. Hoạt động với cả Token Program gốc và Token-2022.
Token Extensions Metadata
Sử dụng tiện ích mở rộng metadata tích hợp với Token-2022. Tiện ích mở rộng metadata chỉ khả dụng cho các mint account được tạo bằng Token-2022. Để thêm metadata vào các mint account được tạo bằng Token Program gốc, hãy sử dụng Metaplex Token Metadata Program.
Is this page helpful?