Skip to main content

How to Build a Constant-Product AMM on Solana with Anchor

Updated on
Nov 17, 2026

21 min read

Overview​

A newly listed stock needs buyers and sellers from its first minute. On a traditional exchange that takes a market maker, a firm that posts buy and sell prices and holds inventory, and a new listing with little trading struggles to attract one.

An automated market maker (AMM) replaces the market maker with a formula.

  • Liquidity providers (LPs) deposit two tokens into a pool and receive LP tokens for their share of it.
  • Anyone can trade one token for the other at once, at a price the formula sets from the pool's two balances.
  • Every trade pays a fee. Most of it stays in the pool for the LPs, and the rest goes to the AMM's admin.
  • The fee pays LPs for impermanent loss, the amount by which providing liquidity falls behind holding the same tokens when the price moves.

Orca and Raydium are popular AMMs on Solana, and AMMs are the standard venue for token launches. Building one shows how an onchain program (sometimes called a "smart contract") prices trades, tracks shares in a pool, splits fees, and rounds in its own favor.

This guide follows the Anchor 1 version of the program, in the anchor-v1 directory of finance/token-swap in Quicknode's Solana program examples repository. The same directory also has Anchor 2 (anchor) and Quasar (quasar) versions of the program.

TLDR
  • An AMM lets anyone trade two tokens at any time, at a price a formula sets from the pool's two balances instead of a market maker, and every trade moves that price
  • Liquidity providers deposit both tokens and earn most of every trading fee, and the admin earns the rest
  • The program defends small and empty pools against the known attacks on them
  • An LP falls behind just holding the tokens whenever the price moves, and comes out ahead only when fee income is larger than that gap
  • Build the program with Anchor, test it with LiteSVM, then deploy it to Solana devnet through a Quicknode endpoint

What You Will Do​

  • Follow one token launch through a constant-product pool, from pool creation to the last withdrawal
  • Learn how the program prices a swap, splits the fee between the LPs and the admin, and checks the pool after every trade
  • Calculate impermanent loss and compare it with an LP's fee income
  • See how the program defends against the empty-reserve drain, the inflation attack, and front-running at pool creation
  • Build the program, run its LiteSVM tests, and deploy it to Solana devnet through a Quicknode endpoint

What You Will Need​

See a Token Launch Through an AMM Pool Step by Step​

The pool in this guide trades ACME, the newly listed stock of a robotics startup, against USDC. Four people use it:

  • Maria runs the AMM and launches ACME. She has 1 SOL, 1,000 USDC, and 400 ACME of founder stock.
  • Alice adds liquidity to earn fees. She has 1 SOL, 1,000 USDC, and 100 ACME her employer granted her.
  • Bob buys ACME, then sells some back. He has 1 SOL and 1,000 USDC.
  • Carol buys ACME after Bob. She has 1 SOL and 1,000 USDC.

Maria also collects her share of the fees, and Alice withdraws at the end.

The animation below shows the tokens moving between the wallets and the pool at each step. Press Play to run it, step through it with Next and Back, and use Reset to start over.

Maria opens an ACME and USDC pool, Alice adds liquidity, Bob and Carol buy ACME, Bob sells some back, Maria claims her admin fees, and Alice withdraws her share of both tokens.

How Does a Constant-Product AMM Price a Swap?​

The pool holds two tokens, and its balances of them are called its reserves. Call the amount of the first X (here, ACME) and the amount of the second Y (USDC). K is X times Y. The program holds K fixed while it prices a trade. A buyer who adds USDC gets the amount of ACME that keeps X times Y at K, rounded down. Rearranged, that is the pricing formula:

output = taxed_input × other_reserve ÷ (this_reserve + taxed_input)

Here taxed_input is the trader's input minus the trading fee. this_reserve is the pool's balance of the token the trader puts in, and other_reserve is its balance of the token the trader gets out.

The spot price is Y ÷ X, and every trade moves it. Buying ACME takes ACME out of the pool and adds USDC, so the next buyer pays more. How far a trade moves the price is its price impact, and a trade that is large compared with the pool moves it a lot.

K changes between trades. It grows in two ways:

  • Liquidity deposits add more of both tokens at the same ratio.
  • Fees. The LPs' share of every trade's fee goes into the reserves, but the curve does not use it to price the trade. LPs collect it as part of their share when they withdraw.

Liquidity withdrawals shrink K, by the withdrawer's share of both reserves.

