How I built a real-time DEX arbitrage detector + smart contract that executes risk-free trades using flash loans — all running on 1GB RAM.
The Hook: Finding Free Money in DeFi
Last month, my bot detected a 0.57% price difference for the same token pair between Uniswap V3 and Aerodrome on Base. That's roughly $5.70 profit per $1,000 traded — with zero risk, thanks to flash loans.
The catch? You need to act in milliseconds before someone else spots it.
So I built an automated system: a TypeScript bot that monitors prices in real-time, paired with a Solidity smart contract that executes atomic arbitrage trades. No upfront capital needed. No risk of partial failure. Just pure, atomic profit.
Here's how I built it.
What is Arbitrage? (The 30-Second Version)
Arbitrage is buying an asset on one exchange where it's cheap and selling it on another where it's expensive. In traditional finance, this requires massive capital and lightning-fast execution.
In DeFi, flash loans change everything. You can borrow millions of dollars, execute your trade, and repay the loan — all in a single transaction. If the trade isn't profitable, the whole thing reverts. Zero risk.
The challenge? Finding those opportunities before everyone else does.
Architecture: Two Components, One System
My project has two main parts:
1. The Detector Bot (TypeScript + Viem)
A lightweight Node.js bot that:
- Monitors Uniswap V3 and Aerodrome pools via WebSockets
- Calculates real-time price differences
- Factors in fees, gas costs, and slippage
- Alerts when profitable opportunities appear
2. The Execution Contract (Solidity + Foundry)
A smart contract that:
- Borrows tokens via EIP-3156 flash loans
- Executes swaps on both DEXes
- Repays the loan + keeps the profit
- All in one atomic transaction
Why split them? The bot runs 24/7, scanning for opportunities. The contract only activates when there's actual profit to be made. This saves gas and keeps things efficient.
Technical Deep Dive: Building the Smart Contract
Choosing Foundry Over Hardhat
I started with Hardhat (the popular choice), but hit endless dependency issues. Then I discovered Foundry — a Rust-based toolkit that compiles Solidity in seconds, not minutes.
The difference?
- Hardhat: 5 minutes of
npm installhell, TypeScript config nightmares - Foundry:
forge build→ done in 2 seconds
Foundry also lets you write tests in Solidity (not JavaScript), which feels more natural when you're testing smart contracts.
The Flash Loan Magic
Here's the core of the contract:
solidity
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external override returns (bytes32) {
// 1. Verify only our contract can trigger this
require(initiator == address(this), "Unauthorized");
// 2. Decode the arbitrage parameters
(address tokenIn, address tokenOut, uint24 fee1, uint24 fee2) =
abi.decode(data, (address, address, uint24, uint24));
// 3. Swap on Uniswap (buy cheap)
ISwapRouter(uniswapRouter).exactInputSingle(...);
// 4. Swap on Aerodrome (sell expensive)
ISwapRouter(aerodromeRouter).exactInputSingle(...);
// 5. Calculate profit and verify it meets threshold
uint256 profit = balanceAfter - (amount + fee);
require(profit >= minProfit, "Insufficient profit");
// 6. Repay the flash loan
IERC20(token).safeTransfer(flashLoanPool, amount + fee);
return keccak256("ERC3156FlashBorrower.onFlashLoan");
}
Key security patterns:
Checks-Effects-Interactions: Update state before external calls
Atomic execution: If any step fails, the whole transaction reverts
Owner-only functions: Only the contract owner can trigger trades
Passing All Tests
I wrote 6 comprehensive tests covering:
✅ Contract deployment and initialization
✅ Owner-only access control
✅ Zero-address validation
✅ Parameter updates (minProfit, routers)
✅ Token balance queries
All tests pass. The contract is ready for production.
The Bot: Real-Time Detection
The TypeScript bot uses Viem (a modern, lightweight alternative to ethers.js) to monitor pools:
// Monitor price changes via WebSocket
publicClient.watchEvent({
event: SwapEvent,
onLogs: (logs) => {
// Calculate new price
// Check for arbitrage opportunity
// If profitable, trigger smart contract
}
});
Performance: The bot runs on just 1GB RAM and processes thousands of price updates per minute. It only triggers the smart contract when the profit exceeds the minimum threshold (configurable, default 0.001 ETH).
Real Results: What I Found
During testing on Base mainnet (using a local fork with Anvil), I discovered:
0.57% spread between Uniswap V3 and Aerodrome for WETH/USDC
Multiple opportunities during high volatility periods
Zero failed transactions — the atomic nature of flash loans means if it's not profitable, it doesn't execute
The bot detected these opportunities in real-time. The contract executed them risk-free.
How to Run It Yourself
Prerequisites
Foundry installed
Node.js 18+ and npm
A Base RPC URL (free from Alchemy)
Quick Start
bash
# Clone the repo
git clone https://github.com/rdin777/base-arbitrage-project.git
cd base-arbitrage-project
# Test the smart contract
forge build
forge test
# Run the bot
cd bot
npm install
cp .env.example .env
# Fill in your PRIVATE_KEY and CONTRACT_ADDRESS
npm run start
Local Testing (No Real Money)
Use Anvil to fork Base mainnet and test with 10,000 fake ETH:
bash
# Terminal 1: Start local fork
anvil --fork-url https://mainnet.base.org
# Terminal 2: Deploy contract
forge script script/Deploy.s.sol \
--rpc-url http://localhost:8545 \
--private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
--broadcast
# Terminal 3: Run bot
cd bot && npm run start
Full deployment guide: DEPLOYMENT.md
What's Next?
This is v1.0. Here's what I'm planning:
Multi-chain support — Expand to Arbitrum, Optimism, Polygon
Triangular arbitrage — Three-token trades (A → B → C → A)
MEV protection — Use private mempools to avoid front-running
Dashboard — Real-time visualization of opportunities and profits
The Code is Open Source
Everything is on GitHub: github.com/rdin777/base-arbitrage-project
Star it if you find it useful. Fork it if you want to build something similar. Open an issue if you have questions.
Lessons Learned
Foundry > Hardhat for Solidity development. The speed difference is night and day.
Flash loans are not free money — you need speed, precision, and good gas optimization.
Atomic execution is your friend — if a trade isn't profitable, it simply doesn't happen.
Testing is everything — 6 unit tests saved me from deploying a broken contract.
Found this useful? Follow me for more Web3 development content. Questions? Drop them in the comments below.
You can check out the previous article
How I Built a Real-Time Arbitrage Detector on Base with Just 1GB RAM
https://dev.to/rdin777/how-i-built-a-real-time-arbitrage-detector-on-base-with-just-1gb-ram-57jp
https://github.com/rdin777/base_bot
#arbitrage #defi #base-chain #solidity #foundry #typescript #flash-loans #smart-contracts #web3
Top comments (0)