A decentralized token swap program built on Solana using the Anchor framework. This program implements a simple automated market maker (AMM) with constant product formula for token swapping.
- Pool Initialization: Create liquidity pools for any SPL token pair
- Add Liquidity: Deposit tokens into existing pools
- Token Swapping: Swap between tokens using constant product formula (x × y = k)
- Slippage Protection: Minimum output amount protection for swaps
Before you begin, ensure you have the following installed:
- Rust (latest stable version)
- Solana CLI (v1.14.0 or higher)
- Anchor CLI (v0.31.1)
- Node.js (v16 or higher)
- Yarn or npm
-
Clone the repository:
git clone https://github.com/Hemanthghs/token-swap cd token-swap -
Install dependencies:
yarn install # or npm install
-
Set up Solana CLI for local development:
# Set to localhost for local testing solana config set --url localhost # Generate a new keypair (if you don't have one) solana-keygen new
-
Configure Anchor:
# Check your wallet address solana address # Update Anchor.toml with your program ID and wallet anchor keys list
-
Build the program:
anchor build
-
Get the program ID:
anchor keys list
-
Update the program ID in your code: (Important!)
- Update
declare_id!()inprograms/swap-2/src/lib.rs - Update
Anchor.tomlwith the correct program ID
- Update
-
Rebuild after updating program ID:
anchor build
-
Start the local Solana test validator:
# Start local validator in a new terminal window solana-test-validatorKeep this terminal open - the validator needs to run continuously.
-
In a new terminal, configure for localhost:
solana config set --url localhost # Check that you have SOL (local validator provides test SOL automatically) solana balance
-
Deploy the program to local testnet:
anchor deploy
-
Verify deployment:
solana program show <PROGRAM_ID>
-
Deploy your program (if not already deployed):
# In another terminal anchor deploy -
Compile TypeScript:
npx tsc
-
Run the client:
node app/client.js
Make sure your client connects to the local cluster:
// In your client code
import * as anchor from "@coral-xyz/anchor";
// Connect to local cluster
const connection = new anchor.web3.Connection("http://localhost:8899", "confirmed");
const provider = new anchor.AnchorProvider(connection, wallet, {});
anchor.setProvider(provider);Creates a new liquidity pool for a token pair.
Parameters:
mint_a: First token mintmint_b: Second token mint
Adds tokens to an existing pool.
Parameters:
amount_a: Amount of token A to addamount_b: Amount of token B to add
Swaps tokens using the constant product formula.
Parameters:
amount_in: Amount of input tokensminimum_amount_out: Minimum acceptable output amounta_to_b: Direction of swap (true for A→B, false for B→A)
authority: Pool creator's public keymint_a: First token mint addressmint_b: Second token mint addressbump: PDA bump seed