Закриття токен-акаунта

Що робить закриття токен-акаунта?

Закриття token account видаляє обліковий запис і переказує всі його lamport, включно з відшкодовуваним мінімальним балансом для зберігання, на цільовий обліковий запис.

Баланс токенів має бути нульовим, перш ніж можна буде закрити обліковий запис. Заморожений обліковий запис все одно можна закрити, якщо баланс токенів на ньому дорівнює нулю. Виняток становлять token account для Wrapped SOL — їх можна закрити з ненульовим балансом токенів, щоб повернути базовий SOL. Власник облікового запису або уповноважений на закриття підписує інструкцію закриття й вибирає призначення. Обліковий запис, який сплатив за створення associated token account, не отримує відновлений баланс автоматично.

Як закрити токен-акаунт

Закриття токен-акаунта використовує інструкцію CloseAccount Token Program.

Інструкція CloseAccount переносить lamport вихідного акаунта на акаунт призначення, очищує вихідний акаунт і видаляє вихідний акаунт. Token Extension Program застосовує додаткові перевірки закриття для певних розширень, але базовий процес закриття залишається таким самим.

Посилання на джерело

ЕлементОписToken ProgramToken Extension Program
AccountСтан токен-акаунта зберігає баланс, нативний статус та повноваження на закриття, які використовуються під час закриття акаунта.ДжерелоДжерело
CloseAccountІнструкція, яка закриває токен-акаунт і переносить lamport токен-акаунта на акаунт призначення.ДжерелоДжерело
process_close_accountСпільна логіка процесора для закриття токен-акаунта.ДжерелоДжерело

Typescript

Наведені нижче приклади Kit демонструють рекомендований підхід з використанням @solana/kit. Приклади застарілого підходу з використанням @solana/web3.js включені для довідки.

Kit

import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import {
findAssociatedTokenPda,
getCreateAssociatedTokenInstructionAsync,
tokenProgram,
TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
const client = await createClient()
.use(generatedPayer())
.use(
solanaRpc({
rpcUrl: "http://localhost:8899",
rpcSubscriptionsUrl: "ws://localhost:8900"
})
)
.use(rpcAirdrop())
.use(airdropPayer(lamports(1_000_000_000n)))
.use(tokenProgram());
const mint = await generateKeyPairSigner();
const destination = client.payer.address;
const [tokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: client.payer.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const result = await client.token.instructions
.closeAccount({
account: tokenAccount, // Token account to close.
destination, // Account receiving the reclaimed SOL.
owner: client.payer // Owner approving the account closure.
})
.sendTransaction();
const tokenAccountData =
await client.token.accounts.token.fetchMaybe(tokenAccount);
console.log("Mint Address:", mint.address);
console.log("\nToken Account Address:", tokenAccount);
console.log("Token Account:", tokenAccountData);
console.log("\nDestination Address:", destination);
console.log("\nTransaction Signature:", result.context.signature);
Console
Click to execute the code.

Web3.js

import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import {
createAssociatedTokenAccount,
closeAccount,
createMint,
TOKEN_PROGRAM_ID
} from "@solana/spl-token";
const result = await closeAccount(
connection, // Connection to the local validator.
feePayer, // Account paying transaction fees.
associatedTokenAccount, // Token account to close.
destination, // Account receiving the reclaimed SOL.
feePayer, // Owner approving the account closure.
[], // Additional multisig signers.
{
commitment: "confirmed" // Confirmation options for the transaction.
},
TOKEN_PROGRAM_ID // Token program to invoke.
);
const tokenAccountData = await connection.getAccountInfo(
associatedTokenAccount,
"confirmed"
);
console.log("Mint Address:", mintPubkey.toBase58());
console.log(
"\nAssociated Token Account Address:",
associatedTokenAccount.toBase58()
);
console.log("Associated Token Account:", tokenAccountData);
console.log("\nDestination Address:", destination.toBase58());
console.log("\nTransaction Signature:", result);
Console
Click to execute the code.

Rust

Rust
use anyhow::Result;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
program_pack::Pack,
signature::{Keypair, Signer},
transaction::Transaction,
};
use solana_system_interface::instruction::create_account;
use spl_associated_token_account_interface::{
address::get_associated_token_address, instruction::create_associated_token_account,
};
use spl_token_interface::{
id as token_program_id,
instruction::{close_account, initialize_mint},
state::{Account, Mint},
};
#[tokio::main]
async fn main() -> Result<()> {
let client = RpcClient::new_with_commitment(
String::from("http://localhost:8899"),
CommitmentConfig::confirmed(),
);
let associated_token_address = get_associated_token_address(&fee_payer.pubkey(), &mint.pubkey());
let destination = fee_payer.pubkey();
let transaction = Transaction::new_signed_with_payer(
&[
close_account(
&token_program_id(), // Token program to invoke.
&associated_token_address, // Token account to close.
&destination, // Account receiving the reclaimed SOL.
&fee_payer.pubkey(), // Owner approving the account closure.
&[], // Additional multisig signers.
)?,
],
Some(&fee_payer.pubkey()),
&[&fee_payer],
latest_blockhash,
);
let transaction_signature = client.send_and_confirm_transaction(&transaction).await?;
let token_data = match client.get_account(&associated_token_address).await {
Ok(account) => Some(Account::unpack(&account.data)?),
Err(_) => None,
};
println!("Mint Address: {}", mint.pubkey());
println!(
"\nAssociated Token Account Address: {}",
associated_token_address
);
println!("Associated Token Account: {:#?}", token_data);
println!("\nDestination Address: {}", destination);
println!("\nTransaction Signature: {}", transaction_signature);
Ok(())
}
Console
Click to execute the code.

Python

Python
#!/usr/bin/env python3
import asyncio
import json
from solana.rpc.async_api import AsyncClient
from solders.keypair import Keypair
from solders.message import Message
from solders.system_program import create_account, CreateAccountParams
from solders.transaction import Transaction
from spl.token.async_client import AsyncToken
from spl.token.instructions import (
close_account,
CloseAccountParams,
create_associated_token_account,
get_associated_token_address,
initialize_mint,
InitializeMintParams,
)
from spl.token.constants import MINT_LEN, TOKEN_PROGRAM_ID
async def main():
rpc = AsyncClient("http://localhost:8899")
async with rpc:
close_account_instruction = close_account(
CloseAccountParams(
program_id=TOKEN_PROGRAM_ID, # Token program to invoke.
account=token_account_address, # Token account to close.
dest=fee_payer.pubkey(), # Account receiving the reclaimed lamports.
owner=fee_payer.pubkey(), # Account allowed to close the token account.
)
)
latest_blockhash = await rpc.get_latest_blockhash()
transaction = Transaction(
[fee_payer],
Message([close_account_instruction], fee_payer.pubkey()),
latest_blockhash.value.blockhash,
)
result = await rpc.send_transaction(transaction)
closed_token_account = (await rpc.get_account_info(token_account_address)).value
print("Mint Address:", mint.pubkey())
print("\nToken Account Address:", token_account_address)
print("Token Account:")
print(json.dumps(closed_token_account, indent=2))
print("\nTransaction Signature:", result.value)
if __name__ == "__main__":
asyncio.run(main())
Console
Click to execute the code.

Is this page helpful?

Зміст

Редагувати сторінку