Skip to content
This enables new use cases for token transfers, such as:
  • 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
To achieve this, developers must build a program that implements the Transfer Hook Interface and initialize a Mint Account with the Transfer Hook extension enabled. For every token transfer involving tokens from the Mint Account, the Token Extensions program makes a cross-program invocation (CPI) to execute an instruction on the Transfer Hook program.
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.
In this guide, we will create Transfer Hook programs with the Anchor framework. You can also implement the Transfer Hook Interface in a native program. Learn more about Anchor at anchor-lang.com.
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 custom Execute instruction.
  • UpdateExtraAccountMetaList (optional): Updates the list of additional accounts by overwriting the existing list.
It is technically not required to implement the 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
By storing the extra accounts required by the 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 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
Then add 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
Run each example’s test with:
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:
  1. initialize_extra_account_meta_list: Creates an account that stores a list of extra accounts required by the transfer_hook instruction. In the hello world we leave this empty.
  2. transfer_hook: This instruction is invoked via CPI on every token transfer. In the hello world it only logs a message.
Every time the token gets transferred this 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.
To run the example, replace programs/transfer-hook/src/lib.rs with the complete program:
programs/transfer-hook/src/lib.rs
Then point declare_id! at your project’s program ID:
Terminal
Next, replace 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
Run the test:
Terminal
The output looks like this, with different signatures. The logs show the Token Extensions program calling your hook during the transfer:
In this function you can now add your additional logic. For example, you could let the transfer fail whenever more than 50 tokens are transferred. 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:
With this check, the test’s one-token transfer still passes, and a transfer of 51 tokens fails with 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 the initialize_extra_account_meta_list instruction:
And we also need to create this account when we initialize the new mint account and we need to pass it in every time we transfer the token.
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):
Now in our transfer hook function we can just increase this counter by one every time it gets called:
In the client these additional accounts are added automatically by a helper function: 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.
To run the example, turn on the init-if-needed feature from the program’s folder:
Terminal
Replace programs/transfer-hook/src/lib.rs with the complete counter program, then run anchor keys sync again:

Complete counter program

programs/transfer-hook/src/lib.rs
The hello-world test runs this program without changes: 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:
Then run 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.
The source token account carries a 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):
And then call it at the start of your transfer_hook function:
A direct call to the hook (outside a transfer) now fails with 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:
The transfer still passes, and the new test prints the error code:

​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:
  1. initialize_extra_account_meta_list: Creates an account that stores a list of extra accounts required by the transfer_hook instruction.
  2. transfer_hook: This instruction is invoked via CPI on every token transfer to perform a wrapped SOL token transfer. Its discriminator matches the interface’s Execute instruction, as in the earlier examples.
This program will require the sender to pay a fee in wrapped SOL (wSOL) on every token transfer. The complete program is under Build the program.

​Getting Started

Continue in the same project. Replace programs/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
Point declare_id! at your program ID and build the starter program:
Terminal
The build prints warnings about unused imports and variables. The next steps use them.

​Initialize ExtraAccountMetas Account Instruction

In this step, we will implement the initialize_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 our transfer_hook instruction.
  • mint: The Mint Account that points to this Transfer Hook program. The mint address is a required seed for deriving the extra_account_meta_list PDA.
  • wsol_mint: The wrapped SOL mint.
  • token_program: The original Token program ID
  • associated_token_program: The Associated Token program ID.
  • system_program: The system program, which is a required account when creating new accounts.
The addresses for 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:
With the code provided below:
Next, update the initialize_extra_account_meta_list instruction by replacing the following starter code:
With the code below:
Let’s walk through the updated instruction logic. We begin by listing the additional accounts that need to be stored on the ExtraAccountMetas account.
There are three methods for storing these accounts:
  1. Directly store the account address:
    • Wrapped SOL mint address
    • Token Program ID
    • Associated Token Program ID
  1. Store the seeds to derive a PDA for the Transfer Hook program:
    • Delegate PDA
  1. 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
