GitHub - codingirldev/AMM

๐Ÿš€ Solana AMM (Automated Market Maker)

A production-ready decentralized exchange (DEX) built on Solana blockchain featuring support for both SPL Token and Token-2022 standards. This AMM implements the battle-tested constant product formula (xร—y=k) with configurable fees, comprehensive security features, and a modern Next.js frontend.

Solana Anchor Next.js

โœจ Key Features

  • ๐Ÿ”„ Dual Token Standard Support - Compatible with SPL Token and Token-2022
  • ๐Ÿ“Š Constant Product Formula - Proven xร—y=k mathematical model for price discovery
  • โš™๏ธ Configurable Fees - Flexible basis points system (0-10000 BP)
  • ๐Ÿ›ก๏ธ Slippage Protection - User-defined minimum output validation
  • ๐Ÿ” Security First - Program Derived Addresses and checked arithmetic
  • ๐ŸŽจ Modern Frontend - React-based UI with wallet integration
  • ๐Ÿงช Comprehensive Testing - Full test coverage for all operations

๐Ÿ—๏ธ System Architecture

Core Components

Component Description
Pool Main state account storing token mints, vaults, and configuration
LP Mint ERC20-like tokens representing liquidity provider ownership
Token Vaults Associated token accounts holding the actual token reserves

Program Derived Addresses (PDAs)

// Pool account derivation
Pool PDA: ["pool", token_a_mint, token_b_mint]

// LP mint derivation  
LP Mint PDA: ["lp_mint", pool_account_key]

Available Instructions

  1. ๐Ÿ Initialize Pool - Create new token trading pairs
  2. ๐Ÿ’ง Add Liquidity - Deposit tokens and receive LP tokens
  3. ๐Ÿ’ธ Remove Liquidity - Burn LP tokens to withdraw underlying assets
  4. ๐Ÿ”„ Swap Aโ†’B - Exchange token A for token B with fee
  5. ๐Ÿ”„ Swap Bโ†’A - Exchange token B for token A with fee

๐Ÿš€ Getting Started

Prerequisites

Ensure you have the following installed:

  • Node.js v18 or higher
  • Rust and Anchor CLI v0.31.1
  • Solana CLI v1.18+
  • pnpm package manager

Installation & Setup

# Clone the repository
git clone https://github.com/Shradhesh71/AMM.git
cd AMM

# Install dependencies
pnpm install

# Build the Anchor program
pnpm anchor-build

# Generate program types
pnpm anchor build

# Run comprehensive tests
pnpm anchor-test

Local Development Environment

# Terminal 1: Start Solana test validator
solana-test-validator

# Terminal 2: Deploy program locally
pnpm anchor deploy

# Terminal 3: Start the frontend development server
pnpm dev

The frontend will be available at http://localhost:3000

๐Ÿ“Š AMM Mathematics

Liquidity Provision Formulas

Initial Liquidity (Bootstrap):

LP_tokens = โˆš(amount_a ร— amount_b)

Subsequent Liquidity (Proportional):

LP_tokens = min(
  (amount_a ร— current_lp_supply) / reserve_a,
  (amount_b ร— current_lp_supply) / reserve_b
)

Trading Formulas

Constant Product Invariant:

reserve_a ร— reserve_b = k (constant before and after trade)

Swap Output Calculation:

amount_in_after_fee = amount_in ร— (10000 - fee_rate) / 10000
amount_out = (reserve_out ร— amount_in_after_fee) / (reserve_in + amount_in_after_fee)

๐Ÿงช Testing & Quality Assurance

Test Coverage

  • โœ… Pool Initialization - Both SPL Token and Token-2022 pools
  • โœ… Liquidity Management - Add/remove operations with proper LP calculations
  • โœ… Token Swapping - Bidirectional swaps with fee validation
  • โœ… Security Checks - PDA validation, slippage protection, arithmetic safety
  • โœ… Edge Cases - Zero amounts, insufficient liquidity, overflow protection

Running Tests

# Run all tests with coverage
pnpm anchor-test

# Run tests with detailed output
cd anchor && anchor test --skip-lint --verbose

# Run specific test suite
cd anchor && anchor test --skip-lint --grep "AMM"

๐Ÿš€ Deployment Guide

Devnet Deployment

# Set cluster to devnet
anchor config set --provider.cluster devnet

# Ensure you have devnet SOL
solana airdrop 2 --url devnet

# Deploy to devnet
anchor deploy --provider.cluster devnet

โš™๏ธ Configuration Options

Fee Structure

pub struct Pool {
    pub fee_rate: u16, // Basis points (100 = 1%, 10000 = 100%)
    // ... other fields
}

Recommended Fee Ranges:

  • Low-volume pairs: 300 BP (3%)
  • Stablecoin pairs: 25-50 BP (0.25%-0.5%)
  • Volatile pairs: 100-300 BP (1%-3%)

๐Ÿ›ก๏ธ Security Features

Feature Implementation
PDA Security All accounts use cryptographically secure Program Derived Addresses
Arithmetic Safety Checked operations prevent integer overflow/underflow
Access Control Proper authority validation for all sensitive operations
Slippage Protection User-defined minimum output amounts prevent MEV attacks
State Validation Comprehensive pool state and balance checks

๐Ÿ“ Project Structure

anchor-AMM/
โ”œโ”€โ”€ anchor/                           # Solana program
โ”‚   โ”œโ”€โ”€ programs/amm/src/
โ”‚   โ”‚   โ”œโ”€โ”€ lib.rs                   # Program entry point
โ”‚   โ”‚   โ”œโ”€โ”€ states.rs                # Pool state definition
โ”‚   โ”‚   โ”œโ”€โ”€ errors.rs                # Custom error types
โ”‚   โ”‚   โ””โ”€โ”€ instructions/            # Instruction handlers
โ”‚   โ”‚       โ”œโ”€โ”€ initialize_pool.rs   # Pool creation logic
โ”‚   โ”‚       โ”œโ”€โ”€ add_liquidity.rs     # Liquidity provision
โ”‚   โ”‚       โ”œโ”€โ”€ remove_liquidity.rs  # Liquidity withdrawal
โ”‚   โ”‚       โ”œโ”€โ”€ swap.rs              # Token swapping logic
โ”‚   โ”‚       โ””โ”€โ”€ helper.rs            # Utility functions
โ”‚   โ””โ”€โ”€ tests/                       # Comprehensive test suite
โ”œโ”€โ”€ src/                             # Next.js frontend
โ”‚   โ”œโ”€โ”€ app/                         # App router (Next.js 14)
โ”‚   โ”œโ”€โ”€ components/                  # React components
โ”‚   โ”‚   โ”œโ”€โ”€ ui/                      # Reusable UI components
โ”‚   โ”‚   โ”œโ”€โ”€ solana/                  # Solana-specific components
โ”‚   โ”‚   โ””โ”€โ”€ amm/                     # AMM-specific components
โ”‚   โ””โ”€โ”€ lib/                         # Utility functions
โ”œโ”€โ”€ public/                          # Static assets
โ””โ”€โ”€ package.json                     # Dependencies and scripts

๐Ÿค Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please ensure all tests pass and follow the existing code style.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.