الرموز المميزة ذات الفائدة

كيفية تمكين InterestBearingExtension

يسمح لك InterestBearingMintExtension بتعيين معدل فائدة مباشرة على حساب mint account. تتراكم الفائدة باستمرار بناءً على الطابع الزمني للشبكة، ولكن رصيد الرمز المميز الفعلي المخزن في كل token account يظل دون تغيير. القيمة الإجمالية (رصيد الرمز المميز بالإضافة إلى الفائدة المتراكمة) هي مجرد حساب. لا يتم إنشاء رموز مميزة جديدة مع هذا الامتداد.

تايب سكريبت

import { getCreateAccountInstruction } from "@solana-program/system";
import {
extension,
getInitializeAccountInstruction,
getInitializeMintInstruction,
getInitializeInterestBearingMintInstruction,
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();
// Define the interest bearing config extension
const interestRate = {
rate: 500 // 5.00% annualized interest (in basis points)
};
// config for interest bearing extension
const interestBearingMintExtension = extension("InterestBearingConfig", {
rateAuthority: authority.address,
initializationTimestamp: BigInt(Math.floor(new Date().getTime() / 1000)),
lastUpdateTimestamp: BigInt(Math.floor(new Date().getTime() / 1000)),
preUpdateAverageRate: interestRate.rate,
currentRate: interestRate.rate
});
// Get mint account size with interest bearing extension
const space = BigInt(getMintSize([interestBearingMintExtension]));
// 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
});
// Instruction to initialize interest bearing config extension
const initializeInterestBearingConfigInstruction =
getInitializeInterestBearingMintInstruction({
mint: mint.address,
rateAuthority: authority.address,
rate: interestRate.rate // in basis points
});
// Instruction to initialize mint account data
// Invokes the token22 program
const initializeMintInstruction = getInitializeMintInstruction({
mint: mint.address,
decimals: 6,
mintAuthority: authority.address,
freezeAuthority: authority.address
});
// Generate keypair to use as address of token account
const tokenAccount = await generateKeyPairSigner();
// get token account size (with extension awareness)
const tokenAccountLen = BigInt(getTokenSize());
// 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
});
console.log("token account", tokenAccount.address); // ! debug
const instructions = [
createMintAccountInstruction,
initializeInterestBearingConfigInstruction,
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 with Interest Bearing Extension:",
mint.address.toString()
);
console.log("Token Account:", tokenAccount.address.toString());
console.log("Interest Rate: 5% APY (500 basis points)");
console.log("Rate Authority:", authority.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_commitment_config::CommitmentConfig;
use solana_sdk::{
signature::{Keypair, Signer},
transaction::Transaction,
};
use solana_system_interface::instruction::create_account;
use spl_token_2022_interface::{
extension::{
interest_bearing_mint::{
instruction::initialize as initialize_interest_bearing_instruction,
InterestBearingConfig,
},
BaseStateWithExtensions, ExtensionType, StateWithExtensions,
},
instruction::initialize_mint,
state::Mint,
ID as TOKEN_2022_PROGRAM_ID,
};
#[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?;
loop {
let confirmed = client.confirm_transaction(&airdrop_signature).await?;
if confirmed {
break;
}
}
// Generate keypair to use as address of mint
let mint = Keypair::new();
// Calculate mint account size with interest bearing extension
let mint_space =
ExtensionType::try_calculate_account_len::<Mint>(&[ExtensionType::InterestBearingConfig])?;
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 interest bearing extension (5% APY)
let initialize_interest_bearing_instruction = initialize_interest_bearing_instruction(
&TOKEN_2022_PROGRAM_ID,
&mint.pubkey(),
Some(fee_payer.pubkey()), // rate authority
500, // interest rate (basis points) = 5%
)?;
// 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
)?;
// Construct transaction with interest bearing mint extension
let transaction = Transaction::new_signed_with_payer(
&[
create_mint_account_instruction,
initialize_interest_bearing_instruction,
initialize_mint_instruction,
],
Some(&fee_payer.pubkey()),
&[&fee_payer, &mint],
latest_blockhash,
);
// Send and confirm transaction
client.send_and_confirm_transaction(&transaction).await?;
println!("Mint Address: {}", mint.pubkey());
// Fetch mint account
let mint_account = client.get_account(&mint.pubkey()).await?;
// Deserialize the mint account with extensions
let mint_state = StateWithExtensions::<Mint>::unpack(&mint_account.data)?;
// Get all extension types enabled on this mint
let mint_extension_types = mint_state.get_extension_types()?;
println!("\nMint extensions enabled: {:?}", mint_extension_types);
// Deserialize the InterestBearingConfig extension data
let interest_bearing_config = mint_state.get_extension::<InterestBearingConfig>()?;
println!("\n{:#?}", interest_bearing_config);
Ok(())
}
Console
Click to execute the code.

Is this page helpful?

جدول المحتويات

تعديل الصفحة

تدار بواسطة

© 2025 مؤسسة سولانا.
جميع الحقوق محفوظة.