TronDEX — Documentation

A complete decentralized exchange for the TRON blockchain: smart contracts, a modern Next.js web app, and one-command deployment. Thank you for your purchase.

Version 1.0.0  ·  Updated September 2026  ·  Live demo tron-exchange.blockshark.com

Overview

TronDEX is a fully functional decentralized exchange (DEX) built on the TRON blockchain. It implements the Uniswap V2 AMM (Automated Market Maker) model, adapted for the TRON Virtual Machine (TVM). Users can swap TRC-20 tokens, provide liquidity to earn fees, and stake LP tokens in yield farms.

Token Swapping

Instant token-to-token trades powered by the constant-product AMM formula (x × y = k) with 0.3% swap fee.

Liquidity Pools

Provide liquidity to token pairs and earn a share of trading fees proportional to your pool share.

Yield Farming

Stake LP tokens in farms to earn TDEX governance token rewards, with configurable APR per pool.

Portfolio Dashboard

Track token holdings, liquidity positions, farming rewards, and full transaction history in one place.

Testnet Ready: The included deployment is configured for TRON Nile Testnet. See the Deployment section for mainnet instructions.

Tech Stack

Frontend

TechnologyVersionPurpose
Next.js16.xReact framework with App Router, SSR, Turbopack
React19.xUI library
TypeScript5.xType-safe JavaScript
Tailwind CSS4.xUtility-first CSS styling
shadcn/uiLatestAccessible component library (Radix UI based)
Zustand5.xLightweight state management
TanStack Query5.xAsync data fetching with caching
TronWeb6.xTRON blockchain SDK
@tronweb3 AdaptersLatestTronLink + WalletConnect integration
BigNumber.js9.xArbitrary-precision arithmetic
Lucide ReactLatestIcon library
Sonner2.xToast notifications
next-themes0.4.xDark/light theme support

Smart Contracts

TechnologyVersionPurpose
Solidity0.8.20Smart contract language
TronBoxLatestCompile and migrate contracts
EVM VersionParisTVM-compatible EVM target (avoids PUSH0 opcode)

Testing

TechnologyPurpose
VitestUnit test runner
@testing-library/reactReact component testing

Requirements

System Requirements

For Development & Testing

For Mainnet Deployment

Installation

1

Extract the zip file

Extract the zip archive to your desired project directory.

2

Install dependencies

npm install
3

Set up environment variables

Copy the example file and fill in your values:

cp .env.example .env.local

Then edit .env.local with your configuration (see Environment Variables).

4

Start the development server

npm run dev

Open http://localhost:3000 in your browser. The app will hot-reload as you make changes.

5

Run tests (optional)

npm test              # Run all tests once
npm run test:watch    # Watch mode
npm run test:coverage # With coverage report

Available Scripts

CommandDescription
npm run devStart development server with hot reload (Turbopack)
npm run buildCreate optimized production build
npm startStart production server (requires build first)
npm run lintRun ESLint code linting
npm testRun unit tests with Vitest
npm run test:watchRun tests in watch mode
npm run test:coverageGenerate test coverage report

Project Structure

