Розширення Cpi Guard
Розширення CpiGuard
є розширенням облікового запису Token
, яке забороняє певні дії всередині міжпрограмних викликів, захищаючи користувачів від зловмисних програм, які можуть спробувати маніпулювати їхніми токен-рахунками без явної згоди.
Ініціалізація токен-рахунку
Щоб ініціалізувати розширення CpiGuard
на обліковому записі Token
, нам знадобиться функція enableCpiGuard()
.
Ось як створити токен з розширенням Cpi Guard:
ts
import {
Keypair,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import {
createInitializeAccountInstruction,
createEnableCpiGuardInstruction,
getAccountLen,
ExtensionType,
TOKEN_2022_PROGRAM_ID,
} from '@solana/spl-token';
const tokenAccount = Keypair.generate();
// Calculate the size needed for a Token account with Cpi Guard extension
const accountLen = getAccountLen([ExtensionType.CpiGuard]);
// Calculate minimum lamports required for rent exemption
const lamports = await connection.getMinimumBalanceForRentExemption(accountLen);
// Create the account with the correct size and owner
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: keypair.publicKey,
newAccountPubkey: tokenAccount.publicKey,
space: accountLen,
lamports,
programId: TOKEN_2022_PROGRAM_ID,
});
// Initialize the Cpi Guard extension
const enableCpiGuardInstruction = createEnableCpiGuardInstruction(
tokenAccount.publicKey,
keypair.publicKey,
undefined,
TOKEN_2022_PROGRAM_ID,
);
// Initialize the Token account itself
const initializeAccountInstruction = createInitializeAccountInstruction(
tokenAccount.publicKey,
mint.publicKey,
keypair.publicKey,
TOKEN_2022_PROGRAM_ID,
);
const transaction = new Transaction().add(
createAccountInstruction,
initializeAccountInstruction,
enableCpiGuardInstruction
);
const signature = await sendAndConfirmTransaction(connection, transaction, [keypair, tokenAccount], {skipPreflight: false});
console.log(`Token accounts created! Check out your TX here: https://explorer.solana.com/tx/${signature}?cluster=devnet`);
Вимкнення CPI Guard
Коли ми хочемо дозволити деякі з поведінок, які блокуються Cpi Guard, ми можемо легко вимкнути захист за допомогою інструкції disableCpiGuard
таким чином:
ts
const disableCpiGuardInstruction = createDisableCpiGuardInstruction(
tokenAccount,
keypair.publicKey,
undefined,
TOKEN_2022_PROGRAM_ID,
);
А коли ми закінчили і хочемо повернути шар безпеки, ми можемо повторно активувати його за допомогою інструкції enableCpiGuard
таким чином:
ts
const enableCpiGuardInstruction = createEnableCpiGuardInstruction(
tokenAccount,
keypair.publicKey,
undefined,
TOKEN_2022_PROGRAM_ID,
);