Decentralized Exchange (DEX) Documentation
Abstract
This document describes our decentralized exchange (DEX) protocol built on Solana devnet using the Anchor framework for on-chain programs and React for the front-end. Our design leverages an Automated Market Maker (AMM) model where the pool invariant is maintained as
In addition to these functionalities, our system integrates Solana Pay to enable seamless and secure on-chain payments. Solana Pay allows users to initiate transactions through QR codes or clickable links that pre-fill payment details—including recipient address, amount, and a unique transaction reference—thus eliminating intermediaries and reducing fees. By combining our AMM-based DEX with Solana Pay, our protocol not only supports efficient token trading but also provides a robust payment layer suitable for real-world commerce, digital goods, and service-based platforms.
x · y = k. The core features include viewing pools, creating liquidity pools, adding liquidity, removing liquidity, and performing token swaps with precise input/output calculations and rigorous security measures.In addition to these functionalities, our system integrates Solana Pay to enable seamless and secure on-chain payments. Solana Pay allows users to initiate transactions through QR codes or clickable links that pre-fill payment details—including recipient address, amount, and a unique transaction reference—thus eliminating intermediaries and reducing fees. By combining our AMM-based DEX with Solana Pay, our protocol not only supports efficient token trading but also provides a robust payment layer suitable for real-world commerce, digital goods, and service-based platforms.
Introduction
Decentralized exchanges (DEXs) enable trustless token trading without relying on centralized intermediaries. This project implements an AMM-based DEX on Solana, where each pool is formed by two unique tokens under a specific fee tier. No initial liquidity is necessary to create a pool; instead, traders pay a fee to initialize it. Subsequent liquidity additions, removals, and swaps maintain the constant product invariant.
Protocol Overview
The protocol is divided into five main modules:
- View Pools: Displays current trading pools (showing Mint-A/Mint-B addresses, fees, liquidity, and total deposits).
- Create Pools: Allows traders to create pools with two unique tokens (Mint-A must be greater than Mint-B) and includes a fee payment to the pool admin.
- Add Liquidity: Lets liquidity providers deposit tokens into a pool. Deposits can be in unequal ratios—in which case the protocol swaps the excess via an external DEX (e.g., Raydium) to maintain balance.
- Remove Liquidity: Liquidity providers burn their liquidity tokens (shares) to reclaim underlying tokens and receive swap fees accrued.
- Swap Tokens: Users can swap tokens via exact input or exact output methods. The protocol calculates fees, enforces slippage tolerance, and adjusts amounts accordingly.
Using Solana Pay for Seamless Blockchain Transactions
In our project, we integrated Solana Pay to handle digital payments directly on the Solana blockchain. Solana Pay is a decentralized, open-source protocol designed for instant, fee-efficient transactions. By using this protocol, we eliminate the need for intermediaries such as traditional payment gateways.
When a user initiates a transaction (e.g., purchasing a service or donating funds), our frontend generates a Solana Pay URL containing:
- The recipient’s wallet address
- The exact amount to be paid
- A unique reference for the transaction
- Optional metadata such as labels or memos
This URL is then presented to the user as a QR code or as a clickable link. The user can scan it using their Phantom or Solflare wallet, which opens a pre-filled transaction that they can confirm. Once confirmed, the transaction is executed directly on-chain.
We also use the reference key mechanism to track transactions and confirm payment success using a backend cron job or webhook that listens for matching transactions on-chain.
This approach provides:
- 🔐 Secure, trustless payments
- ⚡️ Instant settlement
- 🧾 Easy tracking of payment status
- 💸 Minimal transaction fees (fractions of a cent)
By using Solana Pay, we provide a robust payment layer for our decentralized application, making it suitable for real-world commerce, digital goods, and service-based platforms.
Detailed Functional Descriptions
Helper Functions
integer_sqrt: This function computes the square root of a given number (truncated to an integer) using floating‑point arithmetic. For instance,
integer_sqrt(5000) returns approximately 70 since √5000 ≈ 70.71.get_price_percentage_changed: This function calculates the percentage change in price before and after a swap, ensuring that the slippage remains within acceptable limits. It works by taking the difference between the products of pool reserves pre- and post-swap, scaling by a precision constant.
fn get_price_percentage_changed(
before_amount_a: u64,
before_amount_b: u64,
after_amount_a: u64,
after_amount_b: u64,
) -> u64 {
let numerator = ((before_amount_a * after_amount_b) as i64 -
(before_amount_b * after_amount_a) as i64).abs() as u64;
let denominator = before_amount_b * after_amount_a;
(numerator * PRECISION) / denominator
}Here, if
PRECISION is set to 10000, then a 1% change is represented by approximately 100 on this scale.Security Considerations
1. Signer Verification: Critical operations (e.g., pool creation, liquidity deposit, swapping) require that the correct account signs the transaction. This measure prevents unauthorized actions. In our protocol, the payer (or wallet) must sign every transaction to ensure that only the owner approves token transfers.
2. PDA Derivation: All Program Derived Addresses (PDAs) for pools, liquidity tokens, and token accounts are derived using fixed seeds—including fee values, token mints, and other constants. This ensures that account addresses are unique and tamper-resistant. Using consistent seeds on both the client and on‑chain program prevents malicious actors from spoofing addresses.
3. Fee and Slippage Checks: The protocol rigorously enforces that the fee tier specified by the user matches the pool’s stored fee value. Additionally, slippage tolerance parameters (e.g.,
delta_price_change) are validated to ensure that the swap occurs within acceptable price bounds. These checks help protect against market manipulation and unexpected price fluctuations.4. Minimum Liquidity Protection: When a pool is created, the protocol mints a baseline amount of liquidity tokens (e.g., 100 tokens) to protect against inflation attacks. This guarantees that new liquidity deposits cannot be exploited by depositing extremely small amounts.
5. Safe CPI Calls: All token operations, such as transfers, minting, and burning, are performed through Anchor’s secure Cross-Program Invocation (CPI) calls. These functions perform thorough account validations and ensure proper permission checks, reducing the risk of execution errors or malicious activity.
6. Input Validation & Decimal Conversion: The program validates that all numerical inputs are non-zero and that token ordering is correct before processing any transaction. On the client side, user-friendly decimal values are accurately converted into base units using the token’s decimals (e.g., converting 1.5 tokens to 1,500,000 base units for tokens with 6 decimals). This prevents rounding errors and ensures consistency between user inputs and on-chain values.
7. Solana Pay Integration Security: Solana Pay is used to initiate transactions seamlessly via QR codes or pre-filled links. When using Solana Pay, a unique reference is generated to track each transaction, ensuring that only authorized payments are executed. This mechanism provides an extra layer of security by relying on the users wallet (which performs signature verification) and prevents replay attacks or unauthorized transaction execution.
8. Robust Error Handling and Logging: All operations include comprehensive error handling and logging. This makes it easier to detect and recover from any unusual behavior or attack attempts, ensuring that transactions that do not meet protocol requirements are safely reverted.
Together, these security measures—spanning account validation, deterministic address derivation, fee and slippage enforcement, proper decimal management, secure CPI interactions, and robust monitoring via Solana Pay—ensure that our decentralized exchange protocol operates securely and reliably on the Solana devnet.