Note
This is the Anchor v2 copy of this example. Every anchor command on this page
needs the v2 CLI: cargo install anchor-cli --version 2.0.0-rc.1 --locked (avm has
no prebuilt binary for this pre-release). The Anchor v1 version of this example is in
../anchor-v1.
A constant-product AMM (automated market maker) on Solana: create pools, deposit liquidity, swap with slippage guards, and withdraw. This is the exchange design behind Solana venues like Raydium and Orca.
See also: Token Swap overview and the repository catalog.
- Liquidity pool PDA
- LP tokens and swap invariant
- See finance/token-swap/README.md for the full walkthrough
From this directory (finance/token-swap/anchor/):
anchor buildPrerequisites: Agave CLI (version in Anchor.toml [toolchain]), Anchor.
Tests run in-process with LiteSVM. No local validator.
anchor testThis runs cargo test as configured in Anchor.toml. Tests call instruction handlers and check onchain state.
Read the program programs/ source and Anchor.toml for deployed program IDs. For deployment, use anchor build && anchor deploy against your target cluster.
An automated market maker replaces the order book with a liquidity pool: anyone can open a pool with initialize_pool, which takes the creator's first deposit of both tokens and so sets the pool's opening price; later providers add to it with deposit_liquidity, and traders trade against it with swap_tokens. Prices come from the constant-product invariant on the pool's balances, and liquidity providers earn a share of trading fees. Solana exchanges like Raydium and Orca use this design.
swap_tokens takes a min_output_amount guard: if the pool's balances move so the trade would return less than that minimum, the transaction fails instead of filling at a worse price.
The example-level Token Swap overview covers the pool math, LP tokens, and lifecycle; this page covers the Anchor build and test commands. The arithmetic has Kani model checks in ../kani-proofs/.