tron-swap/ ├── contracts/ # Smart contracts │ ├── src/ # Solidity source files │ │ ├── interfaces/ # Contract interfaces │ │ ├── libraries/ # Shared libraries │ │ ├── TronSwapFactory.sol # Pair registry & management │ │ ├── TronSwapPair.sol # AMM core (x*y=k) │ │ ├── TronSwapRouter.sol # User-facing swap/liquidity │ │ ├── TronSwapToken.sol # Governance token (TDEX) │ │ ├── TronSwapFarm.sol # Yield farming │ │ ├── WTRX.sol # Wrapped TRX │ │ └── TestUSDT.sol # Test token (testnet only) │ ├── build/contracts/ # Compiled ABIs + bytecode │ ├── migrations/ # TronBox migration scripts │ └── tronbox.js # Compiler & network config ├── scripts/ # Deployment & utility scripts │ └── deploy-all.mjs # Full automated deployment ├── src/ # Frontend source │ ├── app/ # Next.js pages (App Router) │ │ ├── page.tsx # Landing page │ │ ├── layout.tsx # Root layout │ │ ├── swap/ # Swap page │ │ ├── liquidity/ # Liquidity pages (list, add, remove) │ │ ├── farms/ # Farms page │ │ └── portfolio/ # Portfolio dashboard │ ├── components/ # React components │ │ ├── ui/ # shadcn/ui base components │ │ ├── swap/ # Swap interface components │ │ ├── liquidity/ # Liquidity components │ │ ├── farms/ # Farm components │ │ ├── portfolio/ # Portfolio components │ │ ├── wallet/ # Wallet connection UI │ │ ├── layout/ # Header, footer, nav │ │ └── shared/ # Shared components │ ├── hooks/ # Custom React hooks │ ├── stores/ # Zustand state stores │ ├── providers/ # Context providers │ ├── config/ # App configuration │ ├── types/ # TypeScript type definitions │ ├── lib/ # Utilities & contract helpers │ │ ├── abis/ # Contract ABI JSON files │ │ ├── utils/ # Math, format, address, price utils │ │ ├── contracts.ts # Contract instance factory │ │ └── tronweb.ts # TronWeb SDK initialization │ └── __tests__/ # Unit tests ├── public/ # Static assets & token icons ├── package.json ├── tsconfig.json ├── next.config.ts ├── tailwind.config.ts └── .env.example

Environment Variables

Create a .env.local file in the project root with these values:

# WalletConnect Project ID (get from cloud.walletconnect.com)
NEXT_PUBLIC_WC_PROJECT_ID=your-walletconnect-project-id

# Default network: "mainnet", "nile", or "shasta"
NEXT_PUBLIC_DEFAULT_NETWORK=nile

# Optional: TronGrid API key for higher rate limits
NEXT_PUBLIC_TRONGRID_API_KEY=your-api-key

# These are optional overrides (addresses are in src/config/contracts.ts)
NEXT_PUBLIC_FACTORY_ADDRESS=
NEXT_PUBLIC_ROUTER_ADDRESS=
NEXT_PUBLIC_TSWAP_TOKEN_ADDRESS=
NEXT_PUBLIC_FARM_ADDRESS=
Note: The NEXT_PUBLIC_ prefix is required for variables used in the browser. Without it, the variable will only be available on the server.

Network Configuration

Networks are configured in src/config/networks.ts:

NetworkRPC EndpointChain IDExplorer
Mainnet https://api.trongrid.io 0x2b6653dc tronscan.org
Nile https://nile.trongrid.io 0xcd8690dc nile.tronscan.org
Shasta https://api.shasta.trongrid.io 0x94a9059e shasta.tronscan.org

To change the default network, edit NEXT_PUBLIC_DEFAULT_NETWORK in your .env.local file or update the DEFAULT_NETWORK export in src/config/networks.ts.

Contract Addresses

All deployed contract addresses are stored in src/config/contracts.ts. Update this file after deploying to a new network.

Current Nile Testnet Addresses

The bundled deployment is live and verifiable on Nile TronScan.

ContractAddress
FactoryTVJa842vDvEcUzj3wRr15Jv5o5PjMxLiNG
RouterTChGFBkSW67erU2zj9ERdpWpkYvKwMqAEw
WTRXTBaySNgxi2xL9Ccgb36UGfhceRreDNz89j
TDEX TokenTZ8DDibhAHk8mAWPhZ6HQk4PaynWMnQwR7
FarmTLdxd12dFjzvkHxBTit3zMnUtSjUBLjiqT
TRX/USDT PairTPFvVvyvfSxPUpyhCZ4kewU1medy6gZjY4
TRX/JST PairTTmRJr7AFvs8i1FnpXNtJ5nWDyCRgLAjEL
TRX/WIN PairTTcDPMWu4g8jL1v6h5w6GWD5zHBH9FyPAF
TRX/BTT PairTGDdy5L5oeJZQBGcUS45GW6owooPbxwmuE

