Simulating Chainlink Oracle Arbitrage with PancakeSwap on BuildBear
This guide walks through detecting and executing arbitrage opportunities using Chainlink price feeds and PancakeSwap AMM pricing inside a BuildBear Sandbox.
Arbitrage in DeFi refers to exploiting price differences between markets. In this case, we detect profitable conditions where PancakeSwap's AMM spot price diverges from Chainlink's oracle price.
Arbitrage happens when the price of a token on the AMM (PancakeSwap) differs significantly from the fair market value reported by Chainlink oracles. Traders can profit by buying the cheaper asset and selling the more expensive one. In our BuildBear Sandbox, we simulate these real-world DeFi conditions safely, without using real funds.
BuildBear enables developers to simulate these conditions using Chainlink data feeds and real liquidity pools without real capital exposure.
This Foundry test script demonstrates how price manipulation and reserve imbalance can create arbitrage opportunities.
In real-world DeFi markets, differences often arise between prices quoted by liquidity pools (such as PancakeSwap reserves) and independent Chainlink oracle feeds for the same token pair.
These discrepancies present arbitrage opportunities.
In this test, we synthetically create such a scenario by manipulating AMM reserves while still referencing live Chainlink oracle prices.
The script closely mirrors real-world behavior, ensuring that when deployed, it accurately reflects how arbitrage detection and execution would perform on a live mainnet fork.
The deployment contract is similar to the test contract, but without any liquidity manipulation.
It allows you to deploy the PancakeReactiveSwapper and monitor for real arbitrage opportunities on your BuildBear sandbox, leveraging live mainnet fork data.
Whenever the price divergence between the Chainlink oracle and PancakeSwap AMM becomes profitable based on your configured threshold, the contract can autonomously execute swaps to capture the arbitrage.
You will need to create a cron job or any other automated script to call the reactive swapper.
It's because the opportunities to have a profitable arbitrage are rare and may or may not work manually.
This script will execute the call to executeBidirectionalArbitrageIfProfitable every 30 secs to check for price changes and arbitrage opportunities and execute the swap if it is profitable
// reactive-arbitrage-bot.jsconst { ethers } = require('ethers');const cron = require('node-cron');// ——— Configuration (hard-coded) ———const RPC_URL = 'BuildBear Sandbox URL HERE'; // 👈 replace with your Sandbox URLconst PRIVATE_KEY = '0xYOUR_PRIVATE_KEY_HERE'; // 👈 replace with your keyconst SWAPPER_ADDRESS = '0xYourDeployedSwapperAddressHere'; // 👈 replace with your deployed PancakeReactiveSwapperconst AMOUNT_IN = ethers.utils.parseUnits('10', 18); // tokenIn amountconst MIN_PROFIT_BPS = 100; // 1% threshold// ABI for just the one function we needconst SWAPPER_ABI = ["function executeBidirectionalArbitrageIfProfitable(uint256 amount, uint256 minProfitBps) external"];const provider = new ethers.providers.JsonRpcProvider(RPC_URL);const wallet = new ethers.Wallet(PRIVATE_KEY, provider);const swapper = new ethers.Contract(SWAPPER_ADDRESS, SWAPPER_ABI, wallet);async function attemptArb() { const ts = new Date().toISOString(); console.log(`${ts} Checking arbitrage… `); try { const tx = await swapper.executeBidirectionalArbitrageIfProfitable( AMOUNT_IN, MIN_PROFIT_BPS ); console.log(`tx sent ${tx.hash}\n`); const receipt = await tx.wait(); console.log(`${ts} ✅ Swap executed in block ${receipt.blockNumber}`); } catch (err) { const msg = err.error?.message || err.message; if (msg.includes("No profitable arbitrage")) { console.log("❌ No arbitrage opportunity"); } else { console.error(`❗ Error: ${msg}`); } }}console.log("🔔 ReactiveSwapper bot started, polling every 30 seconds");cron.schedule("*/30 * * * * *", attemptArb);
Once you run this script, the cron job will run every 30 secs checking for profitable arbitrage opportunities and execute a swap whenever there is one
🔔 ReactiveSwapper bot started, polling every 30 seconds2025-04-30T14:23:17.582Z Checking arbitrage… tx sent 0x9f8e3b2c5a1d4e6f7b8c9d0a1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f2025-04-30T14:23:32.764Z ✅ Swap executed in block 227660102025-04-30T14:23:47.201Z Checking arbitrage… ❌ No arbitrage opportunity2025-04-30T14:24:07.418Z Checking arbitrage… ❌ No arbitrage opportunity
Live Oracle Integration
Leverages production-grade Chainlink price feeds alongside PancakeSwap AMM pools for real-time price data.
Fully Sandboxed
Executes the entire arbitrage lifecycle in BuildBear’s safe environment—no real capital at risk.
End-to-End Automation
Covers opportunity detection, simulation, and on-chain execution of arbitrage trades with a single reactive contract.
Built with Chainlink & Foundry
Utilizes the Chainlink Foundry toolkit for data feeds and the Foundry test framework for robust, forked-mainnet testing.
MEV & DeFi Blueprint
Provides a clear path for architecting reactive DeFi bots and MEV strategies in a controlled sandbox.