In short
By default, the transaction’s fee payer needs a little SOL to pay its fee. A fee-payer service such as Kora lets your app pay instead, so customers only ever hold dollars.You’ve used this in: Payments Step 4 Pay-per-call Step 4
How it works
Every transactionTransactionsA transaction is a signed request to change the shared ledger. It either fully happens or doesn't happen at all, and once confirmed anyone can look it up.Learn more (Transactions: A transaction is a signed request to change the shared ledger. It either fully happens or doesn’t happen at all, and once confirmed anyone can look it up.) names a fee payer: the account whose SOL pays the network feeFeesEvery transaction pays a small flat network fee, currently a fraction of a cent, whatever the amount. The transaction's fee payer pays, and that can be your app rather than your customer.Learn more (Fees: Every transaction pays a small flat network fee, currently a fraction of a cent, whatever the amount. The transaction’s fee payer pays, and that can be your app rather than your customer.). The fee payer is always the first signer. It does not have to be the person moving the money. To sponsor a transaction, your app sets its own account as the fee payer. Both parties then sign the same transaction:- the sender signs to authorize moving their tokens;
- the sponsor signs to authorize paying the network fee.
Example
The sender transfers 0.5 tokens to the recipient. A third keypair, the fee payer, pays the fee. The output is from a local Surfpool network.- Kit
- Web3.js v3
- Web3.js v3 Helper
- Python
- Go
- Web3.js (legacy)
- Web3.js (legacy) Helper
Kit
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { rpcAirdrop, solanaRpc } from "@solana/kit-plugin-rpc";
import { airdropPayer, payer } from "@solana/kit-plugin-signer";
import {
fetchToken,
findAssociatedTokenPda,
tokenProgram,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
// Generate keypairs for fee payer, sender, recipient, and mint
const feePayer = await generateKeyPairSigner();
const sender = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
const mint = await generateKeyPairSigner();
console.log("Fee Payer Address:", feePayer.address);
console.log("Sender Address:", sender.address);
console.log("Recipient Address:", recipient.address);
console.log("Mint Address:", mint.address);
// Build a Kit client: fee payer (funded with 1 SOL), local RPC, and the token program plugin
const client = await createClient()
.use(payer(feePayer))
.use(
solanaRpc({
rpcUrl: "http://localhost:8899",
rpcSubscriptionsUrl: "ws://localhost:8900",
}),
)
.use(rpcAirdrop())
.use(airdropPayer(lamports(1_000_000_000n)))
.use(tokenProgram());
// Create the mint and mint 1.00 tokens to sender's ATA (the plugin auto-creates the ATA)
const createMintIx = await client.token.instructions.createMint({
newMint: mint,
decimals: 2,
mintAuthority: sender.address,
});
const mintToSenderIx = await client.token.instructions.mintToATA({
mint: mint.address,
owner: sender.address,
mintAuthority: sender,
amount: 100n,
decimals: 2,
});
const setup = await client.sendTransaction([createMintIx, mintToSenderIx]);
console.log("Transaction Signature:", setup.context.signature);
console.log("Successfully minted 1.0 tokens");
// Transfer 0.50 tokens from sender to recipient — fee paid by feePayer
const transferToRecipientIx = await client.token.instructions.transferToATA({
mint: mint.address,
authority: sender,
recipient: recipient.address,
amount: 50n,
decimals: 2,
});
const transfer = await client.sendTransaction([transferToRecipientIx]);
console.log("Transaction Signature:", transfer.context.signature);
console.log("Successfully transferred 0.5 tokens");
// Verify final balances
const [senderAta] = await findAssociatedTokenPda({
mint: mint.address,
owner: sender.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const [recipientAta] = await findAssociatedTokenPda({
mint: mint.address,
owner: recipient.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const senderTokenAccount = await fetchToken(client.rpc, senderAta, {
commitment: "confirmed",
});
const recipientTokenAccount = await fetchToken(client.rpc, recipientAta, {
commitment: "confirmed",
});
console.log("=== Final Balances ===");
console.log(
"Sender balance:",
Number(senderTokenAccount.data.amount) / 100,
"tokens",
);
console.log(
"Recipient balance:",
Number(recipientTokenAccount.data.amount) / 100,
"tokens",
);
Output from a local Surfpool network
Output
Fee Payer Address: FG6x4E4ZJu9tag9oRqnqF8mZFbRAnqT27iY53ke2BoG8
Sender Address: 6m2yWABs8Vckigww1zG11aNLJ7m1LPzH6rorLiSJBmCV
Recipient Address: 9G7Kr8nNcSbHGJfgwApjP74dN7kL9pw4KxNbhjWfeR35
Mint Address: ByCvsBDE3vxHLwyhSVNTQNvEPjJgGnWeBTVwviqjg9qo
Transaction Signature: 5ijBsiZnte3Yo47c8pmpw941pYyPiudx3ofvbAyjjGM1jBKqJuGYtfWjnotPZgtHuM8xZhwKHuP5s6es6vB1jd7G
Successfully minted 1.0 tokens
Transaction Signature: 2kW3RE7xMa7xrckj7LsFkw5TFNrkjtmDR5SX894JzUr3tGvxNtp3quUVgFHUqeAVQaKxenZeHmeKYpfwWjSxjRJm
Successfully transferred 0.5 tokens
=== Final Balances ===
Sender balance: 0.5 tokens
Recipient balance: 0.5 tokens
Web3.js v3
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL,
} from "@solana/web3.js";
import {
findAssociatedTokenPda,
getCreateAssociatedTokenInstruction,
getInitializeMintInstruction,
getMintSize,
getMintToInstruction,
getTokenDecoder,
getTransferInstruction,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = await Keypair.generate();
const sender = await Keypair.generate();
const recipient = await Keypair.generate();
// Airdrop 1 SOL to fee payer
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature,
});
// Airdrop 0.1 SOL to sender for rent exemption
const senderAirdropSignature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL / 10,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: senderAirdropSignature,
});
// Airdrop 0.1 SOL to recipient for rent exemption
const recipientAirdropSignature = await connection.requestAirdrop(
recipient.publicKey,
LAMPORTS_PER_SOL / 10,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: recipientAirdropSignature,
});
const mint = await Keypair.generate();
const mintRent =
await connection.getMinimumBalanceForRentExemption(getMintSize());
const [senderATA] = await findAssociatedTokenPda({
mint: mint.publicKey.toBase58(),
owner: sender.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const [recipientATA] = await findAssociatedTokenPda({
mint: mint.publicKey.toBase58(),
owner: recipient.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: sender.publicKey,
newAccountPubkey: mint.publicKey,
space: getMintSize(),
lamports: mintRent,
programId: new PublicKey(TOKEN_PROGRAM_ADDRESS),
});
const initializeMintInstruction = getInitializeMintInstruction({
mint: mint.publicKey,
decimals: 2,
mintAuthority: sender.publicKey.toBase58(),
freezeAuthority: sender.publicKey.toBase58(),
});
const createSenderATA = getCreateAssociatedTokenInstruction({
payer: sender,
ata: senderATA,
owner: sender.publicKey,
mint: mint.publicKey,
});
// Note: feePayer pays for recipient's ATA — that's the sponsorship
const createRecipientATA = getCreateAssociatedTokenInstruction({
payer: feePayer,
ata: recipientATA,
owner: recipient.publicKey,
mint: mint.publicKey,
});
const mintAmount = 100;
const mintToInstruction = getMintToInstruction({
mint: mint.publicKey,
token: senderATA,
mintAuthority: sender,
amount: mintAmount,
});
// feePayer pays the SOL fee for this whole transaction
const transaction = new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
}).add(
createAccountInstruction,
initializeMintInstruction,
createSenderATA,
createRecipientATA,
mintToInstruction,
);
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[feePayer, sender, mint],
);
console.log("Transaction Signature:", transactionSignature);
// Transfer tokens — fee still paid by feePayer
const transferAmount = 50;
const transferInstruction = getTransferInstruction({
source: senderATA,
destination: recipientATA,
authority: sender,
amount: transferAmount,
});
const transferBlockhash = await connection.getLatestBlockhash();
const transferTransaction = new Transaction({
feePayer: feePayer.publicKey,
blockhash: transferBlockhash.blockhash,
lastValidBlockHeight: transferBlockhash.lastValidBlockHeight,
}).add(transferInstruction);
const transactionSignature2 = await sendAndConfirmTransaction(
connection,
transferTransaction,
[feePayer, sender],
);
console.log("Successfully transferred 0.5 tokens");
console.log("Transaction Signature:", transactionSignature2);
const senderAccountInfo = await connection.getAccountInfo(
new PublicKey(senderATA),
);
const senderTokenAccount = getTokenDecoder().decode(senderAccountInfo!.data);
const recipientAccountInfo = await connection.getAccountInfo(
new PublicKey(recipientATA),
);
const recipientTokenAccount = getTokenDecoder().decode(
recipientAccountInfo!.data,
);
console.log("=== Final Balances ===");
console.log(
"Sender balance:",
Number(senderTokenAccount.amount) / 100,
"tokens",
);
console.log(
"Recipient balance:",
Number(recipientTokenAccount.amount) / 100,
"tokens",
);
Output from a local Surfpool network
Output
Transaction Signature: 3vtV9DN3hbD43SYS3zgqkFbExGtykjGoR6pFDJfMh3CLspwhsmL4yX1xzxmshS23hLXWfGSgxRmojcNEzvXKNeT7
Successfully transferred 0.5 tokens
Transaction Signature: 2EaMfk6scGvzvrYz9UGPVDc1F3ZZBJnpwuevFqgB2744yC83znNQqPRPA3ZvTzsXMg2GJVqRDQjc4KFH2GJzHVKD
=== Final Balances ===
Sender balance: 0.5 tokens
Recipient balance: 0.5 tokens
Web3.js v3 Helper
import {
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
sendAndConfirmTransaction,
Transaction,
} from "@solana/web3.js";
import {
findAssociatedTokenPda,
getCreateMintInstructionPlan,
getMintToATAInstructionPlan,
getTokenDecoder,
getTransferToATAInstructionPlan,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = await Keypair.generate();
const sender = await Keypair.generate();
const recipient = await Keypair.generate();
// Airdrop 1 SOL to fee payer
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature,
});
// Airdrop 1 SOL to sender so it can act as mint authority
const senderAirdropSignature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: senderAirdropSignature,
});
// Airdrop 0.1 SOL to recipient for rent exemption
const recipientAirdropSignature = await connection.requestAirdrop(
recipient.publicKey,
LAMPORTS_PER_SOL / 10,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: recipientAirdropSignature,
});
// Create mint with feePayer paying the SOL fees
const mint = await Keypair.generate();
await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
}).add(
await getCreateMintInstructionPlan(
{
getMinimumBalance: (space: number) =>
connection.getMinimumBalanceForRentExemption(space),
},
{
payer: feePayer, // fee payer
newMint: mint,
decimals: 2, // decimals
mintAuthority: sender.publicKey.toBase58(), // mint authority
freezeAuthority: sender.publicKey.toBase58(), // freeze authority
},
),
),
[feePayer, mint],
);
const mintPubkey = mint.publicKey;
console.log("Mint Address:", mintPubkey.toBase58());
const [senderATA] = await findAssociatedTokenPda({
mint: mintPubkey.toBase58(),
owner: sender.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
console.log("Sender ATA Address:", senderATA);
const [recipientATA] = await findAssociatedTokenPda({
mint: mintPubkey.toBase58(),
owner: recipient.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
console.log("Recipient ATA Address:", recipientATA);
// Mint 100 tokens (1.00 with 2 decimals) to the sender's ATA
const mintAmount = 100;
const mintSignature = await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
}).add(
getMintToATAInstructionPlan({
payer: feePayer, // payer (covers SOL fee)
ata: senderATA,
owner: sender.publicKey.toBase58(),
mint: mintPubkey.toBase58(),
mintAuthority: sender, // mint authority must sign
amount: mintAmount,
decimals: 2,
}),
),
[feePayer, sender],
);
console.log("Successfully minted 1.0 tokens");
console.log("Transaction Signature:", mintSignature);
// Transfer 50 tokens from sender to recipient (feePayer pays SOL fee)
const transferAmount = 50;
const transactionSignature2 = await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
}).add(
getTransferToATAInstructionPlan({
payer: feePayer,
mint: mintPubkey.toBase58(),
source: senderATA,
authority: sender,
destination: recipientATA,
recipient: recipient.publicKey.toBase58(),
amount: transferAmount,
decimals: 2,
}),
),
[feePayer, sender],
);
console.log("Successfully transferred 0.5 tokens");
console.log("Transaction Signature:", transactionSignature2);
const senderAccountInfo = await connection.getAccountInfo(
new PublicKey(senderATA),
);
const senderTokenAccount = getTokenDecoder().decode(senderAccountInfo!.data);
const recipientAccountInfo = await connection.getAccountInfo(
new PublicKey(recipientATA),
);
const recipientTokenAccount = getTokenDecoder().decode(
recipientAccountInfo!.data,
);
console.log("=== Final Balances ===");
console.log(
"Sender balance:",
Number(senderTokenAccount.amount) / 100,
"tokens",
);
console.log(
"Recipient balance:",
Number(recipientTokenAccount.amount) / 100,
"tokens",
);
Output from a local Surfpool network
Output
Mint Address: BfTqMu5vUUnqRv1Cr6fWBxuVoE4UmGta5ZRqJhhpHDvc
Sender ATA Address: HsrYuT9LU7nfZ3PLYYQMzz6YALjFQWLymFrmCQQqgBm5
Recipient ATA Address: 3wAAEFe6SrA6dgjs3kg9yuF81rYLaag2pTJQ55rGAtau
Successfully minted 1.0 tokens
Transaction Signature: 2hZy9CwcFJzdJQHaYvu9dxUTZMgdBns3EZ9Ghj1KywCQcDHQAqeyEpve2DgSLDknnPwDBU9U3N8qYYJ8Nso494VR
Successfully transferred 0.5 tokens
Transaction Signature: 3VfBzX5kCh1onpNQnsFAd3kEBTBhKvgfrjnLtY7k5jQSyirevJ313xsNkNf5HdQjTdKabNRGAcFzrCknr3Evasnq
=== Final Balances ===
Sender balance: 0.5 tokens
Recipient balance: 0.5 tokens
Python
import asyncio
from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.system_program import CreateAccountParams, create_account
from solders.transaction import VersionedTransaction
from spl.token.constants import MINT_LEN, TOKEN_PROGRAM_ID
from spl.token.instructions import (
create_associated_token_account,
get_associated_token_address,
initialize_mint,
mint_to,
transfer_checked,
)
from spl.token.models import InitializeMintParams, MintToParams, TransferCheckedParams
async def main():
async with AsyncClient("http://localhost:8899", commitment=Confirmed) as client:
fee_payer = Keypair() # pays every fee
sender = Keypair() # holds tokens but no SOL
recipient = Keypair()
mint = Keypair()
airdrop = await client.request_airdrop(fee_payer.pubkey(), 1_000_000_000)
await client.confirm_transaction(airdrop.value)
async def send(instructions, signers):
# fee_payer is the fee payer of every transaction
blockhash = (await client.get_latest_blockhash()).value.blockhash
message = MessageV0.try_compile(fee_payer.pubkey(), instructions, [], blockhash)
signature = (
await client.send_transaction(VersionedTransaction(message, signers))
).value
await client.confirm_transaction(signature)
return signature
# Setup: a mint with 2 decimals, and 1.00 token in the sender's account.
sender_ata = get_associated_token_address(sender.pubkey(), mint.pubkey())
recipient_ata = get_associated_token_address(recipient.pubkey(), mint.pubkey())
rent = (await client.get_minimum_balance_for_rent_exemption(MINT_LEN)).value
await send(
[
create_account(
CreateAccountParams(
from_pubkey=fee_payer.pubkey(),
to_pubkey=mint.pubkey(),
lamports=rent,
space=MINT_LEN,
owner=TOKEN_PROGRAM_ID,
)
),
initialize_mint(
InitializeMintParams(
program_id=TOKEN_PROGRAM_ID,
mint=mint.pubkey(),
decimals=2,
mint_authority=fee_payer.pubkey(),
)
),
create_associated_token_account(
fee_payer.pubkey(), sender.pubkey(), mint.pubkey()
),
create_associated_token_account(
fee_payer.pubkey(), recipient.pubkey(), mint.pubkey()
),
mint_to(
MintToParams(
program_id=TOKEN_PROGRAM_ID,
mint=mint.pubkey(),
dest=sender_ata,
mint_authority=fee_payer.pubkey(),
amount=100,
)
),
],
[fee_payer, mint],
)
# Sender transfers 0.50 token; fee_payer is the transaction's fee payer.
transfer_ix = transfer_checked(
TransferCheckedParams(
program_id=TOKEN_PROGRAM_ID,
source=sender_ata,
mint=mint.pubkey(),
dest=recipient_ata,
owner=sender.pubkey(),
amount=50,
decimals=2,
)
)
signature = await send([transfer_ix], [fee_payer, sender])
print("Transaction Signature:", signature)
asyncio.run(main())
Output from a local Surfpool network
Output
Transaction Signature: 4z9eWn8nBh95fZoF7Z78XDAp924q3W9kXGsc2TG9oPGzajyEjbUqr8AfvHeHr9BFjJcU2szJ2KCddffhqTLByz6T
Go
package main
import (
"context"
"fmt"
"time"
"github.com/solana-foundation/solana-go/v2"
ata "github.com/solana-foundation/solana-go/v2/programs/associated-token-account"
"github.com/solana-foundation/solana-go/v2/programs/system"
"github.com/solana-foundation/solana-go/v2/programs/token"
"github.com/solana-foundation/solana-go/v2/rpc"
)
func main() {
ctx := context.Background()
client := rpc.New("http://localhost:8899")
feePayer := solana.NewWallet() // pays every fee
sender := solana.NewWallet() // holds tokens but no SOL
recipient := solana.NewWallet()
mint := solana.NewWallet()
// Every transaction below is paid for by feePayer.
signers := map[solana.PublicKey]*solana.PrivateKey{
feePayer.PublicKey(): &feePayer.PrivateKey,
sender.PublicKey(): &sender.PrivateKey,
mint.PublicKey(): &mint.PrivateKey,
}
send := func(instructions ...solana.Instruction) solana.Signature {
recent, err := client.GetLatestBlockhash(ctx, rpc.CommitmentConfirmed)
if err != nil {
panic(err)
}
tx, err := solana.NewTransaction(
instructions,
recent.Value.Blockhash,
solana.TransactionPayer(feePayer.PublicKey()),
)
if err != nil {
panic(err)
}
tx.Sign(func(key solana.PublicKey) *solana.PrivateKey { return signers[key] })
sig, err := client.SendTransactionWithOpts(ctx, tx, rpc.TransactionOpts{
PreflightCommitment: rpc.CommitmentConfirmed,
})
if err != nil {
panic(err)
}
return sig
}
_, err := client.RequestAirdrop(ctx, feePayer.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
if err != nil {
panic(err)
}
time.Sleep(2 * time.Second)
// Setup: a mint with 2 decimals, and 1.00 token in the sender's account.
rent, err := client.GetMinimumBalanceForRentExemption(ctx, token.MINT_SIZE, rpc.CommitmentConfirmed)
if err != nil {
panic(err)
}
senderATA, _, _ := solana.FindAssociatedTokenAddress(sender.PublicKey(), mint.PublicKey())
recipientATA, _, _ := solana.FindAssociatedTokenAddress(recipient.PublicKey(), mint.PublicKey())
send(
system.NewCreateAccountInstruction(
rent, token.MINT_SIZE, solana.TokenProgramID, feePayer.PublicKey(), mint.PublicKey(),
).Build(),
token.NewInitializeMint2InstructionBuilder().
SetDecimals(2).
SetMintAuthority(feePayer.PublicKey()).
SetMintAccount(mint.PublicKey()).
Build(),
ata.NewCreateInstruction(feePayer.PublicKey(), sender.PublicKey(), mint.PublicKey()).Build(),
ata.NewCreateInstruction(feePayer.PublicKey(), recipient.PublicKey(), mint.PublicKey()).Build(),
token.NewMintToCheckedInstruction(
100, 2, mint.PublicKey(), senderATA, feePayer.PublicKey(), nil,
).Build(),
)
time.Sleep(2 * time.Second)
// Sender transfers 0.50 token without holding any SOL.
sig := send(
token.NewTransferCheckedInstruction(
50, 2, senderATA, mint.PublicKey(), recipientATA, sender.PublicKey(), nil,
).Build(),
)
fmt.Println("Transaction Signature:", sig)
}
Output from a local Surfpool network
Output
Transaction Signature: 3YPLDG6Tibh3yeMAJmhz1jD7jAZbTeB8qar9u59WgK5nsUuS8YX7nRxRCVDd44uY9Emueuys39jsYmBMDQXk7pQJ
Web3.js (legacy)
@solana/web3.js 1.x is no longer actively maintainedIt receives critical fixes only. Use Kit for new code. To migrate existing code, follow the Kit upgrade guide, or the web3.js v3 migration guide to keep the class-based API.To run this code, install 1.x with npm install @solana/web3.js@1. A plain npm install @solana/web3.js installs v3, which this code doesn’t run on.import {
Connection,
Keypair,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL,
} from "@solana/web3.js";
import {
createInitializeMintInstruction,
MINT_SIZE,
getMinimumBalanceForRentExemptMint,
TOKEN_PROGRAM_ID,
getAssociatedTokenAddressSync,
createAssociatedTokenAccountInstruction,
ASSOCIATED_TOKEN_PROGRAM_ID,
createMintToInstruction,
createTransferInstruction,
getAccount,
} from "@solana/spl-token";
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = Keypair.generate();
const sender = Keypair.generate();
const recipient = Keypair.generate();
// Airdrop 1 SOL to fee payer
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature,
});
// Airdrop 0.1 SOL to sender for rent exemption
const senderAirdropSignature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL / 10,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: senderAirdropSignature,
});
// Airdrop 0.1 SOL to recipient for rent exemption
const recipientAirdropSignature = await connection.requestAirdrop(
recipient.publicKey,
LAMPORTS_PER_SOL / 10,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: recipientAirdropSignature,
});
const mint = Keypair.generate();
const mintRent = await getMinimumBalanceForRentExemptMint(connection);
const senderATA = getAssociatedTokenAddressSync(
mint.publicKey,
sender.publicKey,
false,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
);
const recipientATA = getAssociatedTokenAddressSync(
mint.publicKey,
recipient.publicKey,
false,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
);
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: sender.publicKey,
newAccountPubkey: mint.publicKey,
space: MINT_SIZE,
lamports: mintRent,
programId: TOKEN_PROGRAM_ID,
});
const initializeMintInstruction = createInitializeMintInstruction(
mint.publicKey,
2,
sender.publicKey,
sender.publicKey,
TOKEN_PROGRAM_ID,
);
const createSenderATA = createAssociatedTokenAccountInstruction(
sender.publicKey,
senderATA,
sender.publicKey,
mint.publicKey,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
);
// Note: feePayer pays for recipient's ATA — that's the sponsorship
const createRecipientATA = createAssociatedTokenAccountInstruction(
feePayer.publicKey,
recipientATA,
recipient.publicKey,
mint.publicKey,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
);
const mintAmount = 100;
const mintToInstruction = createMintToInstruction(
mint.publicKey,
senderATA,
sender.publicKey,
mintAmount,
[],
TOKEN_PROGRAM_ID,
);
// feePayer pays the SOL fee for this whole transaction
const transaction = new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
}).add(
createAccountInstruction,
initializeMintInstruction,
createSenderATA,
createRecipientATA,
mintToInstruction,
);
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[feePayer, sender, mint],
);
console.log("Transaction Signature:", transactionSignature);
// Transfer tokens — fee still paid by feePayer
const transferAmount = 50;
const transferInstruction = createTransferInstruction(
senderATA,
recipientATA,
sender.publicKey,
transferAmount,
[],
TOKEN_PROGRAM_ID,
);
const transferBlockhash = await connection.getLatestBlockhash();
const transferTransaction = new Transaction({
feePayer: feePayer.publicKey,
blockhash: transferBlockhash.blockhash,
lastValidBlockHeight: transferBlockhash.lastValidBlockHeight,
}).add(transferInstruction);
const transactionSignature2 = await sendAndConfirmTransaction(
connection,
transferTransaction,
[feePayer, sender],
);
console.log("Successfully transferred 0.5 tokens");
console.log("Transaction Signature:", transactionSignature2);
const senderTokenAccount = await getAccount(
connection,
senderATA,
"confirmed",
TOKEN_PROGRAM_ID,
);
const recipientTokenAccount = await getAccount(
connection,
recipientATA,
"confirmed",
TOKEN_PROGRAM_ID,
);
console.log("=== Final Balances ===");
console.log(
"Sender balance:",
Number(senderTokenAccount.amount) / 100,
"tokens",
);
console.log(
"Recipient balance:",
Number(recipientTokenAccount.amount) / 100,
"tokens",
);
Output from a local Surfpool network
Output
Transaction Signature: 5FBcbLBtmKF9r3PUwipDizyknGWEiob3dqUkxqGbxyZs5T1qRWkdkeK69E2bXGY7BvNA2N7jWSxPKwk97VkNcuTn
Successfully transferred 0.5 tokens
Transaction Signature: 4tmsbkUuLGuGrRk7Q74t8Zedq6TAWWTt28mHEhUbJbU1Rrnu3t7sPHndHpPNnVz4AfDCPS6BZhYo9gcAMz7pXHhY
=== Final Balances ===
Sender balance: 0.5 tokens
Recipient balance: 0.5 tokens
Web3.js (legacy) Helper
@solana/web3.js 1.x is no longer actively maintainedIt receives critical fixes only. Use Kit for new code. To migrate existing code, follow the Kit upgrade guide, or the web3.js v3 migration guide to keep the class-based API.To run this code, install 1.x with npm install @solana/web3.js@1. A plain npm install @solana/web3.js installs v3, which this code doesn’t run on.import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import {
createMint,
createAssociatedTokenAccount,
mintTo,
TOKEN_PROGRAM_ID,
transfer,
getAccount,
} from "@solana/spl-token";
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = Keypair.generate();
const sender = Keypair.generate();
const recipient = Keypair.generate();
// Airdrop 1 SOL to fee payer
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature,
});
// Airdrop 1 SOL to sender so it can act as mint authority
const senderAirdropSignature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: senderAirdropSignature,
});
// Airdrop 0.1 SOL to recipient for rent exemption
const recipientAirdropSignature = await connection.requestAirdrop(
recipient.publicKey,
LAMPORTS_PER_SOL / 10,
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: recipientAirdropSignature,
});
// Create mint with feePayer paying the SOL fees
const mintPubkey = await createMint(
connection,
feePayer, // fee payer
sender.publicKey, // mint authority
sender.publicKey, // freeze authority
2, // decimals
Keypair.generate(),
{ commitment: "confirmed" },
TOKEN_PROGRAM_ID,
);
console.log("Mint Address:", mintPubkey.toBase58());
// Create sender's ATA (feePayer covers the fee)
const senderATA = await createAssociatedTokenAccount(
connection,
feePayer,
mintPubkey,
sender.publicKey,
{ commitment: "confirmed" },
TOKEN_PROGRAM_ID,
);
console.log("Sender ATA Address:", senderATA.toBase58());
// Create recipient's ATA (feePayer covers the fee)
const recipientATA = await createAssociatedTokenAccount(
connection,
feePayer,
mintPubkey,
recipient.publicKey,
{ commitment: "confirmed" },
TOKEN_PROGRAM_ID,
);
console.log("Recipient ATA Address:", recipientATA.toBase58());
// Mint 100 tokens (1.00 with 2 decimals) to the sender's ATA
const mintAmount = 100;
const mintSignature = await mintTo(
connection,
feePayer, // payer (covers SOL fee)
mintPubkey,
senderATA,
sender.publicKey, // mint authority
mintAmount,
[sender], // mint authority must sign
{ commitment: "confirmed" },
TOKEN_PROGRAM_ID,
);
console.log("Successfully minted 1.0 tokens");
console.log("Transaction Signature:", mintSignature);
// Transfer 50 tokens from sender to recipient (feePayer pays SOL fee)
const transferAmount = 50;
const transactionSignature2 = await transfer(
connection,
feePayer,
senderATA,
recipientATA,
sender.publicKey,
transferAmount,
[sender],
{ commitment: "confirmed" },
TOKEN_PROGRAM_ID,
);
console.log("Successfully transferred 0.5 tokens");
console.log("Transaction Signature:", transactionSignature2);
const senderTokenAccount = await getAccount(
connection,
senderATA,
"confirmed",
TOKEN_PROGRAM_ID,
);
const recipientTokenAccount = await getAccount(
connection,
recipientATA,
"confirmed",
TOKEN_PROGRAM_ID,
);
console.log("=== Final Balances ===");
console.log(
"Sender balance:",
Number(senderTokenAccount.amount) / 100,
"tokens",
);
console.log(
"Recipient balance:",
Number(recipientTokenAccount.amount) / 100,
"tokens",
);
Output from a local Surfpool network
Output
Mint Address: 2f6zTUCJANrHpogi712hK9K4A82QMfbm9XCvHhw8Hac1
Sender ATA Address: EbHVLe8WKT7siHkFuSrHWtVaPB8Z7wTbHj2gKqgvwr66
Recipient ATA Address: GLGtQLqjWZUVKAymDT4z2Lhyzip9YQPTRtnAtLxTq3kg
Successfully minted 1.0 tokens
Transaction Signature: 5wTgiRjvCQjbxNtunpnBWhzXv7DCfCDa75Qeju7qWFQ3svg78yxFmDYVwYVkKT36FVJcKAevGgu247pb7isZCnVd
Successfully transferred 0.5 tokens
Transaction Signature: DgfxvFAtsymzGfrzEjMq3JRZ6Zqf4YMMxynhscAZXEUPctBHZoj2VDUJTdwSQerieQmdD5hVCGCYkyJWqDN58K7
=== Final Balances ===
Sender balance: 0.5 tokens
Recipient balance: 0.5 tokens
Sponsoring in production
Signing as fee payer for anything a client sends you is risky: someone could drain your SOL with transactions you didn’t intend to pay for. Before your service signs, check what the transaction does, limit which programs and amounts it may touch, and rate-limit each user. Kora is a fee-payer service that does this for you. It signs only transactions that pass the policy you configure, and it can charge users in a token such as USDC instead of SOL.- Fee abstraction: sponsor fees in a payment flow, then move to Kora at scale.
- Pay fees with any token in the cookbook.
- Fee structure: what the fee you are sponsoring is made of.