Skip to content

AMM Swaps & Liquidity

D9Amm provides a constant-product pool between native D9 and registered USDT. Always perform quote and slippage calculations with bigint integer math.

Query all values from the same finalized block:

Storage Returns
D9Amm::D9Reserve D9 pool reserve (12 decimals)
D9Amm::UsdtReserve USDT pool reserve (6 decimals)
D9Amm::FeePercent Swap fee in basis points (30 = 0.30%)
D9Amm::TotalLpTokens Total LP shares issued
D9Amm::LiquidityProviders(account) LP shares owned by account

For input amountIn, reserves reserveIn and reserveOut, and fee feeBps (in basis points):

function quoteSwapOutput(
amountIn: bigint,
reserveIn: bigint,
reserveOut: bigint,
feeBps: bigint,
): bigint {
const weightedInput = amountIn * (10000n - feeBps);
return (weightedInput * reserveOut) / (reserveIn * 10000n + weightedInput);
}

Block the swap in your UI if either reserve would fall below 600,000 whole units, as the chain rejects swaps breaching the reserve floor:

  • D9 floor: 600000000000000000 raw units (12 decimals)
  • USDT floor: 600000000000 raw units (6 decimals)
D9Amm::swap(direction, amount_in, min_out)
Parameter Description
direction SwapDirection::D9ToUsdt or SwapDirection::UsdtToD9
amount_in Input amount in raw units
min_out Minimum acceptable output after applying user slippage tolerance
// Swap 10 D9 to USDT with 1% slippage tolerance
const quotedUsdt = quoteSwapOutput(10000000000000n, d9Reserve, usdtReserve, 30n);
const minUsdtOut = (quotedUsdt * 99n) / 100n;
const tx = chain.api.tx.D9Amm.swap({
direction: { type: "D9ToUsdt" },
amount_in: 10000000000000n,
min_out: minUsdtOut,
});
Call Purpose
D9Amm::add_liquidity(d9_amount, usdt_amount, min_lp_out) Deposit D9 and USDT proportionally and mint LP shares.
D9Amm::remove_liquidity(lp_amount, min_d9_out, min_usdt_out) Burn LP shares and withdraw D9 and USDT proportionally.

Derive min_lp_out, min_d9_out, and min_usdt_out from current pool reserves minus the user’s slippage tolerance. After finalization, query D9Amm::LiquidityProviders(account) to refresh the user’s LP balance.