The constant-product curve: every point on the curve has the same product of ACME and USDC reserves, and a trade moves the pool along the curve

How Creating an AMM Pool Sets the Launch Price​

Maria earns the admin share of every trading fee. She also earns LP fees on her own deposit.

She runs initialize_config() with a fee of 30 basis points and an admin_share_bps of 1,667 basis points, about one sixth of each fee. Then she runs initialize_pool() for ACME/USDC. It creates the pool config, the LP mint, and the two vaults, and takes the pool's first deposit in the same instruction. Maria thinks a fair launch price is $2.25, so she deposits 400 ACME and 900 USDC. That is all her founder stock and 900 of her 1,000 USDC.

The config account is at a PDA with the seed "config". There is one config per deployed program, and it holds the settings every pool shares:

FieldPurpose
adminThe address that collects the admin share of fees, and the only one that can claim it
feeThe trading fee on each swap, in basis points
admin_share_bpsThe part of each fee that goes to the admin rather than the LPs, in basis points
bumpThe bump seed from deriving the config's address

initialize_config() rejects a fee of 10,000 basis points or more with InvalidFee, and an admin_share_bps of 10,000 basis points or more with AdminShareTooHigh.

The pool config account is at a PDA seeded by the config and the two mints, so there is one per trading pair. Creating it has one rule. mint_a must sort below mint_b, or creation fails with InvalidMintOrder. Without that rule, an (ACME, USDC) pool and a (USDC, ACME) pool could both exist and split the liquidity between them. In this pool ACME is token A and USDC is token B.

From programs/token-swap/src/instructions/initialize_pool.rs:

programs/token-swap/src/instructions/initialize_pool.rs
#[account(
init,
payer = payer,
space = PoolConfig::DISCRIMINATOR.len() + PoolConfig::INIT_SPACE,
seeds = [
config.key().as_ref(),
mint_a.key().as_ref(),
mint_b.key().as_ref(),
],
bump,
constraint = mint_a.key() < mint_b.key() @ AmmError::InvalidMintOrder,
)]
pub pool_config: Box<Account<'info, PoolConfig>>,

Two vaults, pool_a and pool_b, hold the pool's tokens. Their authority is the pool config PDA. Next to them is the LP mint (liquidity_provider_mint). Its tokens are the receipts LPs hold, and its mint authority is the same PDA. Only the program can sign as that PDA, so nobody else can move the vaults' tokens or mint LP tokens.

The pool config also has two counters, admin_fees_owed_a and admin_fees_owed_b. A swap never transfers the admin's share of the fee. The tokens stay in the vaults, and the counters record how much of them the admin is owed. So all the math that LPs depend on uses effective reserves: each vault's balance minus what the admin is owed from it.

From programs/token-swap/src/state/pool_config.rs:

programs/token-swap/src/state/pool_config.rs
#[account]
#[derive(Default, InitSpace)]
pub struct PoolConfig {
/// Address of the parent `Config` account this pool belongs to.
pub config: Pubkey,

/// Mint of token A.
pub mint_a: Pubkey,

/// Mint of token B.
pub mint_b: Pubkey,

/// Admin's accumulated fee claim on token A, in minor units. Sits
/// physically in `pool_a` but is excluded from the LP curve and from
/// LP-withdrawable amounts. Swept by `claim_admin_fees`.
pub admin_fees_owed_a: u64,

/// Admin's accumulated fee claim on token B, in minor units. Sits
/// physically in `pool_b` but is excluded from the LP curve and from
/// LP-withdrawable amounts. Swept by `claim_admin_fees`.
pub admin_fees_owed_b: u64,

/// Canonical bump for this PDA.
pub bump: u8,
}

The First Deposit Sets the Price​

initialize_pool() takes the first deposit in the same instruction that creates the pool, so nobody can deposit into an empty pool and set its price. A zero on either side fails with EmptyInitialDeposit, so no pool exists with an empty vault. After Maria's deposit, X = 400, Y = 900, and K = 360,000.

Maria's LP tokens are the integer square root of X times Y. initial_lp_amount() computes it with integer_sqrt(), which rounds down. A square root grows in proportion to the deposit. Doubling both tokens doubles the LP tokens, whatever the ratio. The square root of 360,000 is 600, so Maria receives 600 LP tokens minus MINIMUM_LIQUIDITY.

From programs/token-swap/src/liquidity.rs:

programs/token-swap/src/liquidity.rs
pub fn initial_lp_amount(amount_a: u64, amount_b: u64) -> Result<u64> {
let product = (amount_a as u128)
.checked_mul(amount_b as u128)
.ok_or(AmmError::MathOverflow)?;
let sqrt_product = u64::try_from(integer_sqrt(product)).map_err(|_| AmmError::MathOverflow)?;
if sqrt_product <= MINIMUM_LIQUIDITY {
return err!(AmmError::DepositTooSmall);
}
sqrt_product
.checked_sub(MINIMUM_LIQUIDITY)
.ok_or_else(|| error!(AmmError::MathOverflow))
}

MINIMUM_LIQUIDITY is 100 minor units of LP supply that are never minted to anyone. The LP mint has six decimals, so that is a ten-thousandth of one LP token, and the reserves it stands for stay in the pool for good. Many AMMs mint this amount to an address nobody can sign for. This program instead counts it in its own math, which defends against the inflation attack described under How the AMM Program Rejects Attacks.

deposit_and_mint_lp_tokens() moves the tokens into the vaults and mints Maria's LP tokens. Every later deposit ends with the same code.

Maria&#39;s first deposit: 400 ACME and 900 USDC move into the pool&#39;s vaults, and she receives 600 LP tokens minus the 100 minor unit floor

Why Adding Liquidity Does Not Move the Price​

Alice wants to earn fees on her ACME, so she becomes the second LP. A deposit cannot change the pool's ratio, so her 100 ACME must come with a matching 225 USDC (100 × $2.25).

deposit_liquidity() keeps the ratio by clamping. It treats amount_a and amount_b as the most Alice will put in. It works out how much token B her token A needs at the current effective reserves, and uses whichever pair of amounts fits inside what she offered. If the clamp rounds one side down to zero, the deposit fails with DepositAmountTooSmall. Asking to deposit more tokens than her token accounts hold fails with InsufficientBalance.

The program mints her LP tokens in proportion to her deposit. It computes her share against each side, takes the smaller, rounds it down, and checks it against her minimum_lp_tokens_out. The share is computed against the LP supply plus MINIMUM_LIQUIDITY, the same divisor the withdrawal uses.

From programs/token-swap/src/instructions/deposit_liquidity.rs:

programs/token-swap/src/instructions/deposit_liquidity.rs
let total_supply = (context.accounts.liquidity_provider_mint.supply as u128)
.checked_add(MINIMUM_LIQUIDITY as u128)
.ok_or(AmmError::MathOverflow)?;
let liquidity_from_a = (amount_a as u128)
.checked_mul(total_supply)
.ok_or(AmmError::MathOverflow)?
.checked_div(effective_pool_a as u128)
.ok_or(AmmError::MathOverflow)?;
let liquidity_from_b = (amount_b as u128)
.checked_mul(total_supply)
.ok_or(AmmError::MathOverflow)?
.checked_div(effective_pool_b as u128)
.ok_or(AmmError::MathOverflow)?;
let liquidity: u64 = u64::try_from(liquidity_from_a.min(liquidity_from_b))
.map_err(|_| AmmError::MathOverflow)?;

Alice's 100 ACME is a quarter of the 400 in the pool, so she receives a quarter of the 600 units of supply: 150 LP tokens. X is now 500, Y is 1,125, and K is 562,500. The price is still $2.25.

Alice&#39;s deposit: 100 ACME and 225 USDC move into the vaults at the pool&#39;s ratio, and she receives 150 LP tokens

How a Swap Moves the Price Along the Curve​

Bob expects ACME to rise. He runs swap_tokens() to spend 100 USDC on ACME. He passes input_is_token_a as false, because his input is USDC, and a min_output_amount as his slippage check. Three things happen, in this order.

The Fee Comes Out First​

30 basis points of 100 USDC is 30 cents. The admin's share, about 5 cents (1,667 basis points of the fee), is added to admin_fees_owed_b as Maria's claim. The other 25 cents stays in the pool, where it adds to the reserves behind every LP token. Bob's taxed input is 99.70 USDC. Both divisions round up.

From programs/token-swap/src/instructions/swap_tokens.rs:

programs/token-swap/src/instructions/swap_tokens.rs
let fee_amount = (input_amount as u128)
.checked_mul(config.fee as u128)
.ok_or(AmmError::MathOverflow)?
.div_ceil(BASIS_POINTS_DIVISOR as u128);
let admin_portion = fee_amount
.checked_mul(config.admin_share_bps as u128)
.ok_or(AmmError::MathOverflow)?
.div_ceil(BASIS_POINTS_DIVISOR as u128);

The Curve Prices the Trade​

The curve prices against Y plus the taxed input, 1,224.70, so X must fall to K ÷ 1,224.70, about 459.3. The vault receives all 100 USDC. Bob receives about 40.7 ACME. He paid an average of about $2.46 per ACME. The price was $2.25 before his trade and about $2.67 after it, because his own trade moved the price along the curve.

From programs/token-swap/src/instructions/swap_tokens.rs:

programs/token-swap/src/instructions/swap_tokens.rs
let (this_reserve, other_reserve) = if input_is_token_a {
(effective_pool_a, effective_pool_b)
} else {
(effective_pool_b, effective_pool_a)
};
let numerator = (taxed_input as u128)
.checked_mul(other_reserve as u128)
.ok_or(AmmError::MathOverflow)?;
let denominator = (this_reserve as u128)
.checked_add(taxed_input as u128)
.ok_or(AmmError::MathOverflow)?;
let output_u128 = numerator
.checked_div(denominator)
.ok_or(AmmError::MathOverflow)?;
let output: u64 = u64::try_from(output_u128).map_err(|_| AmmError::MathOverflow)?;

// Trader's slippage protection: the caller passes the lowest output
// they're willing to accept (computed offchain at quote time). If the
// pool shifted between quoting and landing, we revert rather than fill
// at the worse rate.
require!(output >= min_output_amount, AmmError::SlippageExceeded);

The Program Checks K Again After the Transfers​

After the transfers, the handler reloads both vault balances. It requires the effective product afterward to be at least the old one, and fails with InvariantViolated if it is not. The program's comment calls this the most important defensive check in the file. If a bug earlier in the handler overpays a trader, the product ends up below the old one and the swap fails. The check lets K grow, because the LP fee and rounding leftovers add to the reserves.

From programs/token-swap/src/instructions/swap_tokens.rs:

programs/token-swap/src/instructions/swap_tokens.rs
let new_invariant = (effective_pool_a_after as u128)
.checked_mul(effective_pool_b_after as u128)
.ok_or(AmmError::MathOverflow)?;
require!(new_invariant >= invariant, AmmError::InvariantViolated);

The 25 cents of LP fees that the curve left out of the price raised K once Bob's input landed, so K after his trade is about 562,615.

Bob&#39;s buy: 100 USDC moves into the USDC vault, about 40.7 ACME moves to Bob, and about 5 cents of admin fee accrues to the admin&#39;s USDC counter

Why the Next Buyer Pays a Higher Price​

Carol spends 50 USDC on ACME after Bob's trade. Her 50 USDC pays 15 cents of fees: about 2.5 cents for the admin and about 12.5 cents for the LPs. That leaves 49.85 USDC of taxed input. Bob's buy raised the spot price from $2.25 to $2.67, so the same formula gives Carol about 18 ACME, at an average near $2.78.

Carol&#39;s buy: 50 USDC moves into the USDC vault and about 18 ACME moves to Carol, at a higher average price than Bob paid

Which Token Pays the Fee When You Sell?​

Bob sells 20 of his 40.7 ACME. A sell is the same instruction with input_is_token_a set to true. The fee now comes out of his ACME input. It is 0.06 ACME, and 0.01 ACME of that is added to admin_fees_owed_a.

The curve prices against X plus the taxed 19.94 ACME, the vault receives all 20 ACME, and Y falls to keep the product. Bob receives about 55.11 USDC, an average near $2.76 per ACME against the $2.46 he paid. The spot price falls back to about $2.64. The admin's counters now hold claims in both tokens.

Bob&#39;s sell: 20 ACME moves into the ACME vault, about 55.11 USDC moves to Bob, and 0.01 ACME of admin fee accrues to the admin&#39;s ACME counter

How the AMM Admin Collects Fees​

Maria can run claim_admin_fees() at any time. It sets both owed counters to zero and transfers the owed amounts from the vaults to her token accounts, signed by the pool config PDA. The has_one = admin constraint on the config account rejects anyone else, which test_claim_admin_fees_rejects_non_admin checks. Claiming when nothing is owed fails with NothingToClaim. The claim makes one transfer per token, however many swaps added to the counters.

Maria claims her fees: the owed ACME and USDC move from the vaults to her token accounts, and both counters return to zero

How Withdrawing Liquidity Realizes Impermanent Loss​

Alice wants her tokens back. withdraw_liquidity() burns her LP tokens and pays her a share of both effective reserves in proportion to the LP tokens she burns. It divides by the LP supply plus MINIMUM_LIQUIDITY. It checks each side against her minimum_token_a_out and minimum_token_b_out.

From programs/token-swap/src/instructions/withdraw_liquidity.rs:

programs/token-swap/src/instructions/withdraw_liquidity.rs
let divisor = (context.accounts.liquidity_provider_mint.supply as u128)
.checked_add(MINIMUM_LIQUIDITY as u128)
.ok_or(AmmError::MathOverflow)?;
let amount_a_u128 = (amount as u128)
.checked_mul(effective_pool_a as u128)
.ok_or(AmmError::MathOverflow)?
.checked_div(divisor)
.ok_or(AmmError::MathOverflow)?;

The reserves include the share that backs the 100 unminted units, but the LP mint's supply does not count them. Leaving them out of the withdrawal divisor would overpay every withdrawer. Leaving them out of the deposit divisor would underpay every depositor.

Alice does not get back what she deposited. She put in 100 ACME and 225 USDC. Her 150 LP tokens are a fifth of the 750 units of supply, and the pool's mix has changed since she deposited. Her share is about 92.3 ACME and 244 USDC. At the current price, that is about $1.50 less than if she had kept her original tokens in her wallet.

Alice withdraws: her LP tokens are burned and about 92.3 ACME and 244 USDC move from the vaults to her token accounts

Impermanent Loss Grows With the Price Move​

That gap is impermanent loss. When the price of one token rises, traders buy it from the pool and pay in the other token. So a constant-product pool sells the token that is rising and collects the token that is falling, and an LP falls behind holding whenever the price moves.

An LP position earns fees from trading volume, and falls behind holding when the price moves in either direction. If fees are larger than the gap, providing liquidity wins. If the price moves far on little trading, holding wins. The loss is called "impermanent" because it only becomes final at withdrawal. If Alice had stayed in and ACME had gone back to $2.25, she would have had no loss.

Alice&#39;s LP position minus just holding, plotted against the ACME price at withdrawal, with and without $10 of fee income

The gap is small for ordinary moves. It grows with the square of the price change. A move of a quarter costs Alice $3 or $4 depending on the direction, and a doubling costs about $39. The LPs keep 25 of every 30 basis points of fee, and Alice holds a fifth of the pool, so she earns about 5 basis points of everything traded: $10 for every $20,000.

The table shows what Alice has at withdrawal minus what she would have had by holding, for her $450 position. The fee columns correspond to $20,000, $100,000, and $400,000 of trading. The last is about a year of trading half the pool's value every day.

ACME price at withdrawalHolding is worthNo fees$10 of fees$50 of fees$200 of fees
Halves to $1.13$338−$19−$9+$31+$181
Falls a quarter to $1.69$394−$4+$6+$46+$196
Unchanged at $2.25$450$0+$10+$50+$200
Rises a quarter to $2.81$506−$3+$7+$47+$197
Doubles to $4.50$675−$39−$29+$11+$161
Quadruples to $9.00$1,125−$225−$215−$175−$25

$10 of fees covers a move of a quarter in either direction. With no fee income, the solid curve in the figure, the LP is behind at every price except the one they deposited at. With a year of fees, the LP is still behind when the price quadruples. That move opens a $225 gap, which is more than $200 of fees.

Why Every Division Rounds in the Pool's Favor​

Every division between the pool and a trader or LP rounds in the pool's favor. Swap output, LP minting, and withdrawal amounts round down. The fee rounds up, so a trader never pays a minor unit less than the fee rate (test_swap_fee_rounds_up). The admin's share of the fee also rounds up, against the LPs. The leftover minor units stay in the reserves. If the program rounded the other way, a trader could take a minor unit from the pool on each of many small transactions.

Every multiplication runs in u128 before its division, and every step that can overflow uses a checked_* operation that fails with MathOverflow.

Four Invariants Every AMM Handler Keeps​

These hold before and after every instruction handler:

  • After every swap, effective X times effective Y is at least what it was before. The program checks this onchain after the transfers.
  • The admin's owed fees never take part in the math LPs depend on, which uses effective reserves.
  • LP tokens are a fixed-share claim. They are minted in proportion to the deposit and burned in proportion to the withdrawal.
  • Both effective reserves are positive from creation on. initialize_pool() funds them, a withdrawal leaves behind the share that backs the 100 unminted units, and a swap's output is always less than the reserve it comes from.

How the AMM Program Rejects Attacks​

The Empty-Reserve Drain​

If one reserve were zero, the swap formula would pay out the entire other reserve: output = input × other ÷ (0 + input) = other. The check on K would not catch it, because K before the trade would be 0, and any K afterward is at least 0.

So before any pricing runs, swap_tokens() and deposit_liquidity() check that both effective reserves are positive, and fail with EmptyPoolReserve if not. No instruction can put a pool in that state. test_pool_creation_cannot_be_front_run puts a pool there by hand, setting a vault's balance to zero, and checks that a deposit fails with EmptyPoolReserve.

The Inflation Attack​

In an inflation attack, an attacker opens a tiny pool, then sends tokens directly to its vaults. Each LP unit now stands for a large amount of tokens. A victim's later deposit rounds down to zero LP tokens, and the attacker's units redeem the victim's tokens.

The MINIMUM_LIQUIDITY floor makes the attack cost more than it can earn. The smallest pool an attacker can open leaves them 1 minor unit of LP out of 101 units of supply. To round a deposit down to zero, the attacker then has to send about 101 times that deposit to the vaults, and 100/101 of what they send belongs to units nobody can redeem. This only holds if both the deposit and the withdrawal divide by the supply plus the floor.

test_donation_cannot_round_a_later_deposit_to_zero runs the attack by sending 1,000,000 minor units to each vault. The victim's equal deposit is minted 100 minor units of LP, and the attacker's single unit redeems 9,950 minor units of token A, under 1% of what the attacker sent.

The Creator Sets the First Price​

Every later deposit is clamped to the creator's price, so nobody can deposit at a different ratio and move it. test_pool_creation_cannot_be_front_run opens Maria's pool and has a second wallet deposit 400 ACME against 100 USDC in the next transaction. The 100 USDC is the limiting side, so the program takes only 44.44 of the ACME, and the pool still prices ACME at $2.25 to the cent.

Slippage and Sandwiches​

Every trade, deposit, and withdrawal carries a minimum the caller supplies: min_output_amount, minimum_lp_tokens_out, minimum_token_a_out, and minimum_token_b_out. The tests check that each one fails with SlippageExceeded, DepositBelowMinimum, or WithdrawalBelowMinimum when the result is below it.

A zero minimum is allowed, and it is what a sandwich attacker hopes for. The attacker buys before the trade, lets it fill at the worse price, and sells after it. Compute the minimum from a fresh quote, less the slippage you accept.

Someone Else Creates the Pool First​

There is one pool per pair, and anyone can create it. The creator chooses nothing that lasts. The fee and the admin come from the config, and arbitrage corrects the first price. A launchpad that calls initialize_pool() for a pair that already has a pool fails, so it has to check for the pool and call deposit_liquidity() if it exists.

The Tests Cover Each Flow in Both Directions​

The tests in programs/token-swap/tests/test_swap.rs cover pool creation, deposits, swaps, withdrawals, and fees, and run each two-sided flow in both directions. test_invariant_holds_after_normal_swap and test_invariant_holds_after_b_to_a_swap check that K does not fall. test_lp_mint_after_swap_uses_effective_reserves checks that the admin's owed fees stay out of the LP math.

Run the Program and Its Tests​

Clone the examples repository and move into the Anchor 1 version of the program:

git clone https://github.com/quicknode/solana-program-examples
cd solana-program-examples/finance/token-swap/anchor-v1

The program needs the Anchor 1.2.1 CLI. Install and select it with avm:

avm install 1.2.1 && avm use 1.2.1

Anchor 1 requires the program ID in declare_id! to match the public key in the program's key pair file in target/deploy. Sync them, then build:

anchor keys sync
anchor build --arch v1
SBPF Version

Anchor 1.2.1 builds programs as SBPF v3 by default, but devnet and Surfpool can't deploy SBPF v3 programs yet. Pass --arch v1 to build an SBPF v1 program instead.