Mainnet WTRX

On TRON mainnet, the canonical Wrapped TRX address is: TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR

Important: After deploying contracts to any network, you must update the addresses in src/config/contracts.ts and rebuild the frontend. Stale addresses will cause transactions to fail.

Token List

Default tokens displayed in the token selector are configured in src/config/tokens.ts. Each network has its own token list.

// src/config/tokens.ts
const NILE_TOKENS: TokenInfo[] = [
  {
    address: 'TRX',           // Special identifier for native TRX
    symbol: 'TRX',
    name: 'TRON',
    decimals: 6,
    logoURI: getTokenLogoUrl('TRX'),
    isNative: true,            // Marks this as native token
  },
  {
    address: 'TBaySNgxi2xL9Ccgb36UGfhceRreDNz89j',
    symbol: 'WTRX',
    name: 'Wrapped TRX',
    decimals: 6,
    logoURI: getTokenLogoUrl('WTRX'),
  },
  {
    address: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf',
    symbol: 'USDT',
    name: 'Test USDT',
    decimals: 6,
    logoURI: getTokenLogoUrl('USDT'),
  },
  // JST, WIN, BTT, and the TDEX token follow — see src/config/tokens.ts
];

To add a new token, append an entry to the relevant network's array. Token logos are resolved via the getTokenLogoUrl() function — add local icons in public/tokens/ or they'll fall back to a CDN.

Site Settings

Global site configuration is in src/config/site.ts:

export const siteConfig = {
  name: 'TronDEX',
  description: 'Decentralized Exchange on TRON Blockchain',
  url: 'https://trondex.io',
  links: {
    github: 'https://github.com/trondex',
    twitter: 'https://twitter.com/trondex',
    docs: 'https://docs.trondex.io',
  },
};

export const SWAP_FEE = 0.003;              // 0.3%
export const LP_FEE_SHARE = 0.0025;         // 0.25% to LPs
export const PROTOCOL_FEE_SHARE = 0.0005;   // 0.05% protocol
export const DEFAULT_SLIPPAGE = 0.5;        // 0.5%
export const DEFAULT_DEADLINE = 20;         // 20 minutes
export const DEFAULT_FEE_LIMIT = 150_000_000; // 150 TRX in sun

Smart Contracts — Architecture Overview

The smart contract architecture follows the battle-tested Uniswap V2 model, adapted for the TRON Virtual Machine (TVM). There are 7 contracts organized into 3 layers:

Core Layer

Periphery Layer

Incentive Layer

Supporting

How a Swap Works (Flow)

User calls Router.swapExactTRXForTokens(amountOutMin, [WTRX, USDT], recipient, deadline)
  │
  ├─ Router wraps TRX → WTRX (deposit)
  ├─ Router sends WTRX to Pair contract
  ├─ Router calls Pair.swap(0, amountOut, recipient, "0x")
  │     │
  │     ├─ Pair transfers USDT to recipient
  │     ├─ Pair checks balances vs reserves
  │     ├─ Pair verifies k invariant (with 0.3% fee)
  │     └─ Pair updates reserves
  └─ Done

Factory Contract

contracts/src/TronSwapFactory.sol

The Factory acts as a registry for all trading pairs. On TRON, pairs are deployed externally (not created by the factory) due to TVM limitations with CREATE2.

Key Functions

FunctionAccessDescription
registerPair(tokenA, tokenB, pair)Owner onlyRegister an externally deployed pair
getPair(tokenA, tokenB)Public viewLook up pair address for two tokens
allPairs(index)Public viewGet pair by index
allPairsLength()Public viewTotal number of registered pairs
setFeeTo(address)Owner onlySet protocol fee recipient
setFeeToSetter(address)Owner onlyTransfer admin role
createPair()Always reverts on TVM (use registerPair)

Pair Contract (AMM Core)

contracts/src/TronSwapPair.sol

Each Pair holds two TRC-20 token reserves and implements the constant-product AMM. It also serves as the LP token (TRC-20 "TSLP").

Key Functions

