compressSplTokenAccount function compresses the balance of an SPL token account, with an optional remainingAmount parameter to leave tokens in the original account.
Before compressing SPL token accounts, you need:
- An SPL mint with a token pool for compression. This token pool can be created for new SPL mints via
createMint(), and - SPL token account (ATA) with tokens to compress.
closeAccount().
Function Difference and Best Practice:
compressSplTokenAccount(tokenAccount, remainingAmount)compresses the entire SPL token
account balance minus optional remaining amount only to the same owner. Use to migrate complete token
accounts with optional partial retention.compress(amount, sourceTokenAccount, toAddress)compresses specific amounts from
source to a specified recipient. Use for transfers and precise amounts. Here is how.
Full Code Example
Prerequisites
Make sure you have dependencies and developer environment set up!Prerequisites & Setup
Prerequisites & Setup
DependenciesAlternatives:Developer EnvironmentBy default, this guide uses Localnet.Alternative: Using DevnetFollow these steps to create an RPC Connection. Replace
<your-api-key> with your actual API key.Get your API key here, if you don’t have one yet.
Compress SPL Token Accounts
Compress entire SPL token account balance.compress-full-account.ts
Troubleshooting
Insufficient balance in token account
Insufficient balance in token account
The token account doesn’t have enough tokens for the operation.
Remaining amount exceeds balance
Remaining amount exceeds balance
The
remainingAmount parameter exceeds the current account balance.Advanced Configuration
Partial Account Compression
Partial Account Compression
Compress most tokens while leaving some in SPL format:
Compress Multiple Accounts
Compress Multiple Accounts
Compress several token accounts for the same mint: