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.
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.
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.
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
├── 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
- Deploy contracts to your target blockchain using Hardhat
- The deploy script saves all contract addresses to
deployed-addresses.json update-frontend.jsreads those addresses and patches the frontend config filespatch-sdk.jspatches the@pancakeswap/sdkwith your factory address and init code hash- The frontend reads chain ID from
.env.developmentand connects to your contracts
Requirements
| Tool | Version | Purpose |
|---|---|---|
| Node.js | 16.x or 18.x | Runtime for Hardhat and Next.js |
| npm | 8+ | Package manager for dex-contracts |
| Yarn | 1.x (classic) | Package manager for frontend |
| Git | Any recent | Version 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
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.
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
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.
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
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
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
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
Start the development server
cd ../fireswap-frontend
yarn dev
The frontend will be available at http://localhost:3000.
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.
| Recipient | Share | Condition |
|---|---|---|
| Liquidity Providers | 0.17% | Always (via LP token value growth) |
| Protocol Treasury | 0.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
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
| Contract | Solidity | Purpose |
|---|---|---|
| PancakeFactory | 0.5.16 | Creates and tracks token pair contracts. Manages the protocol fee recipient. |
| PancakePair | 0.5.16 | Each trading pair is its own contract. Holds reserves, executes swaps, mints/burns LP tokens. |
| PancakeRouter | 0.6.6 | Entry point for users. Routes swaps through pairs, handles ETH/BNB wrapping, multi-hop paths. |
| PancakeLibrary | 0.6.6 | Helper functions for calculating swap amounts and pair addresses (contains INIT_CODE_HASH). |
| WBNB | 0.4.18 | Wrapped native token (WETH/WBNB). Required for native token ↔ ERC-20 swaps. |
| Multicall2 | 0.5.16 | Batches multiple read calls into a single RPC request. Required by the frontend. |
Farm Contracts
| Contract | Solidity | Purpose |
|---|---|---|
| CakeToken | 0.6.12 | BEP-20 governance token with mint function (owner = MasterChef). |
| SyrupBar | 0.6.12 | Receipt token for staking CakeToken in MasterChef (pid 0). |
| MasterChef (V1) | 0.6.12 | Central farming contract. Distributes CakeToken to LP stakers based on allocation points. |
| SmartChef | 0.8.4 | Independent staking pool. Stake token A, earn token B. Used for syrup pools. |
MasterChef Key Parameters
| Parameter | Default | Set At |
|---|---|---|
cakePerBlock | 40 tokens | Deployment (immutable) |
startBlock | 0 | Deployment (immutable) |
devaddr | Deployer wallet | Deployment (changeable by current dev) |
| Farm allocation | Varies per pool | Via add() / set() (owner only) |
Lottery & Prediction Contracts
Lottery
| Contract | Solidity | Purpose |
|---|---|---|
| PancakeSwapLottery | 0.8.4 | Main lottery contract. Manages rounds, ticket sales, prize distribution. |
| MockRandomNumberGenerator | 0.8.4 | Mock 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
| Contract | Solidity | Purpose |
|---|---|---|
| PancakePredictionV2 | 0.8.0 | Binary prediction game. Users bet Bull/Bear on price movement per round. |
| MockAggregator | 0.8.0 | Chainlink-compatible mock oracle. For production, use a real Chainlink price feed. |
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
| Network | Chain ID | Config Key |
|---|---|---|
| BSC Mainnet | 56 | — |
| BSC Testnet | 97 | bscTestnet |
| Ethereum Sepolia | 11155111 | sepolia |
| Localhost (Hardhat) | 31337 | localhost |
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
| Variable | Required | Description |
|---|---|---|
DEPLOYER_PRIVATE_KEY | Yes | Private key of the deployer wallet (without 0x prefix) |
BSC_TESTNET_RPC_URL | No | RPC for BSC testnet (has default) |
SEPOLIA_RPC_URL | No | RPC for Ethereum Sepolia |
fireswap-frontend/.env.development
These are automatically set by update-frontend.js:
| Variable | Description |
|---|---|
NEXT_PUBLIC_CHAIN_ID | Target chain ID (e.g., 97 for BSC testnet) |
NEXT_PUBLIC_NODE_1 | Primary RPC endpoint |
NEXT_PUBLIC_NODE_2 | Secondary RPC endpoint |
NEXT_PUBLIC_NODE_3 | Tertiary RPC endpoint |
Scripts Reference
| Script | Purpose |
|---|---|
deploy.js | Deploy all core contracts (Factory, Router, Token, MasterChef, etc.) + create initial LP pairs and farms |
setup-testnet.js | Add liquidity to pools, deposit into farms, harvest tokens, deploy Lottery + start first round |
deploy-pools.js | Deploy SmartChef syrup pool contracts and fund them with reward tokens |
deploy-prediction.js | Deploy MockAggregator oracle + PancakePredictionV2 and start genesis round |
deploy-nft.js | Deploy FireNFT (ERC-721) contract and mint initial tokens |
update-frontend.js | Read deployed-addresses.json and patch all frontend config files |
patch-sdk.js | Patch @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