Decentralized Exchange — Full Documentation

A complete, production-ready DEX built on PancakeSwap V2. Includes an AMM exchange, yield farms, staking pools, lottery, and price prediction — deployable on any EVM-compatible blockchain.

Solidity Next.js EVM Compatible

What Is This

This is a fully functional decentralized exchange (DEX) forked from PancakeSwap V2. It includes the complete smart contract suite and a working frontend — not a template or mockup.

All contracts are compiled, tested, and deploy from a single Hardhat project. The frontend connects to your deployed contracts automatically via configuration scripts.

What you get

Smart contracts (Solidity) + Frontend (Next.js/React) + Deployment scripts + SDK patching — everything needed to launch a DEX on your chosen EVM chain.

What This Is NOT

  • Not a SaaS platform — you deploy and own everything
  • Not connected to PancakeSwap — fully independent after deployment
  • Does not include a backend API server — the NFT marketplace page requires one and is not functional without it
  • Does not include a SubGraph indexer — some analytics features (info pages) depend on The Graph and are disabled

Features Included

Token Swap (AMM)

Automated Market Maker with constant product formula. Swap any ERC-20 token pair with 0.2% trading fee. Supports multi-hop routing.

Liquidity Pools

Add/remove liquidity for any token pair. LP tokens represent your pool share and earn swap fees automatically.

🌱

Yield Farms

Stake LP tokens in MasterChef farms to earn your native token. Configurable allocation points per farm and emission rate.

💰

Staking Pools (Syrup)

Single-token staking via SmartChef contracts. Stake your main token, earn other tokens. Each pool is an independent contract.

🎲

Lottery

On-chain lottery with configurable ticket price, prize breakdown, and treasury fee. Uses a random number generator contract.

📈

Price Prediction

Binary price prediction game (Bull/Bear) with configurable round intervals. Uses a Chainlink-compatible oracle for price feeds.

Not included / requires additional work

NFT Marketplace — the page exists but requires a custom backend API and SubGraph indexer to display collections. An ERC-721 contract is included for minting NFTs.
Info/Analytics — requires The Graph SubGraph deployment (not included).
IFO (Initial Farm Offering) — contracts not included.
Voting/Governance — requires a Snapshot-style backend.

Architecture

dex-contracts/ — Hardhat project (all Solidity contracts + deploy scripts)
  ├── contracts/core/ — Factory, Pair (AMM core)
  ├── contracts/periphery/ — Router, Library (swap routing)
  ├── contracts/farm/ — MasterChef, CakeToken, SyrupBar, SmartChef
  ├── contracts/lottery/ — PancakeSwapLottery, RandomNumberGenerator
  ├── contracts/prediction/ — PancakePredictionV2, MockAggregator
  ├── contracts/nft/ — FireNFT (ERC-721)
  ├── contracts/utils/ — WBNB, Multicall2, mock BEP20 tokens
  ├── scripts/ — deploy.js, setup-testnet.js, update-frontend.js, patch-sdk.js
  └── deployed-addresses.json — all contract addresses after deployment

fireswap-frontend/ — Next.js application (React frontend)
  ├── src/config/constants/ — tokens, contracts, farms, pools config
  ├── src/views/ — page components (Swap, Farms, Pools, Lottery, etc.)
  ├── src/state/ — Redux state management
  ├── packages/uikit/ — UI component library
  └── public/ — static assets, token icons

How It Works

  1. Deploy contracts to your target blockchain using Hardhat
  2. The deploy script saves all contract addresses to deployed-addresses.json
  3. update-frontend.js reads those addresses and patches the frontend config files
  4. patch-sdk.js patches the @pancakeswap/sdk with your factory address and init code hash
  5. The frontend reads chain ID from .env.development and connects to your contracts

Requirements

ToolVersionPurpose
Node.js16.x or 18.xRuntime for Hardhat and Next.js
npm8+Package manager for dex-contracts
Yarn1.x (classic)Package manager for frontend
GitAny recentVersion control

For Deployment to a Live Network

  • Private key of a funded wallet (deployer account)
  • RPC endpoint for your target chain (Alchemy, Infura, QuickNode, or public RPC)
  • Native gas tokens — deployment costs approximately 0.15–0.3 of the chain's native token (varies by network)

Project Structure

Install Dependencies

# Smart contracts
cd dex-contracts
npm install

# Frontend
cd ../fireswap-frontend
yarn install

Deploy Smart Contracts

1

Configure your network

Create a .env file in the dex-contracts/ directory:

# dex-contracts/.env
DEPLOYER_PRIVATE_KEY=your_private_key_here

# Pick your network RPC:
BSC_TESTNET_RPC_URL=https://data-seed-prebsc-1-s1.bnbchain.org:8545
# SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY

To add a new network, edit hardhat.config.js and add an entry under networks.

2

Deploy core contracts

This deploys: WBNB, Factory, Router, your Token, SyrupBar, MasterChef, Multicall2, mock stablecoins, and creates initial LP pairs with liquidity.

cd dex-contracts
npx hardhat run scripts/deploy.js --network bscTestnet
First-time deployment

On the first run, the script detects a mismatched INIT_CODE_HASH in PancakeLibrary.sol, auto-patches it, and exits. Run the command again to complete deployment.

3

Deploy additional features (optional)

Run any combination of these scripts after the core deployment:

# Add liquidity to pools, deploy lottery
npx hardhat run scripts/setup-testnet.js --network bscTestnet

# Deploy syrup staking pools
npx hardhat run scripts/deploy-pools.js --network bscTestnet

# Deploy price prediction game
npx hardhat run scripts/deploy-prediction.js --network bscTestnet

# Deploy NFT collection
npx hardhat run scripts/deploy-nft.js --network bscTestnet
4

Verify deployment

All deployed addresses are saved to dex-contracts/deployed-addresses.json. You can verify contracts on your chain's block explorer.

Setup Frontend

1

Patch frontend configuration

This reads deployed-addresses.json and automatically updates all frontend config files (contracts, tokens, chain ID, RPC URLs).

cd dex-contracts
node scripts/update-frontend.js
2

Patch the SDK

The @pancakeswap/sdk has hardcoded factory addresses and init code hashes. This script patches them to match your deployment.

node scripts/patch-sdk.js
3

Start the development server

cd ../fireswap-frontend
yarn dev

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

4

Build for production

yarn build
# Deploy the 'out' or '.next' directory to Vercel, Netlify, or any static host

Change the Main Token

The default governance/reward token is called CakeToken in the contracts. To rebrand it (e.g., to "FIRE", "MYTOKEN", etc.), update these locations:

1. Smart Contract — Token Name & Symbol

Edit dex-contracts/contracts/farm/CakeToken.sol:

// In the constructor or token metadata:
constructor() BEP20('Your Token Name', 'SYMBOL') {
    // ...
}

Redeploy after changing this.

2. Frontend — Token Display

Edit fireswap-frontend/src/config/constants/tokens.ts — update the localTokens.cake entry:

cake: new Token(
  CUSTOM_CHAIN_ID,
  '0xYOUR_TOKEN_ADDRESS',
  18,
  'SYMBOL',        // Display symbol
  'Your Token Name', // Display name
  '#',
),

3. Farm Labels

Edit fireswap-frontend/src/config/constants/farms.ts — update the lpSymbol values:

// pid 0
lpSymbol: 'SYMBOL',

// pid 1
lpSymbol: 'SYMBOL-BNB LP',

4. Token Icon

Place your token icon (PNG, 128x128 recommended) at:

fireswap-frontend/public/images/tokens/{your_token_address}.png

The filename must be the checksummed contract address with a .png extension.

5. Emission Rate

The MasterChef mints your token at a configurable rate. Edit in dex-contracts/scripts/deploy.js:

// 40 tokens per block (default)
const cakePerBlock = ethers.utils.parseEther("40");

This is set at deployment time and cannot be changed after MasterChef is deployed.

Swap Fees

Trading Fee (Default: 0.2%)

Every swap charges a 0.2% fee on the input amount. This fee is split between liquidity providers and (optionally) a protocol treasury.

RecipientShareCondition
Liquidity Providers0.17%Always (via LP token value growth)
Protocol Treasury0.03%Only when feeTo is set on the Factory

How to Change the Swap Fee

The fee is hardcoded in two contract files. Both must match:

File 1: contracts/periphery/libraries/PancakeLibrary.sol

// Line 47 — getAmountOut()
uint amountInWithFee = amountIn.mul(998);  // 998 = 0.2% fee
// For 0.3% fee, use 997. For 0.25% fee, use 9975 (and change 1000 → 10000).

// Line 58 — getAmountIn()
uint denominator = reserveOut.sub(amountOut).mul(998);

File 2: contracts/core/PancakePair.sol

// Lines 180-181 — swap()
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(2));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(2));
// The "2" here = 1000 - 998 = 2 (the fee in thousandths)
// For 0.3% fee: change 2 → 3, and PancakeLibrary to 997
Important

Swap fees are set at compile time. You must redeploy the Factory, all Pairs, and the Router after changing fees. Existing liquidity pools cannot be migrated — users would need to withdraw and re-add liquidity.

Protocol Fee Recipient

To enable the protocol treasury fee, call setFeeTo() on the Factory contract after deployment:

