- Enforcing NFT royalties
- Black or white list wallets that can receive tokens
- Implementing custom fees on token transfers
- Creating custom token transfer events
- Track statistics over your token transfers
- And many more
When the Token Extensions program CPIs to a Transfer Hook program, all accounts
from the initial transfer are converted to read-only accounts. This means the
signer privileges of the sender do not extend to the Transfer Hook program.This design decision is made to prevent malicious use of Transfer Hook programs.
The programs in this guide use Anchor 1.1.2 and run on your machine. You build
them in one Anchor project, one stage at a time: a hello-world hook, a counter,
and a hook that charges a wSOL fee. Each stage’s TypeScript test creates a mint
that uses the hook and transfers it on a local validator. Start with
Set up the project.
Transfer Hook Interface Overview
The Transfer Hook Interface provides a way for developers to implement custom instruction logic that is executed on every token transfer for a specific Mint Account. The Transfer Hook Interface specifies the following instructions:Execute: An instruction that the Token Extension program invokes on every token transfer.InitializeExtraAccountMetaList(optional): Creates an account that stores a list of additional accounts required by the customExecuteinstruction.UpdateExtraAccountMetaList(optional): Updates the list of additional accounts by overwriting the existing list.
InitializeExtraAccountMetaList
instruction using the interface. The account can be created by any instruction
on a Transfer Hook program.
However, the program-derived address (PDA) for the account must be derived using
the following seeds:
- The hard coded string “extra-account-metas”
- The Mint Account address
- The Transfer Hook program ID
@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.Execute instruction in the
predefined PDA, these accounts can be automatically added to a token transfer
instruction from the client.
Set up the project
Install Rust, the Solana CLI, the Anchor CLI, Node.js, and Yarn as shown in the Quickstart. This guide was tested with Anchor CLI 1.1.2 and Solana CLI 3.1.10, the release that AVM installs with Anchor 1.1.2.1
Create the project
Create an Anchor project with a single-file program and a Mocha test:
Terminal
--package-manager yarn sets the project up with Yarn, which the installer
includes. Without it, anchor init uses the first of pnpm, Yarn, and npm that
it finds. The program is in programs/transfer-hook/src/lib.rs and its test is
in tests/transfer-hook.ts. Each example in this guide replaces one or both
files.2
Add the Rust dependencies
From the program’s folder, add Then add
anchor-spl and the crates for the Transfer Hook
Interface. These versions build against the same Solana 3.x crates as Anchor
1.1.2:Terminal
anchor-spl/idl-build to the idl-build feature in
programs/transfer-hook/Cargo.toml. Without it, anchor build fails with
Building IDL failed:programs/transfer-hook/Cargo.toml
3
Add the TypeScript packages
The tests build token instructions with
@solana/spl-token, which runs on
@solana/web3.js 1.x:Terminal
Terminal
anchor test builds the program, starts a local validator, deploys the program
to it, runs tests/transfer-hook.ts, then stops the validator. With
--validator legacy the local validator is solana-test-validator. Without the
flag, Anchor 1.1.2 starts Surfpool, and on Surfpool 1.7.0 the wSOL fee example’s
transfer fails with Blockhash not found.
If
anchor build or anchor test stops with
Platform tools v1.52 is incompatible with SBPFv3, you’re on Solana CLI 4.3 or
later without AVM (see
Build your first program).
Build the program for SBPF v0 without the IDL, build the IDL and its TypeScript
types on their own, then test without rebuilding:Terminal
Hello-world Transfer hook
This example is the hello world of transfer hooks. It is a simple transfer hook that will just print a message on every token transfer. This program has 2 instructions:initialize_extra_account_meta_list: Creates an account that stores a list of extra accounts required by thetransfer_hookinstruction. In the hello world we leave this empty.transfer_hook: This instruction is invoked via CPI on every token transfer. In the hello world it only logs a message.
transfer_hook function will be
called by the token program. Its #[instruction(discriminator = ...)]
attribute gives it the discriminator of the interface’s Execute instruction,
which is the instruction the Token Extensions program calls.
Instruction discriminator explains why.
programs/transfer-hook/src/lib.rs with the
complete program:
programs/transfer-hook/src/lib.rs
declare_id! at your project’s program ID:
Terminal
tests/transfer-hook.ts with the test below. It creates a mint
whose Transfer Hook extension points at your program, creates two token
accounts and mints 100 tokens, creates the ExtraAccountMetaList account, then
transfers one token and prints the program logs from the transfer.
@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.tests/transfer-hook.ts
Terminal
amount is
in base units, so scale the limit by the mint’s decimals: the test mints a token
with 9 decimals and transfers 1 * 10 ** decimals (one token), which a plain
amount > 50 check would reject. Put the MyError enum outside the
#[program] module:
AmountTooBig.
To create a mint that uses your hook from the command line instead, for example
on devnet after you deploy the program there, use the spl-token CLI. The mint
still needs its ExtraAccountMetaList account, which
initialize_extra_account_meta_list creates.
Counter Transfer hook
The next example increases a counter every time your token is transferred. If you want to add logic to your transfer hook that needs additional accounts you need to add them to the ExtraAccountMetaList account. In our case here we want a PDA that saves how often the token has been transferred. This can be done by adding the following code to theinitialize_extra_account_meta_list instruction:
init_if_needed creates the counter account if it doesn’t exist yet. It needs
Anchor’s init-if-needed feature, which you turn on below.
And the account will hold a u64 counter variable (space = 16 is the 8-byte
account discriminator plus the u64):
getTransferCheckedWithTransferHookInstructionAsync from
@solana-program/token-2022 on web3.js v3, or
createTransferCheckedWithTransferHookInstruction from @solana/spl-token on
legacy web3.js. The v3 helper takes a Kit RPC, so build one for the same
endpoint as the Connection with createSolanaRpc from @solana/kit.
@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.init-if-needed feature from the program’s
folder:
Terminal
programs/transfer-hook/src/lib.rs with the complete counter program,
then run anchor keys sync again:
Complete counter program
Complete counter program
programs/transfer-hook/src/lib.rs
initializeExtraAccountMetaList() fills in counterAccount from the seeds in
the program’s IDL, and createTransferCheckedWithTransferHookInstruction adds
the counter PDA to the transfer. To also read the saved count, add these lines
at the end of the Transfer Hook with Extra Account Meta test in
tests/transfer-hook.ts:
anchor test --validator legacy. The transfer’s logs now include the
count:
Security: Anyone can call your hook directlySince here we are increasing a counter whenever the token is transferred we need
to make sure that the transfer hook instruction can only be called during a
transfer, otherwise someone could just call the transfer hook instruction
directly and mess up our counter. This is a check you should add to any of your
transfer hooks.
TransferHookAccount extension whose
transferring flag Token-2022 sets only while it runs a transfer. You can check
it like this (add the use lines at the top of lib.rs, and the error enum and
the function outside the #[program] module):
transfer_hook function:
IsNotCurrentlyTransferring. To see it, add this test at the end of the
describe block in tests/transfer-hook.ts, then run
anchor test --validator legacy again:
Transfer Hook with wSOL Transfer fee (advanced example)
In the next part of this guide, we will build a more advanced Transfer Hook program using the Anchor framework. This program will require the sender to pay a wSOL fee for every token transfer. The wSOL transfers will be executed using a delegate that is a PDA derived from the Transfer Hook program. This is necessary because the signature from the initial sender of the token transfer instruction is not accessible in the Transfer Hook program. This program has 2 instructions:initialize_extra_account_meta_list: Creates an account that stores a list of extra accounts required by thetransfer_hookinstruction.transfer_hook: This instruction is invoked via CPI on every token transfer to perform a wrapped SOL token transfer. Its discriminator matches the interface’sExecuteinstruction, as in the earlier examples.
Getting Started
Continue in the same project. Replaceprograms/transfer-hook/src/lib.rs with
the starter code below, which is scaffolded for the program we will be creating:
programs/transfer-hook/src/lib.rs
declare_id! at your program ID and build the starter program:
Terminal
Initialize ExtraAccountMetas Account Instruction
In this step, we will implement theinitialize_extra_account_meta_list
instruction for our Transfer Hook program. This instruction creates an
ExtraAccountMetas account, which will store the additional accounts required by
our transfer_hook instruction.
In this example, the initialize_extra_account_meta_list instruction requires 7
accounts:
payer: The account used to pay for the creation of the ExtraAccountMetas account.extra_account_meta_list: The ExtraAccountMetas account created to store the list of accounts required by ourtransfer_hookinstruction.mint: The Mint Account that points to this Transfer Hook program. The mint address is a required seed for deriving theextra_account_meta_listPDA.wsol_mint: The wrapped SOL mint.token_program: The original Token program IDassociated_token_program: The Associated Token program ID.system_program: The system program, which is a required account when creating new accounts.
mint, wsol_mint, and associated_token_program will be
used to derive the addresses for the wSOL Associated Token Accounts. These
accounts are required by the transfer_hook instruction and will be stored on
the ExtraAccountMetas account.
Update the InitializeExtraAccountMetaList struct by replacing the following
starter code:
initialize_extra_account_meta_list instruction by replacing
the following starter code:
- Directly store the account address:
- Wrapped SOL mint address
- Token Program ID
- Associated Token Program ID
- Store the seeds to derive a PDA for the Transfer Hook program:
- Delegate PDA
- Store the seeds to derive a PDA for a program other than the Transfer Hook
program:
- Delegate wSOL Associated Token Account
- Sender wSOL Associated Token Account
CpiContext::new takes the address of the program being invoked,
here ctx.accounts.system_program.key().
In this example, we are not using the Transfer Hook interface to create the
ExtraAccountMetas account.
Custom Transfer Hook Instruction
Next, let’s implement the customtransfer_hook instruction. This is the
instruction the Token Extension program will invoke on every token transfer.
In this example, we will require a fee paid in wSOL for every token transfer.
For simplicity, the fee amount equals the token transfer amount.
Update the TransferHook struct by replacing the following starter code:
Note that the order of accounts in this struct matters. This is the order in
which the Token Extensions program provides these accounts when it CPIs to this
Transfer Hook program.
transfer_hook instruction.
initialize_extra_account_meta_list
instruction.
try_accounts). Without the
boxes, that function’s stack frame grows past the 4,096-byte limit for one
function: anchor build prints Stack offset of ... exceeded max offset of 4096, and the transfer fails with Access violation in stack frame.
Next, update the transfer_hook instruction by replacing the following starter
code:
Instruction discriminator
The starter code already sets thetransfer_hook instruction’s discriminator.
Here is why the program needs it.
The Token Extensions program calls the hook with the Transfer Hook Interface’s
Execute instruction. Its instruction data starts with an 8-byte discriminator,
the first 8 bytes of the SHA-256 hash of spl-transfer-hook-interface:execute,
followed by the u64 amount. Anchor derives an instruction’s discriminator from
its name (the hash of global:transfer_hook), so without an override the CPI
matches no instruction in the program and every transfer fails with
InstructionFallbackNotFound.
The #[instruction(discriminator = ...)] attribute replaces the derived
discriminator with the interface’s:
amount argument.
The IDL records the same discriminator, so the TypeScript client’s
program.methods.transferHook() sends the bytes the Token Extensions program
sends. Examples written for Anchor 0.29 route Execute through a fallback
function instead; in Anchor 1.x, set the discriminator on the instruction.
Build the program
The Transfer Hook program is now complete:Complete wSOL fee program
Complete wSOL fee program
programs/transfer-hook/src/lib.rs
anchor keys sync first to
point its declare_id! at your project’s program ID:
Terminal
anchor test deploys the program to the local validator it starts, so you
don’t need to deploy it to run the test. To deploy it to devnet, see
Deploy Program.
Test File Overview
Next, let’s test the program. Replacetests/transfer-hook.ts with the
following starter code:
The test file below uses legacy web3.js (
@solana/web3.js v1) and
@solana/spl-token, because Anchor’s TypeScript client (@anchor-lang/core,
with AnchorProvider, program.methods, and the Wallet it exposes) is
built on legacy web3.js types. For a client-side send path written against
web3.js v3 and @solana-program/token-2022, see the Transfer Hook
Integration
Guide.@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.tests/transfer-hook.ts
Create Mint Account
To begin, build a transaction to create a new Mint Account with the Transfer Hook extension enabled. In this transaction, make sure to specify our program as the Transfer Hook program stored on the extension. Enabling the Transfer Hook extension allows the Transfer Extension program to determine which program to invoke on every token transfer. Replace the placeholder test:Creating Token Accounts
Next, as part of the setup, create the Associated Token Accounts for both the sender and recipient. Also, fund the sender’s account with some tokens. Replace the placeholder test:Create ExtraAccountMeta Account
Before sending a token transfer, we need to create the ExtraAccountMetas account to store all the additional accounts required by the transfer hook instruction. To create this account, we invoke the instruction from our program.accountsPartial lets the test pass accounts that the client could also derive
from the IDL, such as the PDA and the program addresses.
Replace the placeholder test:
Transfer Tokens
Finally, we are ready to send a token transfer. In addition to the transfer instruction, there are a few additional instructions that need to be included.- The sender must transfer SOL to their wSOL token account to cover the fee required by the transfer hook instruction.
- The sender must approve the delegate PDA for the amount of the wSOL fee.
- Include an instruction to sync the wSOL balance.
- The token transfer instruction must include all the extra accounts required by the transfer hook instruction.
createTransferCheckedWithTransferHookInstruction, which the starter file
doesn’t import. Add it to the @solana/spl-token import at the top of the file:
Complete test file
Complete test file
tests/transfer-hook.ts
Run Test File
Once you have updated all the tests, the final step is to run the test:Terminal
Using token account data in transfer hook
Sometimes you may want to use account data to derive additional accounts in the extra account metas. This is useful if, for example, you want to use the token account’s owner as a seed for a PDA. When creating the ExtraAccountMeta you can use the data of any account as an extra seed. In this case we want to derive a counter account from the token account owner and the string ‘counter’. This means we will be always able to see how often that token account owner has transferred tokens. This is how you set it up in theextra_account_metas() function.
account_index: 0. account_index refers to the index of the account in the
accounts array. In the case of a transfer hook, the source token account is the
first entry in the accounts array. The second account is always the mint and the
third account is the destination token account. This account order is the same
as in the old token program.
init this PDA
counter account that is derived from the sender token account owner and the
string ‘counter’. When the PDA counter account is initialized we will be able to
use it within the transfer hook to increment the value in every transfer.
Add the counter account to the InitializeExtraAccountMetaList struct. The
struct uses Program<'info, Token2022>, so also import Token2022 from
anchor_spl:
init, the
instruction only writes the list into it:
counter_account as mut:
Anchor only writes back accounts marked mut, so without it the new count is
never saved.
@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.programs/transfer-hook/src/lib.rs with the
complete program below and run anchor keys sync. Replace
tests/transfer-hook.ts with the hello-world test
again, then run anchor test --validator legacy. The transfer’s logs name the
sender’s wallet address:
Complete program with an owner-derived counter
Complete program with an owner-derived counter
programs/transfer-hook/src/lib.rs