Luo Token Mint

Mikä on Mint Account?

Mint account on tilityypppi Solanan Token Programs -ohjelmissa, joka edustaa yksilöllisesti tokenia verkossa ja tallentaa globaalia metatietoa tokenista.

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 initialized
pub is_initialized: bool,
/// Optional authority to freeze token accounts.
pub freeze_authority: COption<Pubkey>,
}

Huomaa, että sekä Token Program että Token Extension Program jakavat saman perusimplementaation Mint-tilille.

Jokainen token Solanassa on olemassa mint account -tilinä, jossa mint accountin osoite toimii sen yksilöllisenä tunnisteena verkossa.

Esimerkiksi USD Coin (USDC) -digitaalidollarilla Solanassa on mint-osoite EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v. Tämä mint-osoite toimii USD Coinin yksilöllisenä tunnisteena koko Solana-ekosysteemissä. Voit tarkastella tämän mint accountin tietoja Solana Explorerissa.

Miten luoda Mint Account

Luodaksesi Mint Accountin, kutsu InitializeMint -ohjetta. Tämän ohjeen toteutukset löytyvät täältä.

Mint accountin luomiseen tarvittava transaktio vaatii kaksi ohjetta:

  1. Kutsu System Programia luomaan ja allokoimaan tilaa mint accountille ja siirtämään omistajuus Token Programille.
  2. Kutsu Token Programia alustamaan mint accountin data.

Typescript

import {
airdropFactory,
appendTransactionMessageInstructions,
createSolanaRpc,
createSolanaRpcSubscriptions,
createTransactionMessage,
generateKeyPairSigner,
getSignatureFromTransaction,
lamports,
pipe,
sendAndConfirmTransactionFactory,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
signTransactionMessageWithSigners
} from "@solana/kit";
import { getCreateAccountInstruction } from "@solana-program/system";
import {
getInitializeMintInstruction,
getMintSize,
TOKEN_2022_PROGRAM_ADDRESS
} from "@solana-program/token-2022";
// Create Connection, local validator in this example
const rpc = createSolanaRpc("http://127.0.0.1:8899");
const rpcSubscriptions = createSolanaRpcSubscriptions("ws://localhost:8900");
// Generate keypairs for fee payer
const feePayer = await generateKeyPairSigner();
// Fund fee payer
await airdropFactory({ rpc, rpcSubscriptions })({
recipientAddress: feePayer.address,
lamports: lamports(1_000_000_000n),
commitment: "confirmed"
});
// Generate keypair to use as address of mint
const mint = await generateKeyPairSigner();
// Get default mint account size (in bytes), no extensions enabled
const space = BigInt(getMintSize());
// Get minimum balance for rent exemption
const rent = await rpc.getMinimumBalanceForRentExemption(space).send();
// Instruction to create new account for mint (token 2022 program)
// Invokes the system program
const createAccountInstruction = getCreateAccountInstruction({
payer: feePayer,
newAccount: mint,
lamports: rent,
space,
programAddress: TOKEN_2022_PROGRAM_ADDRESS
});
// Instruction to initialize mint account data
// Invokes the token 2022 program
const initializeMintInstruction = getInitializeMintInstruction({
mint: mint.address,
decimals: 9,
mintAuthority: feePayer.address
});
const instructions = [createAccountInstruction, initializeMintInstruction];
// Get latest blockhash to include in transaction
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
// Create transaction message
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }), // Create transaction message
(tx) => setTransactionMessageFeePayerSigner(feePayer, tx), // Set fee payer
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), // Set transaction blockhash
(tx) => appendTransactionMessageInstructions(instructions, tx) // Append instructions
);
// Sign transaction message with required signers (fee payer and mint keypair)
const signedTransaction =
await signTransactionMessageWithSigners(transactionMessage);
// Send and confirm transaction
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(
signedTransaction,
{ commitment: "confirmed" }
);
// Get transaction signature
const transactionSignature = getSignatureFromTransaction(signedTransaction);
console.log("Mint Address:", mint.address);
console.log("Transaction Signature:", transactionSignature);
Click to execute the code.

Rust

use anyhow::Result;
use solana_client::rpc_client::RpcClient;
use solana_sdk::{
commitment_config::CommitmentConfig,
program_pack::Pack,
signature::{Keypair, Signer},
system_instruction::create_account,
transaction::Transaction,
};
use spl_token_2022::{id as token_2022_program_id, instruction::initialize_mint, state::Mint};
fn main() -> Result<()> {
// Create connection to local validator
let client = RpcClient::new_with_commitment(
String::from("http://127.0.0.1:8899"),
CommitmentConfig::confirmed(),
);
let recent_blockhash = client.get_latest_blockhash()?;
// Generate a new keypair for the fee payer
let fee_payer = Keypair::new();
// Airdrop 1 SOL to fee payer
let airdrop_signature = client.request_airdrop(&fee_payer.pubkey(), 1_000_000_000)?;
client.confirm_transaction(&airdrop_signature)?;
loop {
let confirmed = client.confirm_transaction(&airdrop_signature)?;
if confirmed {
break;
}
}
// Generate keypair to use as address of mint
let mint = Keypair::new();
let mint_space = Mint::LEN;
let rent = client.get_minimum_balance_for_rent_exemption(mint_space)?;
// Create account instruction for mint
let create_account_instruction = create_account(
&fee_payer.pubkey(), // payer
&mint.pubkey(), // mint address
rent, // rent
mint_space as u64, // space
&token_2022_program_id(), // program id
);
// Initialize mint account data
let initialize_mint_instruction = initialize_mint(
&token_2022_program_id(), // program id
&mint.pubkey(), // mint address
&fee_payer.pubkey(), // mint authority
Some(&fee_payer.pubkey()),// freeze authority
9, // decimals
)?;
// Create transaction and add instructions
let transaction = Transaction::new_signed_with_payer(
&[create_account_instruction, initialize_mint_instruction],
Some(&fee_payer.pubkey()),
&[&fee_payer, &mint],
recent_blockhash,
);
// Send and confirm transaction
let transaction_signature = client.send_and_confirm_transaction(&transaction)?;
println!("Mint Address: {}", mint.pubkey());
println!("Transaction Signature: {}", transaction_signature);
Ok(())
}
Click to execute the code.

Is this page helpful?

Sisällysluettelo

Muokkaa sivua