// In a Hardhat script or via block explorer:
factory.setFeeTo("0xYOUR_TREASURY_ADDRESS");

If feeTo is the zero address (default), all fees go to LPs.

Farms & Pools

Adding a New Farm

Farms are managed by the MasterChef contract. Each farm tracks an LP token and distributes your main token as rewards.

On-Chain (MasterChef)

// Call add() on MasterChef — only the owner can do this
masterChef.add(
  2000,            // allocPoint — share of total emissions
  "0xLP_ADDRESS", // LP token address from Factory.getPair()
  true             // withUpdate — update all pools
);

The allocPoint determines what fraction of token emissions this farm receives. If total allocPoints across all farms is 10000 and your farm has 2000, it gets 20% of emissions.

Frontend Config

Edit fireswap-frontend/src/config/constants/farms.ts and add an entry:

{
  pid: 3,                    // Must match the MasterChef pool ID
  lpSymbol: 'TOKEN-BNB LP',
  lpAddresses: {
    97: '0xLP_ADDRESS_TESTNET',
    56: '0xLP_ADDRESS_MAINNET',
  },
  token: serializedTokens.yourToken,
  quoteToken: serializedTokens.wbnb,
},

Adding a Syrup Pool (SmartChef)

Syrup pools are standalone contracts. Deploy a new SmartChef for each pool:

// Constructor parameters:
SmartChef(
  stakedToken,     // Token users deposit (e.g., your main token)
  rewardToken,     // Token users earn (e.g., BUSD)
  rewardPerBlock,  // Reward rate per block (in wei)
  startBlock,      // Block number when rewards begin
  bonusEndBlock,   // Block number when rewards stop
)

After deploying, transfer reward tokens to the SmartChef contract to fund it, then add the pool to fireswap-frontend/src/config/constants/pools.tsx.

Branding & Theme

Colors

Theme colors are defined in the UIKit package:

fireswap-frontend/packages/uikit/src/theme/colors.ts

Edit darkColors and lightColors objects. Key properties: primary, secondary, background, backgroundAlt, cardBorder.

Logo

Replace the logo files in:

fireswap-frontend/public/logo.png
fireswap-frontend/packages/uikit/src/components/Svg/Icons/Logo*.tsx

Site Title & Metadata