Next, we calculate the size and rent required to store the list of ExtraAccountMetas.
Next, we make a CPI to the System Program to create an account and set the Transfer Hook Program as the owner. The PDA seeds are included as signer seeds on the CPI because we are using the PDA as the address of the new account. In Anchor 1.x, CpiContext::new takes the address of the program being invoked, here ctx.accounts.system_program.key().
Once we’ve created the account, we initialize the account data to store the list of ExtraAccountMetas.
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 custom transfer_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:
With the updated code below:
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.
The first 4 accounts are the accounts required by the initial token transfer.
The 5th account is the address of the ExtraAccountMeta account that stores the list of extra accounts required by our transfer_hook instruction.
The remaining accounts are the accounts listed in the ExtraAccountMetas account in the order we defined them in the initialize_extra_account_meta_list instruction.
The two wSOL token accounts are boxed, which keeps them on the heap. Anchor deserializes all 11 accounts in one function (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:
With the updated code below:
Within the instruction logic, we make a CPI to transfer wSOL from the sender’s wSOL token account. This transfer is signed for using the delegate PDA. For every token transfer, the sender must first approve the delegate for the transfer amount.

​Instruction discriminator

The starter code already sets the transfer_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:
Anchor then reads the bytes after the discriminator as the 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

programs/transfer-hook/src/lib.rs
Build it. If you pasted the complete program, run 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. Replace tests/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
First, we generate a keypair to use as the address for a new Mint Account. Using the mint address, we derive the Associated Token Account (ATA) addresses that we will use for the token transfer.
Next, we derive the PDA for the ExtraAccountMetas account. This account is created to store the additional accounts required by the custom transfer hook instruction.
We also derive the PDA that will be used as the delegate. The sender must approve this address as a delegate for their wSOL token account. This delegate PDA is used to “sign” for the wSOL transfer in the custom transfer hook instruction.
Additionally, we derive the addresses for the wSOL token accounts. The first address is for the sender’s wSOL token account, which needs to be funded to pay for the transfer fee required by the transfer hook instruction. The second address is for the wSOL token account owned by the delegate PDA. In this example, all wSOL fees are sent to this account.
Finally, as part of the setup, we create the wSOL token accounts.

​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:
With the updated test below:

​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:
With the updated test below:

​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:
With the updated test below:

​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.
The test builds the transfer with createTransferCheckedWithTransferHookInstruction, which the starter file doesn’t import. Add it to the @solana/spl-token import at the top of the file:
Then replace the placeholder test:
With the updated test below. After the transfer, it reads the delegate PDA’s wSOL token account and checks that it received the fee:
The transfer instruction must include all additional AccountMetas, the address of the ExtraAccountMetas account, and the address of the Transfer Hook program.

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
You should see output similar to the following. The fee equals the transfer amount, 1 token with 9 decimals, so the delegate’s wSOL account receives 1,000,000,000 lamports (1 SOL):

​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 the extra_account_metas() function.
Let’s look at the token account struct to understand how the account data is stored. Below is an example of a token account structure. So we can take 32 bytes at position 32 to 64 as the owner of the token account, which is at 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.
In our case, we want to derive a counter account from the owner of the sender token account so when we create the ExtraAccountMeta accounts we 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:
Because the struct creates the ExtraAccountMetaList account with init, the instruction only writes the list into it:
We also need to define this extra counter account in the TransferHook struct. These are the accounts that are passed to our TransferHook program every time a transfer is done. The client gets these additional accounts from the ExtraAccountsMetaList PDA and includes them in token transfer instruction, but here in the program we still need to define it. Mark counter_account as mut: Anchor only writes back accounts marked mut, so without it the new count is never saved.
The hook then increments the owner’s counter on every transfer:
In the client this account is auto generated and you can use it as follows.
The helper function is resolving the account automatically from the ExtraAccounts data account. How the account would be resolved in the client is like this:
Note that the counter account is derived from the owner of the token account and needs to be initialized before doing a transfer. In the case of this example we initialize the counter account when we initialize the extra account metas. So we will only have a counter PDA for the owner of the token account that called that function. If you want to have a counter account for every token account for your mint out there you will need to have some functionality to create these PDAs before hand. There could be a button on your dapp to sign up for a counter that creates this PDA account and from then on the users can use this counter token. To run this version, replace 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

programs/transfer-hook/src/lib.rs

​Conclusion

The Transfer Hook extension and Transfer Hook Interface allow for the creation of Mint Accounts that execute custom instruction logic on every token transfer. This guide serves as a reference to help you create your own Transfer Hook programs. Use them to build the transfer rules your token needs.