The tests are in programs/token-swap/tests/test_swap.rs. They run in LiteSVM, a Solana virtual machine that runs inside the test process, and load the built program from target/deploy/swap_example.so. Anchor.toml sets the cluster to localnet and the test script to cargo test, so anchor test starts a Surfpool local validator and then runs the tests. anchor test has no --arch option, so pass --skip-build to keep it from rebuilding the program as SBPF v3:

anchor test --skip-build

Each test named in this guide appears in the output with ok when it passes.

Deploy the Program to Devnet​

Point the Solana CLI at your Quicknode devnet endpoint:

solana config set --url <your Quicknode devnet URL>

The wallet in Anchor.toml is ~/.config/solana/id.json, and it pays for the deployment. Deploying a program costs the rent for its account, so fund that wallet with devnet SOL first. A Complete Guide to Airdropping Test SOL on Solana lists the ways to get some. Then deploy through the same endpoint. anchor program deploy deploys swap_example, the workspace's only program, with the key pair in target/deploy/swap_example-keypair.json, and uploads its IDL:

anchor program deploy --provider.cluster <your Quicknode devnet URL>

Use Quicknode with the Token Swap AMM​

  • Route swaps instead of building a pool. An application that only lets users trade one token for another does not need its own pool. The Swap API's /quote and /swap endpoints route each trade for the best price across existing Solana DEXs, and How to Use Jupiter API to Create a Solana Trading Bot builds a client for them. Run a pool like this one when you are the venue, for example when a token such as ACME has no market yet, or when you want to earn the admin share of every fee.
  • Stream the pool's price and fees. Subscribe to pool_a, pool_b, and the pool config account over Solana gRPC, and subtract admin_fees_owed_a and admin_fees_owed_b from the vault balances to get the effective reserves. A dashboard can show the spot price after every swap, and Maria can run a bot that calls claim_admin_fees() once the owed amounts pass a threshold.
  • Land swaps while their quote is fresh. A trader's min_output_amount comes from the pool's reserves at quote time, and a swap that lands slots later is more likely to fail with SlippageExceeded. Estimate a competitive priority fee with qn_estimatePriorityFees, as Understand Solana Priority Fees shows, so the transaction is included sooner when the network is busy.

Next Steps​

  • Compare the Anchor 2 (anchor) and Quasar (quasar) versions of finance/token-swap with the Anchor 1 version this guide follows, to see how the same accounts, checks, and math carry over between frameworks.
  • Apply the same writing and program rules to your own Solana finance work with the solana-finance-claude-plugin.

Wrapping Up​

You followed one token launch from Maria's first deposit, which set the price, to Alice's withdrawal, which realized her impermanent loss. swap_tokens() takes its fee first, prices against effective reserves, and checks K again after the transfers. The MINIMUM_LIQUIDITY floor stops the inflation attack, and the EmptyPoolReserve check stops the empty-reserve drain. You also built the program, ran its LiteSVM tests, and deployed your own copy to devnet through Quicknode.

Resources​

Frequently Asked Questions​

How does a constant-product AMM price a swap on Solana?

It keeps the product of its two reserves fixed while it prices the trade. The output is the input minus the fee, times the reserve of the token going out, divided by the reserve of the token coming in plus the input minus the fee. The result is rounded down.

How many LP tokens does the first deposit into a pool receive?

The integer square root of the two deposit amounts multiplied together, minus 100 minor units that are never minted to anyone. A deposit of 400 ACME and 900 USDC receives 600 LP tokens minus those 100 minor units.

What is impermanent loss for a liquidity provider?

It is the amount by which a liquidity provider's share of the pool falls behind just holding the tokens they deposited, after the price moves. It grows with the square of the price change, and it only becomes final when they withdraw.

How does an AMM program stop the inflation attack?

This program counts 100 minor units of LP supply that nobody ever receives when it mints and burns LP tokens. To round a later deposit down to zero, an attacker then has to send the pool about 101 times that deposit, and most of what they send belongs to units nobody can redeem.

Where does the admin's share of the trading fee go?

It stays in the pool's vaults, and the admin_fees_owed_a and admin_fees_owed_b counters on the pool config account record how much the admin is owed. The admin collects it with claim_admin_fees. The math LPs depend on leaves it out by using effective reserves.

Should I build my own AMM or route swaps through an aggregator?

Route swaps through an aggregator such as the Quicknode Swap API when your application only needs users to trade tokens that already have markets. Build a pool when you are the venue, for example when a token has no market yet or you want to earn the admin share of fees.