Trừu tượng hóa phí

Mọi giao dịch Solana đều yêu cầu SOL để thanh toán phí mạng. Nhưng người dùng đến với ứng dụng thanh toán của bạn mong đợi giao dịch bằng stablecoin—chứ không phải quản lý số dư token thứ hai. Trừu tượng hóa phí loại bỏ rào cản này bằng cách để người khác thanh toán phí.

Hướng dẫn này bao gồm hai cấp độ:

  1. Cách tài trợ phí hoạt động — nguyên lý cơ bản của Solana
  2. Trừu tượng hóa phí quy mô lớn với Kora — dịch vụ trừu tượng hóa phí sẵn sàng cho sản xuất

Cách tài trợ phí hoạt động

Các giao dịch Solana có một người trả phí được chỉ định—tài khoản thanh toán phí mạng. Theo mặc định, đây là người ký đầu tiên. Nhưng bạn có thể chỉ định một tài khoản khác làm người trả phí, cho phép bên thứ ba ("nhà tài trợ") chi trả phí thay mặt người gửi.

Cả người gửi và nhà tài trợ đều phải ký giao dịch:

  • Người gửi ký để ủy quyền chuyển token của họ
  • Nhà tài trợ ký để ủy quyền thanh toán phí mạng

Xem Cách thanh toán hoạt động trên Solana để hiểu các khái niệm thanh toán cốt lõi.

Các bước dưới đây cho thấy luồng cốt lõi. Xem Demo để có mã hoàn chỉnh có thể chạy được.

Tạo tài khoản nhà tài trợ

Tạo một keypair riêng cho nhà tài trợ sẽ thanh toán phí giao dịch. Nhà tài trợ cần SOL cho phí nhưng không cần giữ các token đang được chuyển.

Tạo lệnh chuyển

Tạo lệnh chuyển token với người gửi là người có thẩm quyền. Người gửi sở hữu các token và phải ký chuyển khoản.

Gửi với nhà tài trợ là người trả phí

Tạo client với sponsor được đặt làm người thanh toán phí qua payer(sponsor), sau đó gọi client.sendTransaction. Sponsor ký để thanh toán phí mạng trong khi người gửi ký để ủy quyền chuyển khoản—sendTransaction tự động thu thập mọi người ký được tham chiếu.

Tạo tài khoản nhà tài trợ

Tạo một keypair riêng cho nhà tài trợ sẽ thanh toán phí giao dịch. Nhà tài trợ cần SOL cho phí nhưng không cần giữ các token đang được chuyển.

Tạo lệnh chuyển

Tạo lệnh chuyển token với người gửi là người có thẩm quyền. Người gửi sở hữu các token và phải ký chuyển khoản.

Gửi với nhà tài trợ là người trả phí

Tạo client với sponsor được đặt làm người thanh toán phí qua payer(sponsor), sau đó gọi client.sendTransaction. Sponsor ký để thanh toán phí mạng trong khi người gửi ký để ủy quyền chuyển khoản—sendTransaction tự động thu thập mọi người ký được tham chiếu.

Sponsor Transaction Fee
const sponsor = await generateKeyPairSigner();

Demo

Demo
// Generate keypairs for sender, recipient, and sponsor (fee payer)
const sender = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
const sponsor = await generateKeyPairSigner();
console.log("Sender Address:", sender.address);
console.log("Recipient Address:", recipient.address);
console.log("Sponsor Address (Fee Payer):", sponsor.address);
// Demo Setup: Create client, mint account, token accounts, and fund with initial tokens
const { client, mint } = await demoSetup(sender, recipient, sponsor);
console.log("\nMint Address:", mint.address);
// Derive the Associated Token Accounts addresses (ATAs) for sender and recipient
const [senderAta] = await findAssociatedTokenPda({
mint: mint.address,
owner: sender.address,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});
const [recipientAta] = await findAssociatedTokenPda({
mint: mint.address,
owner: recipient.address,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});
console.log("Sender Token Account:", senderAta.toString());
console.log("Recipient Token Account:", recipientAta.toString());
// =============================================================================
// Sponsored Token Payment Demo
// =============================================================================
// Create instruction to transfer tokens from sender to recipient
// Transferring 250,000 base units = 0.25 tokens (with 6 decimals)
const transferInstruction = getTransferCheckedInstruction({
source: senderAta,
mint: mint.address,
destination: recipientAta,
authority: sender, // Sender signs to authorize the transfer
amount: 250_000n, // 0.25 tokens
decimals: 6
});
// Send transaction with sponsor as fee payer using @solana/kit
// The sponsor (client.payer) pays fees; the sender signs for the transfer
const { context } = await client.sendTransaction([transferInstruction]);
const signature = context.signature;
console.log("\n=== Sponsored Token Payment Complete ===");
console.log("Transaction Signature:", signature.toString());
// Fetch final token account balances from the RPC
const senderBalance = await client.rpc.getTokenAccountBalance(senderAta).send();
const recipientBalance = await client.rpc
.getTokenAccountBalance(recipientAta)
.send();
console.log("\nSender Token Account Balance:", senderBalance.value.uiAmount);
console.log(
"Recipient Token Account Balance:",
recipientBalance.value.uiAmount
);
// Fetch transaction details
const transaction = await client.rpc
.getTransaction(signature, {
encoding: "jsonParsed",
maxSupportedTransactionVersion: 0
})
.send();
const feePayer = transaction?.transaction.message.accountKeys?.[0];
console.log("\nNote: The first account in accountKeys is always the fee payer");
console.log("Fee Payer Address:", feePayer);
// =============================================================================
// Demo Setup Helper Function
// =============================================================================
Console
Click to execute the code.

Khi bạn tạo token account cho người dùng cuối, họ có thể đóng nó và lấy lại SOL đã dùng cho rent. Hãy cân nhắc tính phí người dùng cho việc tạo tài khoản bằng stablecoin, hoặc tính chi phí này vào mô hình kinh tế sản phẩm của bạn.

Fee abstraction quy mô lớn với Kora

Primitive fee payer rất mạnh mẽ, nhưng xây dựng hệ thống gasless production yêu cầu nhiều hơn: quản lý ví nhà tài trợ, xử lý chuyển đổi token (để người dùng có thể "trả" phí bằng USDC), giới hạn tốc độ và kiểm soát bảo mật.

Kora xử lý sự phức tạp này. Đây là một máy chủ JSON-RPC cung cấp tính năng trừu tượng hóa phí, giúp người dùng không bao giờ cần SOL. Bạn có thể tài trợ toàn bộ phí hoặc chấp nhận thanh toán phí bằng bất kỳ token nào.

Triển khai Kora chỉ với một lệnh:

cargo install kora-cli
kora --config path/to/kora.toml rpc start --signers-config path/to/signers.toml

Sau đó trỏ một client Kit tới máy chủ Kora của bạn và gửi giao dịch bằng cùng API đã dùng ở trên:

pnpm add @solana/kora
import { address } from "@solana/kit";
import { createKitKoraClient } from "@solana/kora";
// A Kora-backed Kit client: Kora is the fee payer, and users pay
// fees in the SPL token of your choice instead of SOL
const kora = await createKitKoraClient({
endpoint: "https://your-kora-instance",
rpcUrl: "https://api.mainnet-beta.solana.com",
feeToken: address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), // USDC
feePayerWallet: sender // Signs to authorize the token fee payment
});
// Same instruction, same call—Kora sponsors the network fee
const { context } = await kora.sendTransaction([transferInstruction]);
console.log("Signature:", context.signature);

Tài nguyên Kora

Is this page helpful?

Mục lục

Chỉnh sửa trang