Розширення з нарахуванням відсотків
Розширення InterestBearing
є розширенням облікового запису Mint
, яке дозволяє користувачам застосовувати відсоткову ставку до своїх токенів і отримувати оновлену загальну суму, включаючи відсотки, у будь-який момент.
Initializing the Mint Account
Щоб ініціалізувати розширення InterestBearing
на обліковому записі Mint
, нам знадобиться функція interestBearingMint()
.
Ось як створити емісію з розширенням нарахування відсотків:
import {
Keypair,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import {
createInitializeMintInstruction,
createInitializeInterestBearingMintInstruction,
getMintLen,
ExtensionType,
TOKEN_2022_PROGRAM_ID,
} from '@solana/spl-token';
const mint = Keypair.generate();
// Calculate the size needed for a Mint account with Interest Bearing extension
const mintLen = getMintLen([ExtensionType.InterestBearingConfig]);
// Calculate minimum lamports required for rent exemption
const lamports = await connection.getMinimumBalanceForRentExemption(mintLen);
// Create the account with the correct size and owner
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: keypair.publicKey,
newAccountPubkey: mint.publicKey,
space: mintLen,
lamports,
programId: TOKEN_2022_PROGRAM_ID,
});
// Initialize the Interest Bearing extension
const initializeMintInterestBearing = createInitializeInterestBearingMintInstruction(
mint.publicKey,
keypair.publicKey,
500,
TOKEN_2022_PROGRAM_ID,
);
// Initialize the mint itself
const initializeMintInstruction = createInitializeMintInstruction(
mint.publicKey,
6,
keypair.publicKey,
null,
TOKEN_2022_PROGRAM_ID,
);
// Combine all instructions in the correct order
const transaction = new Transaction().add(
createAccountInstruction,
initializeMintNonTransferable,
initializeMintInstruction,
);
const signature = await sendAndConfirmTransaction(connection, transaction, [keypair, mint]);
console.log(`Mint created! Check out your TX here: https://explorer.solana.com/tx/${signature}?cluster=devnet`);
Calculating the Interest
Розширення InterestBearing
не генерує нові токени; відображена сума просто включає накопичені відсотки через функцію amount_to_ui_amount
, що робить зміну суто естетичною.
Отже, після unpacking
облікового запису Token
, для якого ми хочемо обчислити відсотки, легко отримати всю інформацію, необхідну для розрахунку суми відсотків.
На щастя, нам навіть не потрібно це робити, оскільки ми можемо використовувати функцію amountToUiAmount
таким чином:
const tokenInfo = await getAccount(
connection,
tokenAccount,
undefined,
TOKEN_2022_PROGRAM_ID,
);
console.log("Token Amount: ", tokenInfo.amount);
const uiAmount = await amountToUiAmount(
connection,
keypair,
mint.publicKey,
tokenInfo.amount,
TOKEN_2022_PROGRAM_ID,
);
console.log("UI Amount: ", uiAmount);
Updating the Interest Bearing Extension
З розширенням InterestBearing
можливо змінювати відсотки, що нараховуються на токен-рахунок, завдяки структурі його даних:
pub struct InterestBearing {
pub rate_authority: Pubkey,
pub initialization_timestamp: i64,
pub pre_update_average_rate: u16,
pub last_update_timestamp: i64,
pub current_rate: u16,
}
Для цього ми можемо використовувати функцію updateRateInterestBearingMint
таким чином:
const updateRateInstruction = await createUpdateRateInterestBearingMintInstruction(
mint.publicKey,
newRateAuthority.publicKey,
1000, // updated rate
undefined,
TOKEN_2022_PROGRAM_ID,
);
І якщо ми хочемо, ми можемо змінити повноваження щодо встановлення відсотків, використовуючи функцію setAuthority
і передаючи правильний AuthorityType
таким чином:
const setAuthorityInstruction = await createSetAuthorityInstruction(
mint.publicKey,
keypair.publicKey,
AuthorityType.InterestRate,
newRateAuthority.publicKey,
[],
TOKEN_2022_PROGRAM_ID,
);