Tạo một Token Mint
Chương trình ZK ElGamal tạm thời bị vô hiệu hóa trên mainnet và devnet khi đang được kiểm tra bảo mật. Điều này có nghĩa là tiện ích mở rộng confidential transfers hiện không khả dụng. Mặc dù các khái niệm vẫn hợp lệ, nhưng các ví dụ mã sẽ không chạy được.
Cách tạo một mint với tiện ích mở rộng Confidential Transfer
Tiện ích mở rộng Confidential Transfer cho phép chuyển token riêng tư bằng cách thêm trạng thái bổ sung vào tài khoản mint. Phần này giải thích cách tạo một token mint với tiện ích mở rộng này được kích hoạt.
Sơ đồ sau đây cho thấy các bước liên quan đến việc tạo một mint với tiện ích mở rộng Confidential Transfer:
Trạng thái Confidential Transfer Mint
Tiện ích mở rộng này thêm trạng thái ConfidentialTransferMint vào tài khoản mint:
#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]pub struct ConfidentialTransferMint {/// Authority to modify the `ConfidentialTransferMint` configuration and to/// approve new accounts (if `auto_approve_new_accounts` is true)////// The legacy Token Multisig account is not supported as the authoritypub authority: OptionalNonZeroPubkey,/// Indicate if newly configured accounts must be approved by the/// `authority` before they may be used by the user.////// * If `true`, no approval is required and new accounts may be used/// immediately/// * If `false`, the authority must approve newly configured accounts (see/// `ConfidentialTransferInstruction::ConfigureAccount`)pub auto_approve_new_accounts: PodBool,/// Authority to decode any transfer amount in a confidential transfer.pub auditor_elgamal_pubkey: OptionalNonZeroElGamalPubkey,}
ConfidentialTransferMint
chứa ba trường cấu hình:
-
authority: Tài khoản có quyền thay đổi cài đặt chuyển khoản bảo mật cho mint và phê duyệt các tài khoản bảo mật mới nếu tự động phê duyệt bị vô hiệu hóa.
-
auto_approve_new_accounts: Khi được đặt thành true, người dùng có thể tạo tài khoản token với chuyển khoản bảo mật được kích hoạt theo mặc định. Khi false, authority phải phê duyệt từng tài khoản token mới trước khi nó có thể được sử dụng cho chuyển khoản bảo mật.
-
auditor_elgamal_pubkey: Một kiểm toán viên tùy chọn có thể giải mã số tiền chuyển khoản trong các giao dịch bảo mật, cung cấp cơ chế tuân thủ trong khi vẫn duy trì quyền riêng tư đối với công chúng.
Các lệnh cần thiết
Tạo một mint với Confidential Transfer được kích hoạt yêu cầu ba lệnh trong một giao dịch duy nhất:
-
Tạo tài khoản Mint: Gọi lệnh
CreateAccount
của System Program để tạo tài khoản mint. -
Khởi tạo Tiện ích mở rộng Chuyển khoản Bảo mật: Gọi hướng dẫn ConfidentialTransferInstruction::InitializeMint của Token Extension Program để cấu hình trạng thái
ConfidentialTransferMint
cho mint. -
Khởi tạo Mint: Gọi hướng dẫn
Instruction::InitializeMint
của Token Extension Program để khởi tạo trạng thái mint tiêu chuẩn.
Mặc dù bạn có thể viết các hướng dẫn này thủ công, crate spl_token_client
cung
cấp phương thức create_mint
để xây dựng và gửi một giao dịch với cả ba hướng
dẫn trong một lần gọi hàm duy nhất, như được minh họa trong ví dụ dưới đây.
Mã ví dụ
Đoạn mã sau đây minh họa cách tạo một mint với tiện ích mở rộng Chuyển khoản Bảo mật.
Để chạy ví dụ, hãy khởi động một validator cục bộ với Token Extension Program được sao chép từ mainnet bằng lệnh sau. Bạn phải cài đặt Solana CLI để khởi động validator cục bộ.
$solana-test-validator --clone-upgradeable-program TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb --url https://api.mainnet-beta.solana.com -r
Tại thời điểm viết bài, Chuyển khoản Bảo mật chưa được kích hoạt trên validator cục bộ mặc định. Bạn phải sao chép Token Extension Program từ mainnet để chạy mã ví dụ.
use anyhow::{Context, Result};use solana_client::nonblocking::rpc_client::RpcClient;use solana_sdk::{commitment_config::CommitmentConfig,signature::{Keypair, Signer},};use spl_token_client::{client::{ProgramRpcClient, ProgramRpcClientSendTransaction},spl_token_2022::id as token_2022_program_id,token::{ExtensionInitializationParams, Token},};use std::sync::Arc;#[tokio::main]async fn main() -> Result<()> {// Create connection to local test validatorlet rpc_client = RpcClient::new_with_commitment(String::from("http://localhost:8899"),CommitmentConfig::confirmed(),);// Load the default Solana CLI keypair to use as the fee payer// This will be the wallet paying for the transaction fees// Use Arc to prevent multiple clones of the keypairlet payer = Arc::new(load_keypair()?);println!("Using payer: {}", payer.pubkey());// Generate a new keypair to use as the address of the token mintlet mint = Keypair::new();println!("Mint keypair generated: {}", mint.pubkey());// Set up program client for Token clientlet program_client =ProgramRpcClient::new(Arc::new(rpc_client), ProgramRpcClientSendTransaction);// Number of decimals for the mintlet decimals = 9;// Create a token client for the Token-2022 program// This provides high-level methods for token operationslet token = Token::new(Arc::new(program_client),&token_2022_program_id(), // Use the Token-2022 program (newer version with extensions)&mint.pubkey(), // Address of the new token mintSome(decimals), // Number of decimal placespayer.clone(), // Fee payer for transactions (cloning Arc, not keypair));// Create extension initialization parameters// The ConfidentialTransferMint extension enables confidential (private) transfers of tokenslet extension_initialization_params =vec![ExtensionInitializationParams::ConfidentialTransferMint {authority: Some(payer.pubkey()), // Authority that can modify confidential transfer settingsauto_approve_new_accounts: true, // Automatically approve new confidential accountsauditor_elgamal_pubkey: None, // Optional auditor ElGamal public key}];// Create and initialize the mint with the ConfidentialTransferMint extension// This sends a transaction to create the new token mintlet transaction_signature = token.create_mint(&payer.pubkey(), // Mint authority - can mint new tokensSome(&payer.pubkey()), // Freeze authority - can freeze token accountsextension_initialization_params, // Add the ConfidentialTransferMint extension&[&mint], // Mint keypair needed as signer).await?;// Print results for user verificationprintln!("Mint Address: {}", mint.pubkey());println!("Transaction Signature: {}", transaction_signature);Ok(())}// Load the keypair from the default Solana CLI keypair path (~/.config/solana/id.json)// This enables using the same wallet as the Solana CLI toolsfn load_keypair() -> Result<Keypair> {// Get the default keypair pathlet keypair_path = dirs::home_dir().context("Could not find home directory")?.join(".config/solana/id.json");// Read the keypair file directly into bytes using serde_json// The keypair file is a JSON array of byteslet file = std::fs::File::open(&keypair_path)?;let keypair_bytes: Vec<u8> = serde_json::from_reader(file)?;// Create keypair from the loaded bytes// This converts the byte array into a keypairlet keypair = Keypair::from_bytes(&keypair_bytes)?;Ok(keypair)}
Is this page helpful?