Edit fireswap-frontend/src/views/*/index.tsx — each page has a <PageMeta /> component that sets the page title. Global defaults are in src/components/Layout/Page.tsx.

Menu Items

The navigation menu is configured in:

fireswap-frontend/src/components/Menu/config/config.ts

The localConfig array controls which menu items appear. Add or remove items as needed.

Core Contracts

ContractSolidityPurpose
PancakeFactory0.5.16Creates and tracks token pair contracts. Manages the protocol fee recipient.
PancakePair0.5.16Each trading pair is its own contract. Holds reserves, executes swaps, mints/burns LP tokens.
PancakeRouter0.6.6Entry point for users. Routes swaps through pairs, handles ETH/BNB wrapping, multi-hop paths.
PancakeLibrary0.6.6Helper functions for calculating swap amounts and pair addresses (contains INIT_CODE_HASH).
WBNB0.4.18Wrapped native token (WETH/WBNB). Required for native token ↔ ERC-20 swaps.
Multicall20.5.16Batches multiple read calls into a single RPC request. Required by the frontend.

Farm Contracts

ContractSolidityPurpose
CakeToken0.6.12BEP-20 governance token with mint function (owner = MasterChef).
SyrupBar0.6.12Receipt token for staking CakeToken in MasterChef (pid 0).
MasterChef (V1)0.6.12Central farming contract. Distributes CakeToken to LP stakers based on allocation points.
SmartChef0.8.4Independent staking pool. Stake token A, earn token B. Used for syrup pools.

MasterChef Key Parameters

ParameterDefaultSet At
cakePerBlock40 tokensDeployment (immutable)
startBlock0Deployment (immutable)
devaddrDeployer walletDeployment (changeable by current dev)
Farm allocationVaries per poolVia add() / set() (owner only)

Lottery & Prediction Contracts

Lottery

ContractSolidityPurpose
PancakeSwapLottery0.8.4Main lottery contract. Manages rounds, ticket sales, prize distribution.
MockRandomNumberGenerator0.8.4Mock RNG for testing. For production, implement a Chainlink VRF or equivalent.

Lottery rounds are managed by an operator address. Key functions: startLottery(), closeLottery(), drawFinalNumberAndMakeLotteryClaimable().

Prediction

ContractSolidityPurpose
PancakePredictionV20.8.0Binary prediction game. Users bet Bull/Bear on price movement per round.
MockAggregator0.8.0Chainlink-compatible mock oracle. For production, use a real Chainlink price feed.
Production note

The lottery and prediction contracts include mock oracles for testing. For mainnet deployment, you must integrate Chainlink VRF (lottery) and Chainlink Price Feeds (prediction), or equivalent decentralized oracle solutions for your target chain.

Supported Blockchains

This DEX can be deployed on any EVM-compatible blockchain. The contracts are standard Solidity and the frontend uses standard Web3 libraries.

Pre-configured Networks

NetworkChain IDConfig Key
BSC Mainnet56
BSC Testnet97bscTestnet
Ethereum Sepolia11155111sepolia
Localhost (Hardhat)31337localhost

Adding a New Network

1. Add the network to dex-contracts/hardhat.config.js:

polygon: {
  url: process.env.POLYGON_RPC_URL || "",
  chainId: 137,
  accounts: process.env.DEPLOYER_PRIVATE_KEY ? [process.env.DEPLOYER_PRIVATE_KEY] : [],
},

2. Deploy with npx hardhat run scripts/deploy.js --network polygon

3. The update-frontend.js and patch-sdk.js scripts automatically detect the chain ID from deployed-addresses.json.

Compatible Chains (non-exhaustive)

Ethereum

Mainnet, Sepolia, Goerli

BNB Smart Chain

Mainnet, Testnet

Polygon

PoS, zkEVM

Arbitrum

One, Nova

Avalanche

C-Chain

Base

Mainnet, Sepolia

Any chain with EVM bytecode compatibility, a JSON-RPC endpoint, and a block explorer will work.

Environment Variables

dex-contracts/.env

VariableRequiredDescription
DEPLOYER_PRIVATE_KEYYesPrivate key of the deployer wallet (without 0x prefix)
BSC_TESTNET_RPC_URLNoRPC for BSC testnet (has default)
SEPOLIA_RPC_URLNoRPC for Ethereum Sepolia

fireswap-frontend/.env.development

These are automatically set by update-frontend.js:

VariableDescription
NEXT_PUBLIC_CHAIN_IDTarget chain ID (e.g., 97 for BSC testnet)
NEXT_PUBLIC_NODE_1Primary RPC endpoint
NEXT_PUBLIC_NODE_2Secondary RPC endpoint
NEXT_PUBLIC_NODE_3Tertiary RPC endpoint

Scripts Reference

ScriptPurpose
deploy.jsDeploy all core contracts (Factory, Router, Token, MasterChef, etc.) + create initial LP pairs and farms
setup-testnet.jsAdd liquidity to pools, deposit into farms, harvest tokens, deploy Lottery + start first round
deploy-pools.jsDeploy SmartChef syrup pool contracts and fund them with reward tokens
deploy-prediction.jsDeploy MockAggregator oracle + PancakePredictionV2 and start genesis round
deploy-nft.jsDeploy FireNFT (ERC-721) contract and mint initial tokens
update-frontend.jsRead deployed-addresses.json and patch all frontend config files
patch-sdk.jsPatch @pancakeswap/sdk with your factory address, INIT_CODE_HASH, and WBNB address

Troubleshooting

Swap page shows no output amount

Cause: The @pancakeswap/sdk has stale factory address or INIT_CODE_HASH.

Fix: Run node scripts/patch-sdk.js again, then delete fireswap-frontend/.next/ and restart the dev server.

First deployment exits early with "hash mismatch"

Cause: Normal behavior. The script auto-patches PancakeLibrary.sol with the correct INIT_CODE_HASH on first run.

Fix: Run npx hardhat compile then re-run the deploy script. The second run will complete successfully.

Token icons are broken / missing

Cause: Icons are loaded by contract address from /public/images/tokens/{address}.png. Your deployed tokens have different addresses than mainnet.

Fix: Copy or create icon files named with your deployed token addresses (checksummed format).

Pages redirect to /swap unexpectedly

Cause: next.config.js redirects pages that require external APIs (NFTs, Info, Voting) on non-mainnet chains.

Fix: To enable a page, remove its entry from the apiDependentRedirects array in next.config.js. Note that the page may still not function without a backend API.

Farms/Pools show 0 APR or "Loading"

Cause: The farm or pool contract address in the frontend config doesn't match the deployed contract, or the pool has no staked liquidity.

Fix: Verify addresses in farms.ts and pools.tsx match deployed-addresses.json. Add liquidity and stake LP tokens to see APR calculations.

Prediction page shows loading spinner

Cause: The predictions contract address is empty in contracts.ts, or the genesis round hasn't been started.

Fix: Deploy prediction contracts via deploy-prediction.js, then update contracts.ts with the deployed address.


Built on PancakeSwap V2 · Solidity · Next.js · Hardhat