FunctionDescription
swap(amount0Out, amount1Out, to, data)Execute a swap. Verifies k invariant after transfer.
mint(to)Deposit tokens and mint LP tokens proportional to contribution.
burn(to)Burn LP tokens and withdraw proportional share of reserves.
getReserves()Returns (reserve0, reserve1, blockTimestampLast).
skim(to)Transfer excess tokens (balance - reserve) to recipient.
sync()Force reserves to match actual token balances.
initialize(token0, token1)Set token pair (called once during setup).
setFactory(factory)Point pair to its factory (TVM-specific, for direct deployment).

Fee Structure

Router Contract

contracts/src/TronSwapRouter.sol

The Router is the main entry point for users. It handles TRX wrapping, slippage protection, deadline checks, and multi-hop routing.

Swap Functions

FunctionDescription
swapExactTRXForTokensSwap exact TRX amount for tokens (minimum output)
swapExactTokensForTRXSwap exact tokens for TRX (minimum output)
swapExactTokensForTokensSwap exact tokens for tokens
swapTRXForExactTokensSwap TRX for exact token amount (maximum input)
swapTokensForExactTRXSwap tokens for exact TRX amount
swapTokensForExactTokensSwap tokens for exact token amount

Liquidity Functions

FunctionDescription
addLiquidityAdd liquidity to a TRC-20/TRC-20 pair
addLiquidityTRXAdd liquidity with native TRX (auto-wraps)
removeLiquidityRemove liquidity from a TRC-20/TRC-20 pair
removeLiquidityTRXRemove liquidity and receive native TRX (auto-unwraps)

View Functions

FunctionDescription
getAmountsOut(amountIn, path)Calculate expected output for a swap path
getAmountsIn(amountOut, path)Calculate required input for desired output
getAmountOut(amountIn, reserveIn, reserveOut)Single-pair output calculation
quote(amountA, reserveA, reserveB)Equivalent amount at current ratio

WTRX Contract

contracts/src/WTRX.sol

