Consolidate multiple compressed token accounts of the same mint into a single account to reduce fragmentation.
The mergeTokenAccounts() function consolidates multiple compressed accounts of the same mint into a single compressed account.The function
consumes multiple compressed token accounts (up to 8 accounts), and
creates a single output compressed token account with combined balance for the owner.
State trees where compressed account’s are stored, are append only. mergeTokenAccounts() reduces account fragmentation to simplify balance calculations from getCompressedTokenAccountsByOwner.
Report incorrect code
Copy
Ask AI
// Combines multiple compressed token accounts into single compressed accountconst transactionSignature = await mergeTokenAccounts( rpc, payer, mint, // SPL mint with token pool for compression owner,);
In the code examples, use createRpc(RPC_URL) with the devnet URL.
Report incorrect code
Copy
Ask AI
import "dotenv/config";import { Keypair } from "@solana/web3.js";import { createRpc, bn } from "@lightprotocol/stateless.js";import { createMint, mintTo, mergeTokenAccounts } from "@lightprotocol/compressed-token";import { homedir } from "os";import { readFileSync } from "fs";// devnet:const RPC_URL = `https://devnet.helius-rpc.com?api-key=${process.env.API_KEY!}`;// localnet:// const RPC_URL = undefined;const payer = Keypair.fromSecretKey( new Uint8Array( JSON.parse(readFileSync(`${homedir()}/.config/solana/id.json`, "utf8")) ));(async function () { // devnet: const rpc = createRpc(RPC_URL); // localnet: // const rpc = createRpc(); // Setup: Create mint and mint multiple times to create multiple accounts const { mint } = await createMint(rpc, payer, payer.publicKey, 9); const owner = Keypair.generate(); await mintTo(rpc, payer, mint, owner.publicKey, payer, bn(100_000_000)); await mintTo(rpc, payer, mint, owner.publicKey, payer, bn(200_000_000)); await mintTo(rpc, payer, mint, owner.publicKey, payer, bn(300_000_000)); // Merge all accounts for owner const tx = await mergeTokenAccounts(rpc, payer, mint, owner); console.log("Mint:", mint.toBase58()); console.log("Tx:", tx);})();
Before we merge compressed accounts, we need
Multiple compressed token accounts of the same mint owned by the same wallet, and
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 via createTokenPool().