Typescript
Token2022 di Web3.js

Token2022 di Web3.js

Ekstensi Cpi Guard

Ekstensi CpiGuard adalah ekstensi akun Token yang melarang tindakan tertentu di dalam cross-program invocations, melindungi pengguna dari program berbahaya yang mungkin mencoba memanipulasi akun token mereka tanpa persetujuan eksplisit.

Initializing the Token Account

Untuk menginisialisasi ekstensi CpiGuard pada akun Token kita akan membutuhkan fungsi enableCpiGuard().

Berikut cara membuat token dengan ekstensi 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`);

Disabling the CPI Guard

Ketika kita ingin mengaktifkan beberapa perilaku yang diblokir oleh Cpi guard, kita dapat dengan mudah menonaktifkan guard menggunakan instruksi disableCpiGuard seperti ini:

ts
const disableCpiGuardInstruction = createDisableCpiGuardInstruction(
    tokenAccount,
    keypair.publicKey,
    undefined,
    TOKEN_2022_PROGRAM_ID,
);

Dan ketika kita selesai dan ingin menambahkan kembali lapisan keamanan, kita dapat mengaktifkan kembali menggunakan instruksi enableCpiGuard seperti ini:

ts
const enableCpiGuardInstruction = createEnableCpiGuardInstruction(
    tokenAccount,
    keypair.publicKey,
    undefined,
    TOKEN_2022_PROGRAM_ID,
);
Daftar Isi
Lihat Sumber
Blueshift © 2025Commit: 1e001ec