Varsayılan Durum

DefaultAccountStateExtension nasıl etkinleştirilir

DefaultAccountStateExtension, bir mint için oluşturulan tüm yeni token account'ları için varsayılan bir durum belirler. Etkinleştirildiğinde, bu uzantı otomatik olarak her yeni token account'ını dondurulmuş gibi belirli bir durumla başlatır. Bu, token oluşturucularının, açıkça çözülene kadar tüm yeni hesapların varsayılan olarak dondurulması gibi belirli davranışları uygulamasına olanak tanır.

Typescript

import { getCreateAccountInstruction } from "@solana-program/system";
import {
AccountState,
extension,
getInitializeAccountInstruction,
getInitializeDefaultAccountStateInstruction,
getInitializeMintInstruction,
getMintSize,
getTokenSize,
TOKEN_2022_PROGRAM_ADDRESS
} from "@solana-program/token-2022";
import {
airdropFactory,
appendTransactionMessageInstructions,
createSolanaRpc,
createSolanaRpcSubscriptions,
createTransactionMessage,
generateKeyPairSigner,
getSignatureFromTransaction,
lamports,
pipe,
sendAndConfirmTransactionFactory,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
signTransactionMessageWithSigners
} from "@solana/kit";
// Create Connection, local validator in this example
const rpc = createSolanaRpc("http://localhost:8899");
const rpcSubscriptions = createSolanaRpcSubscriptions("ws://localhost:8900");
// Generate the authority for the mint (also acts as fee payer)
const authority = await generateKeyPairSigner();
// Fund authority/fee payer
await airdropFactory({ rpc, rpcSubscriptions })({
recipientAddress: authority.address,
lamports: lamports(5_000_000_000n), // 5 SOL
commitment: "confirmed"
});
// Generate keypair to use as address of mint
const mint = await generateKeyPairSigner();
// default account state extension
const defaultAccountStateExtension = extension("DefaultAccountState", {
state: AccountState.Frozen
});
// Get default mint account size (in bytes), default account state enabled
const space = BigInt(getMintSize([defaultAccountStateExtension]));
// Get minimum balance for rent exemption
const rent = await rpc.getMinimumBalanceForRentExemption(space).send();
// Get latest blockhash to include in transaction
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
// Instruction to create new account for mint (token program)
// Invokes the system program
const createMintAccountInstruction = getCreateAccountInstruction({
payer: authority,
newAccount: mint,
lamports: rent,
space,
programAddress: TOKEN_2022_PROGRAM_ADDRESS
});
// Generate keypair to use as address of token account
const tokenAccount = await generateKeyPairSigner();
// get token account size with extension enabled
const tokenAccountLen = BigInt(getTokenSize([defaultAccountStateExtension]));
// Get minimum balance for rent exemption
const tokenAccountRent = await rpc
.getMinimumBalanceForRentExemption(tokenAccountLen)
.send();
// Instruction to create new account for the token account
// Invokes the system program
const createTokenAccountInstruction = getCreateAccountInstruction({
payer: authority,
newAccount: tokenAccount,
lamports: tokenAccountRent,
space: tokenAccountLen,
programAddress: TOKEN_2022_PROGRAM_ADDRESS
});
// Instruction to initialize the created token account
const initializeTokenAccountInstruction = getInitializeAccountInstruction({
account: tokenAccount.address,
mint: mint.address,
owner: authority.address
});
// Instruction to initialize account with default account state (frozen)
let initializeDefaultAccountState = getInitializeDefaultAccountStateInstruction(
{
mint: mint.address,
state: AccountState.Frozen
}
);
// Instruction to initialize mint account data
// Invokes the token22 program
const initializeMintInstruction = getInitializeMintInstruction({
mint: mint.address,
decimals: 9,
mintAuthority: authority.address,
freezeAuthority: authority.address
});
const instructions = [
createMintAccountInstruction,
initializeDefaultAccountState,
initializeMintInstruction,
createTokenAccountInstruction,
initializeTokenAccountInstruction
];
// Create transaction message
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(authority, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
// Sign transaction message with all required signers
const signedTransaction =
await signTransactionMessageWithSigners(transactionMessage);
// Send and confirm transaction
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(
signedTransaction,
{ commitment: "confirmed", skipPreflight: true }
);
// Get transaction signature
const transactionSignature = getSignatureFromTransaction(signedTransaction);
console.log("Mint Address:", mint.address.toString());
console.log("Frozen token account:", tokenAccount.address.toString());
console.log("Transaction Signature:", transactionSignature);
Console
Click to execute the code.

Rust

use anyhow::Result;
use solana_client::nonblocking::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,
extension::{
ExtensionType, default_account_state::instruction::initialize_default_account_state,
},
instruction::{initialize_account, initialize_mint},
state::{Account, Mint},
};
#[tokio::main]
async fn main() -> Result<()> {
// Create connection to local validator
let client = RpcClient::new_with_commitment(
String::from("http://localhost:8899"),
CommitmentConfig::confirmed(),
);
let latest_blockhash = client.get_latest_blockhash().await?;
// Generate a new keypair for the fee payer
let fee_payer = Keypair::new();
// Airdrop 5 SOL to fee payer
let airdrop_signature = client
.request_airdrop(&fee_payer.pubkey(), 5_000_000_000)
.await?;
client.confirm_transaction(&airdrop_signature).await?;
loop {
let confirmed = client.confirm_transaction(&airdrop_signature).await?;
if confirmed {
break;
}
}
// Generate keypair to use as address of mint
let mint = Keypair::new();
// Get default mint account size (in bytes),
let mint_space =
ExtensionType::try_calculate_account_len::<Mint>(&[ExtensionType::DefaultAccountState])?;
let mint_rent = client
.get_minimum_balance_for_rent_exemption(mint_space)
.await?;
// Instruction to create new account for mint (token22)
let create_mint_account_instruction = create_account(
&fee_payer.pubkey(), // payer
&mint.pubkey(), // new account (mint)
mint_rent, // lamports
mint_space as u64, // space
&TOKEN_2022_PROGRAM_ID, // program id
);
// Instruction to initialize mint account data
let initialize_mint_instruction = initialize_mint(
&TOKEN_2022_PROGRAM_ID, // program id
&mint.pubkey(), // mint
&fee_payer.pubkey(), // mint authority
Some(&fee_payer.pubkey()), // freeze authority
9, // decimals
)?;
// Generate keypair to use as address of token account
let token_account = Keypair::new();
// Get default token account size (in bytes),
let token_account_space = Account::LEN;
let token_account_rent = client
.get_minimum_balance_for_rent_exemption(token_account_space)
.await?;
// Instruction to create new account for token account (token22)
let create_token_account_instruction = create_account(
&fee_payer.pubkey(), // payer
&token_account.pubkey(), // new account (token account)
token_account_rent, // rent
token_account_space as u64, // space
&TOKEN_2022_PROGRAM_ID, // program id
);
// initialize token account
let initialize_token_account = initialize_account(
&TOKEN_2022_PROGRAM_ID, // program_id
&token_account.pubkey(), // token account
&mint.pubkey(), // mint
&fee_payer.pubkey(), // authority
)?;
// initialize default token account state instruction
let initialize_default_account_state_instruction = initialize_default_account_state(
&TOKEN_2022_PROGRAM_ID,
&mint.pubkey(),
&spl_token_2022::state::AccountState::Frozen,
)?;
// Construct transaction with previous instructions
let transaction = Transaction::new_signed_with_payer(
&[
create_mint_account_instruction,
initialize_default_account_state_instruction,
initialize_mint_instruction,
create_token_account_instruction,
initialize_token_account,
],
Some(&fee_payer.pubkey()),
&[&fee_payer, &mint, &token_account],
latest_blockhash,
);
// Send and confirm transaction
let transaction_signature = client.send_and_confirm_transaction(&transaction).await?;
println!("Mint Address: {}", mint.pubkey());
println!(
"token account with default state(frozen) extension: {}",
token_account.pubkey()
);
println!("\nSuccessfully enabled the default sate extension on new token accounts");
println!("Transaction Signature: {}", transaction_signature);
Ok(())
}
Console
Click to execute the code.

Is this page helpful?

İçindekiler

Sayfayı Düzenle