How can we collect the transfer fee/tax per token transfer on Solana? Is it possible to automate this process, or do we need to collect it manually? Manually means here , to run js code for searching those accounts and then withdraw funds to wallet.
1 Answer
During the creation of the token we can include an instruction in the transaction to config the Transfer fee.
The transaction would look like this
const mintTransaction = new Transaction().add(
SystemProgram.createAccount({
fromPubkey: payer.publicKey,
newAccountPubkey: mint,
space: mintLen,
lamports: mintLamports,
programId: TOKEN_2022_PROGRAM_ID,
}),
createInitializeTransferFeeConfigInstruction(
mint,
transferFeeConfigAuthority.publicKey,
withdrawWithheldAuthority.publicKey,
feeBasisPoints,
maxFee,
TOKEN_2022_PROGRAM_ID
),
createInitializeMintInstruction(
mint,
decimals,
payer.publicKey,
null,
TOKEN_2022_PROGRAM_ID
),
);
Where the transferFeeConfigAuthority is the account responsible to store how much each user should pay when they interact with your token, and the withdrawWithheldAuthority is responsible to store all the transaction fees collected.
Here is a repo containing how Create token with transaction fees
you can now find the account with the withheld funds and transfer the amount anywhere using the withdrawWithheldTokensFromAccounts.
await withdrawWithheldTokensFromAccounts(
connection,
payer,
mint,
destinationAccount,
withdrawWithheldAuthority,
[],
[destinationAccount],
undefined,
TOKEN_2022_PROGRAM_ID
);