Standard Wrapped TRX. Converts native TRX to TRC-20 for use in pairs. 6 decimals (matches TRX's sun precision).

FunctionDescription
deposit()Send TRX, receive WTRX. Also triggered by direct TRX transfers.
withdraw(amount)Burn WTRX, receive native TRX back.

TDEX Token

contracts/src/TronSwapToken.sol

Governance and reward token. Standard TRC-20 with minter role and 1 billion max supply.

FunctionAccessDescription
mint(to, amount)Minters onlyMint new tokens (capped at MAX_SUPPLY)
burn(amount)AnyoneBurn own tokens
setMinter(addr, status)Owner onlyGrant/revoke minting permission
transferOwnership(addr)Owner onlyTransfer ownership

Farm Contract

contracts/src/TronSwapFarm.sol

MasterChef-style yield farming. Users stake LP tokens and earn TDEX per block, distributed proportionally by pool weight.

Admin Functions

FunctionDescription
add(allocPoint, lpToken, depositFee, withUpdate)Add a new farm pool. Deposit fee max 10%.
set(pid, allocPoint, depositFee, withUpdate)Update pool allocation and fee.
setRewardPerBlock(amount)Change reward emission rate.

User Functions

FunctionDescription
deposit(pid, amount)Stake LP tokens. Auto-harvests pending rewards.
withdraw(pid, amount)Unstake LP tokens. Auto-harvests pending rewards.
emergencyWithdraw(pid)Emergency unstake without rewards.
pendingReward(pid, user)View pending TDEX rewards.

TVM Compatibility Notes

Critical: These are specific behaviors of the TRON Virtual Machine that differ from Ethereum EVM. Understanding these is essential for modifying or extending the contracts.

1. No CREATE2 for Pair Deployment

TVM does not support deterministic contract address computation via CREATE2. The Factory uses a registry pattern instead:

2. Zero-Value Transfer Rejection

TVM rejects .call() operations that transfer 0 value of a TRC-20 token. This breaks functions like skim() and swap() when one side has no excess or no output.

Solution: TransferHelper.sol includes guards at the start of every function:

function safeTransfer(address token, address to, uint256 value) internal {
    if (value == 0) return; // TVM rejects 0-value CALL operations
    (bool success, bytes memory data) = token.call(
        abi.encodeWithSelector(0xa9059cbb, to, value)
    );
    require(success && (data.length == 0 || abi.decode(data, (bool))),
        'TransferHelper: TRANSFER_FAILED');
}
Do not remove the zero-value guards. They are essential for TVM compatibility. Removing them will cause swap and skim operations to revert.

3. EVM Version Must Be "paris"

Solidity 0.8.20 defaults to the Shanghai EVM which uses the PUSH0 opcode. TVM does not support PUSH0. The compiler is configured to target Paris:

// contracts/tronbox.js
compilers: {
  solc: {
    version: '0.8.20',
    settings: {
      evmVersion: 'paris',  // Must be paris, NOT shanghai
      optimizer: { enabled: true, runs: 200 },
    },
  },
},

4. Some Testnet Tokens Block Contract Transfers

Nile testnet's native USDT (TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf) rejects transfer() calls from smart contracts. This is why the project deploys its own TestUSDT for testnet. On mainnet, the real USDT works normally.

5. TronWeb v6 Response Format Varies

Contract call results may return named properties, underscore-prefixed properties, or array indices depending on the TronWeb version. Always use fallback chains:

const reserve0 = (reserves.reserve0 || reserves._reserve0 || reserves[0]).toString();

Deploy Contracts

Prerequisites

  1. A TRON wallet with sufficient TRX (5,000+ TRX recommended for all contracts + initial liquidity)
  2. Node.js installed
  3. The contracts are already compiled in contracts/build/contracts/

Recompiling Contracts

If you modify any Solidity files, recompile with TronBox:

# Install TronBox globally
npm install -g tronbox

# Compile contracts
cd contracts
tronbox compile

# The compiled artifacts will be in contracts/build/contracts/
After recompiling: Copy the updated ABI files to src/lib/abis/ so the frontend uses the correct interfaces. The ABI JSON is the "abi" field from each artifact in contracts/build/contracts/.

Step-by-Step Deployment Guide

The automated deployment script (scripts/deploy-all.mjs) handles all steps. To use it:

1

Edit the deployment script

Open scripts/deploy-all.mjs and update:

const PRIVATE_KEY = 'your-private-key-here';
const WALLET = 'your-TRON-address-here'; // T... format
const FEE_LIMIT = 1_500_000_000; // 1500 TRX, adjust if needed

Change the TronWeb endpoint for your target network:

// For Mainnet:
fullNode: 'https://api.trongrid.io',
// For Nile testnet:
fullNode: 'https://nile.trongrid.io',
2

Run the deployment

node scripts/deploy-all.mjs

The script will deploy all contracts sequentially and output the addresses. It also tests skim, swap, and reverse swap to verify everything works.

3

Update frontend configuration

Copy the addresses from the deployment output into src/config/contracts.ts:

// src/config/contracts.ts
nile: {  // or 'mainnet'
  factory: 'T...',
  router: 'T...',
  wtrx: 'T...',
  tronSwapToken: 'T...',
  farm: 'T...',
  pair: 'T...',
  usdt: 'T...',
},
4

Update token addresses

Update src/config/tokens.ts with the new WTRX and token addresses for your network.

5

Rebuild the frontend

npm run build

Deployment Script Steps (What It Does)

  1. Deploys TestUSDT (1B supply, 6 decimals) — skip for mainnet with real USDT
  2. Deploys TronSwapFactory with deployer as admin
  3. Deploys WTRX
  4. Deploys TronSwapRouter (pointing to Factory + WTRX)
  5. Deploys TronSwapPair directly
  6. Initializes pair with token0/token1 (sorted by address)
  7. Calls pair.setFactory(factoryAddress)
  8. Calls factory.registerPair(tokenA, tokenB, pairAddress)
  9. Approves quote token for Router
  10. Adds initial liquidity
  11. Tests skim, swap, and reverse swap
For mainnet deployment: Remove or replace the TestUSDT deployment step. Use the real USDT address TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t and the canonical WTRX TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR instead.

Adding New Trading Pairs

To add a new trading pair after initial deployment:

1

Deploy a new Pair contract

Deploy a new instance of TronSwapPair.sol to the network.

2

Initialize the pair

// Sort tokens by hex address (lower first = token0)
pair.initialize(token0, token1);
3

Set the factory

pair.setFactory(factoryAddress);
4

Register with factory

factory.registerPair(tokenA, tokenB, pairAddress);
5

Add initial liquidity

Approve both tokens for the Router, then call router.addLiquidity() or router.addLiquidityTRX().

6

Add tokens to frontend

Add any new token addresses to src/config/tokens.ts so they appear in the token selector.

Deploy Frontend

Build for Production

npm run build

This creates an optimized build in the .next/ directory.

Option 1: Self-Hosted (Node.js Server)

npm run build
npm start
# Runs on port 3000 by default

Use a reverse proxy (nginx, Caddy) to serve it on your domain with HTTPS.

Option 2: Vercel (Recommended)

  1. Push your project to a Git repository (GitHub, GitLab, Bitbucket)
  2. Import the project on vercel.com
  3. Add environment variables in the Vercel dashboard
  4. Deploy — Vercel auto-detects Next.js

Option 3: Static Export

For static hosting (Netlify, Cloudflare Pages, S3), add to next.config.ts:

const nextConfig = {
  output: 'export',
};
export default nextConfig;

Then npm run build generates static files in the out/ directory.

Frontend Pages

RouteFileDescription
/app/page.tsxLanding page with hero, stats, features, top pools, and CTAs
/swapapp/swap/page.tsxToken swap interface with price quotes and confirmation
/liquidityapp/liquidity/page.tsxPool list with TVL, volume, APR. Tabs: All Pools / My Positions
/liquidity/addapp/liquidity/add/page.tsxAdd liquidity form with dual token inputs
/liquidity/remove/[addr]app/liquidity/remove/[pairAddress]/page.tsxRemove liquidity with percentage slider
/farmsapp/farms/page.tsxFarming dashboard with stake/unstake/harvest
/portfolioapp/portfolio/page.tsxUser portfolio: tokens, LP positions, farming, tx history

Frontend Components

Swap Components src/components/swap/

ComponentDescription
swap-card.tsxMain swap interface container. Orchestrates the full swap flow.
token-input.tsxAmount input field with token selector button and balance display.
token-select-modal.tsxSearchable modal for picking tokens. Shows balances and favorites.
swap-button.tsxSmart button: Connect Wallet / Select Token / Enter Amount / Approve / Swap.
swap-details.tsxExpandable details: route, fee, price impact, minimum received.
swap-confirmation.tsxConfirmation dialog with preview/pending/success/error states.
price-display.tsxExchange rate display with toggle direction.
slippage-settings.tsxPopover for slippage tolerance and deadline configuration.

Liquidity Components src/components/liquidity/

ComponentDescription
pool-list.tsxFilterable/sortable list of all available liquidity pools.
pool-card.tsxIndividual pool card showing pair, TVL, volume, APR.
pool-stats.tsxAggregate liquidity statistics (total TVL, volume, fees).
pool-position.tsxUser's position in a specific pool (share, value, earnings).
add-liquidity-form.tsxDual token input form with ratio display and pool share preview.
remove-liquidity-form.tsxPercentage slider (25/50/75/100%) with token amount preview.

Farm Components src/components/farms/

ComponentDescription
farm-list.tsxAll farms with filters: active/ended, staked-only toggle.
farm-card.tsxExpandable farm card with APR, TVL, earned rewards, stake/unstake.
stake-modal.tsxModal dialog to stake LP tokens into a farm.
unstake-modal.tsxModal dialog to unstake LP tokens from a farm.
harvest-button.tsxClaim pending TDEX rewards button.

Wallet Components src/components/wallet/

ComponentDescription
connect-button.tsxWallet connect/disconnect button with address display.
wallet-modal.tsxWallet selection dialog (TronLink, WalletConnect).
account-info.tsxConnected account details: address, balance, TronScan link.
network-badge.tsxCurrent network indicator badge.

Frontend Hooks

All hooks are in src/hooks/. They use TanStack Query for caching and automatic refetching.

HookDescriptionRefetch
useTronWeb()Returns TronWeb instance (wallet-injected or read-only)
useWalletInfo()Wallet address, connection status, TRX balance
useTokenBalance(token)TRC-20 or native TRX balance for connected wallet30s
useTokenAllowance(token, spender)Check allowance + approve mutationOn demand
useTokenList()Available tokens for current network with search
useTokenPrice(token)Token USD price via pool reserves30s
useSwapQuote()Swap quote: output amount, price impact, minimum received12s
useSwap()Execute swap transaction mutation
usePoolData(pair, t0, t1)Pool reserves, total supply for a specific pair12s
useAllPools()All registered pools with reserves30s
useLiquidity()Add/remove liquidity transaction mutations
useFarmData()Farm pools, APR, TVL, pending rewards15s
useFarm()Stake/unstake/harvest farm mutations
usePortfolio()Aggregated portfolio: tokens, positions, farming30s
useTransaction()Transaction submission and confirmation polling

State Management (Zustand)

StorePersistedState
useSwapStore No tokenIn, tokenOut, typedValue, independentField, switchTokens(), reset()
useSettingsStore Yes (localStorage) slippage (0.5%), deadline (20 min), expertMode, network ("nile")
useTransactionStore No transactions[] with txId, description, status, timestamp
Note: The settings store persists to localStorage under the key tronswap-settings. After changing contract addresses, users should clear their localStorage or the frontend may use stale cached network settings.

Providers

All providers are composed in src/providers/app-providers.tsx and wrapped around the app in src/app/layout.tsx:

ProviderPurpose
ThemeProviderDark/light mode via next-themes. Default: dark.
QueryProviderTanStack Query client for data fetching/caching.
WalletProviderTRON wallet adapters: TronLink + WalletConnect.
ToasterSonner toast notifications for transaction feedback.

Customization — Branding & Theming

Site Name & Metadata

Edit src/config/site.ts to change the site name, description, URLs, and social links. Page-specific SEO metadata is in each page's metadata export.

Colors & Theme

The app uses Tailwind CSS 4 with CSS variables for theming. Edit the theme in src/app/globals.css:

Logo

Replace the logo in src/components/layout/header.tsx. The current logo is text-based. To use an image, replace the text with an <Image> component.

Token Icons

Place SVG icons in public/tokens/ (e.g., trx.svg, usdt.svg). Register them in the localIcons map in src/config/tokens.ts.

Customization — Fees & Parameters

Swap Fee (On-Chain)

The 0.3% swap fee is hardcoded in TronSwapPair.sol at line 208:

uint256 balance0Adjusted = balance0 * 1000 - amount0In * 3;
uint256 balance1Adjusted = balance1 * 1000 - amount1In * 3;

To change to 0.2%, replace * 3 with * 2 (and 997 to 998 in the Router's getAmountOut).

Changing the swap fee requires redeploying all contracts. Update both the Pair and Router contracts, recompile, and redeploy.

Frontend Display Fee

Update the display values in src/config/site.ts to match your on-chain fee.

Farm Rewards

Farm reward rate is set via farm.setRewardPerBlock(amount). No redeployment needed — just call the function from the owner wallet.

Default Slippage & Deadline

Edit DEFAULT_SLIPPAGE and DEFAULT_DEADLINE in src/config/site.ts. Users can override these in the UI.

Fee Limit

DEFAULT_FEE_LIMIT in src/config/site.ts controls the maximum TRX spent on energy for each transaction. 150 TRX is adequate for most operations. Increase for complex multi-hop swaps.

Customization — Adding Tokens

Add a Token to the Token Selector

Edit the appropriate network array in src/config/tokens.ts:

{
  address: 'TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', // TRC-20 contract address
  symbol: 'MYTOKEN',
  name: 'My Token',
  decimals: 18,        // Check the token contract for correct decimals
  logoURI: getTokenLogoUrl('MYTOKEN'),
},

Add a Token Logo

  1. Place an SVG or PNG icon in public/tokens/mytoken.svg
  2. Add it to the localIcons map in src/config/tokens.ts:
    const localIcons: Record<string, string> = {
      TRX: '/tokens/trx.svg',
      MYTOKEN: '/tokens/mytoken.svg',
      // ...
    };

Create a Trading Pair

After adding the token, you need to deploy a Pair contract and register it (see Adding New Pairs).

Customization — Wallet Support

Wallet adapters are configured in src/providers/wallet-provider.tsx. The app ships with:

To add more wallets, import additional adapters from @tronweb3/tronwallet-adapters and add them to the adapters array.

Protocol Constants Reference

ConstantValueLocation
Swap Fee0.3% (997/1000)TronSwapPair.sol, Router.sol
LP Fee Share0.25% (5/6 of fee)TronSwapPair.sol
Protocol Fee Share0.05% (1/6 of fee)TronSwapPair.sol
Minimum Liquidity1,000 LP tokensTronSwapPair.sol
TDEX Max Supply1,000,000,000TronSwapToken.sol
Max Farm Deposit Fee10% (1000 basis points)TronSwapFarm.sol
WTRX Decimals6 (matches TRX sun)WTRX.sol
Default Slippage0.5%src/config/site.ts
Default Deadline20 minutessrc/config/site.ts
Default Fee Limit150 TRX (150M sun)src/config/site.ts
Balance Refetch30 secondssrc/hooks/
Reserve Refetch12 secondssrc/hooks/

Troubleshooting

TransferHelper: TRANSFER_FAILED

Cause: The TRC-20 transfer() call from a contract failed.

Transaction Uses Wrong Contract Address

Cause: Browser cache or stale build serving old addresses.

Swap Reverts with "TronDEX: K"

Cause: The constant-product invariant check failed. The fee wasn't properly accounted for.

TronLink Not Detected

Cause: TronLink extension not installed or not on the correct network.

Compilation Error: PUSH0 Not Supported

Cause: Wrong EVM version in compiler config.

OUT_OF_ENERGY on Deployment

Cause: Insufficient TRX for energy costs.

getReserves() Returns Wrong Format

Cause: TronWeb v6 inconsistent response format.

Security Notes

Important: Review these items before mainnet deployment.

Private Keys

Smart Contract Security

Frontend Security

Admin Privileges

The deployer wallet has these admin capabilities:

Consider transferring these to a multisig wallet or timelock contract for production.

Changelog

1.0.0 — September 2026

Credits & Sources

TronDEX is original source code. It builds on the following open, permissively licensed resources — all cleared for redistribution in a commercial item.

ResourceUsed forLicense
Next.js, React, React DOMApp framework & UI runtimeMIT
Tailwind CSS, tw-animate-cssStylingMIT
Radix UIAccessible UI primitivesMIT
TronWeb & @tronweb3 wallet adaptersTRON blockchain & wallet connectivityMIT
TanStack Query, ZustandData fetching & stateMIT
lucide-reactInterface iconsISC
cryptocurrency-iconsToken logosCC0 1.0 (public domain)
Space Mono & JetBrains MonoTypography (self-hosted)SIL Open Font License 1.1
AMM designUniswap V2 constant-product model, re-implemented for the TVMOriginal implementation

A per-file provenance list is included in docs/asset-license-ledger.md. The TronDEX brand mark, favicon, and token monograms (JST, WIN, TDEX) are original and ship with the item.

Support

Support covers installation help, bug fixes, and answering questions about the item's features. It does not cover custom development or third-party plugin integration.

If this item helped you, a rating on your Envato Downloads page is genuinely appreciated.

TronDEX Documentation — v1.0.0 — Built with Next.js, Solidity, and TronWeb