In the fast-evolving world of decentralized finance (DeFi), automated trading strategies have become essential tools for maximizing returns. One such strategy is arbitrage trading, which exploits price differences of the same asset across different platforms. This article explores a fully functional arbitrage bot built using Node.js and Web3.js, designed to detect and execute profitable trades between two major DeFi protocols: Uniswap and Kyber Network.
The bot continuously polls real-time exchange rates, compares them, and triggers transactions when a profitable arbitrage opportunity arises—offering developers and traders a powerful foundation for algorithmic trading in blockchain ecosystems.
How the Arbitrage Bot Works
At its core, this arbitrage bot runs a local server that periodically checks token prices on both Uniswap and Kyber. It leverages smart contract interactions via the Ethereum blockchain to fetch expected swap rates and determine whether a risk-free profit can be made by buying low on one platform and selling high on another.
Core Components
- Web3.js Integration: Connects to the Ethereum network using an RPC endpoint.
- Smart Contract ABIs: Interfaces with Uniswap Factory, Kyber Rate, and Kyber Network Proxy contracts.
- Price Monitoring Loop: Polls market data at regular intervals (configurable).
- Profit Calculation Engine: Compares net returns after gas costs to identify viable trades.
- Auto-Execution Logic: Triggers buy/sell functions when arbitrage conditions are met.
This modular design allows for easy extension to other DEXs or token pairs.
Key Protocols Involved
Uniswap
Uniswap uses automated market maker (AMM) models where liquidity pools determine prices based on supply and demand. The bot interacts with Uniswap’s factory contract to locate token-specific exchange addresses and then queries getTokenToEthInputPrice and getEthToTokenInputPrice to estimate trade outcomes.
Kyber Network
Kyber provides instant liquidity through reserve pools. The bot calls getExpectedRate on Kyber’s rate contract to compare conversion rates. A significant discrepancy between Kyber and Uniswap pricing signals a potential arbitrage window.
👉 Discover how automated trading strategies can boost your DeFi performance
Technical Implementation Overview
The script begins by loading environment variables and initializing Express for local server operations. It sets up Web3 with an HDWalletProvider to sign transactions securely.
const web3 = new Web3(new Web3.providers.HttpProvider(process.env.RPC_URL_MAINNET));Next, it defines ABIs for:
- Uniswap Factory Contract
- Kyber Rate Contract
- Kyber Network Proxy
- DAI Token Contract
These ABIs enable direct interaction with on-chain smart contracts without relying on third-party APIs.
Token addresses (e.g., ETH, DAI, MKR) are stored in a configuration object for easy reference during swaps.
Real-Time Price Comparison
The checkPair() function is central to the bot’s logic. For each token pair (e.g., ETH/DAI), it:
- Fetches Uniswap's input/output prices using exchange-specific contract methods.
- Retrieves Kyber’s expected rate and slippage threshold.
- Logs side-by-side comparisons using
console.table()for transparency.
const uniResults = await Promise.all([
exchangeContract.methods.getTokenToEthInputPrice(inputAmount).call(),
exchangeContract.methods.getEthToTokenInputPrice(inputAmount).call()
]);
const kyberResults = await Promise.all([
kyberRateContract.methods.getExpectedRate(outputTokenAddress, inputTokenAddress, AMOUNT_TOKEN_WEI, true).call(),
kyberRateContract.methods.getExpectedRate(inputTokenAddress, outputTokenAddress, AMOUNT_ETH_WEI, true).call()
]);Profitability Assessment
After gathering rates, the bot calculates net profits from two possible scenarios:
- Buy on Kyber, Sell on Uniswap
- Buy on Uniswap, Sell on Kyber
Gas fees are factored in to ensure only net-positive opportunities trigger execution.
const profit1 = AMOUNT_ETH * (uniswapRates.sell - kyberRates.buy) - gasPrice * currentEthPrice;
const profit2 = AMOUNT_ETH * (kyberRates.sell - uniswapRates.buy) - gasPrice * currentEthPrice;Only if profit > 0 does the bot proceed with transaction execution.
Execution Workflow
When an arbitrage opportunity is detected:
- The bot logs detailed trade information including buy/sell prices and expected profit.
- It executes the first leg (buy) via either Kyber (
swapEtherToToken) or Uniswap (ethToTokenSwapInput). - Then completes the second leg (sell) on the opposite platform.
- All transactions are sent from a designated
userAddressmanaged by the wallet provider.
This ensures atomicity in logic, though not in transaction execution—meaning front-running risks exist and should be mitigated in production environments.
Configuration & Customization
Several parameters can be adjusted in .env or directly in code:
POLLING_INTERVAL: How often (in ms) to check prices (default: 1000ms).RPC_URL_MAINNET: Ethereum node URL (Infura, Alchemy, etc.).GAS_PRICE: Optional override for dynamic fee estimation.- Token pairs: Easily extendable by adding new entries in the
checkPair()loop.
👉 Learn how to optimize blockchain trading bots with advanced execution tools
Frequently Asked Questions (FAQ)
How does this arbitrage bot avoid losses?
The bot calculates net profit after accounting for gas fees and slippage. Only trades with positive expected returns are executed. However, real-world factors like network congestion or price movement during transaction confirmation can still lead to losses.
Can this bot work on testnets?
Yes. By changing the RPC_URL_MAINNET to a testnet endpoint (e.g., Ropsten or Goerli) and using testnet versions of contract addresses, the bot can safely operate in development mode.
Is this strategy still profitable today?
While simple cross-DEX arbitrage was highly profitable in early DeFi, increased competition from professional bots has narrowed margins. This script serves as an educational base—profitability depends on low-latency infrastructure, gas optimization, and access to private mempools or MEV relays.
What security considerations should I keep in mind?
Never expose your mnemonic or private keys. Use hardware wallets or secure key management systems in production. Additionally, consider implementing rate limiting, fail-safes, and transaction simulation before sending.
Can I add more DEXs like SushiSwap or Curve?
Absolutely. By integrating their respective ABIs and router contracts, you can expand this bot into a multi-DEX arbitrage engine. Each new exchange increases the number of detectable price inefficiencies.
Does this bot handle failed transactions?
Not inherently. In its current form, failed transactions due to slippage or insufficient balance will throw errors. Production-grade bots typically include retry logic, health checks, and alerting mechanisms.
Final Thoughts
This arbitrage bot demonstrates the power of combining blockchain connectivity, smart contract interaction, and real-time data analysis to automate financial strategies. While basic in structure, it lays the groundwork for more sophisticated systems involving flash loans, MEV extraction, or AI-driven prediction models.
Whether you're a developer building your first DeFi tool or a trader exploring automation, understanding how such bots work is crucial in today’s decentralized economy.
👉 Start building smarter trading algorithms with powerful crypto tools
By leveraging platforms like OKX for market insights and secure trading infrastructure, you can enhance your bot’s performance while maintaining control over risk and execution quality.