compress() and decompress() functions convert SPL tokens between compressed and regular format.
Before we convert formats, we need:
- An SPL mint with a token pool for compression. This token pool can be created for new SPL mints via
createMint()or added to existing SPL mints viacreateTokenPool(). - For
compress()SPL tokens in an Associated Token Account, or - For
decompress()compressed token accounts with sufficient balance.
Function Difference and Best Practice:
compress(amount, sourceTokenAccount, toAddress)compresses specific amounts from source to a specified recipient. Use for transfers and precise amounts.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. Here is how.
Full Code Example
Prerequisites
Make sure you have dependencies and developer environment set up!Prerequisites & Setup
Prerequisites & Setup
DependenciesAlternatives:Alternative: Using DevnetFollow these steps to create an RPC Connection. Replace
Developer Environment
By default, this guide uses Localnet.<your_api_key> with your API key before running.Get your API key here, if you don’t have one yet.
Compress / Decompress Tokens
- Compress Tokens
- Compress and Decompress
Compress SPL tokens to compressed format.
compress-tokens.ts
Troubleshooting
Insufficient balance between decompress and compress
Insufficient balance between decompress and compress
Check your balances before operations:
Invalid owner
Invalid owner
Ensure the signer owns the tokens being decompressed/compressed:
Advanced Configurations
Compress to Different Owner
Compress to Different Owner
Compress tokens directly to someone else:
Batch Operations
Batch Operations
Compress multiple token accounts:
Decompress with Delegate Authority
Decompress with Delegate Authority