FlashArbAI is a decentralized finance (DeFi) arbitrage bot that leverages Balancer V2 flash loans to identify and execute profitable arbitrage opportunities across decentralized exchanges (DEXs). It integrates with the Goat Framework and utilizes the Eliza AI agent plugin to provide a conversational interface for interacting with trades and opportunities.
- FlashArbAI Project
FlashArbAI uses Balancer V2 flash loans to borrow tokens without collateral and perform arbitrage trades on Uniswap V3-compatible DEXs. The AI-powered Eliza agent provides a natural language interface to:
- Discover supported token pairs
- Monitor arbitrage opportunities
- Execute profitable trades
The core of the project is the Arbitrage
smart contract, responsible for flash loans, token swaps, and profit calculations.
- Balancer V2 Flash Loans: Borrow tokens without collateral to execute trades.
- Uniswap V3 Integration: Perform token swaps across Uniswap V3-compatible DEXs.
- AI-Powered Interface: Use Eliza AI for opportunity discovery and execution.
- Customizable Token Pairs: Define and adjust arbitrage token pairs.
- Profit Distribution: Profits are automatically transferred to the contract owner.
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Eliza AI ββββββ FlashArbAI ββββββ Balancer V2 β
β Agent β β Arbitrage β β Flash Loans β
β β β Contract β β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
β β β
βΌ βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β User β β Uniswap V3 β β Other DEXs β
β Interface β β Compatible β β (SushiSwap, β
β β β DEXs β β PancakeSwap) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
- Opportunity Detection: AI agent monitors price differences across supported DEXs
- Flash Loan Initiation: Contract requests flash loan from Balancer V2
- Arbitrage Execution: Execute swaps across different DEXs to capture price differences
- Profit Calculation: Calculate net profit after fees and gas costs
- Loan Repayment: Repay flash loan and transfer profits to contract owner
The Arbitrage
contract is the core of the FlashArbAI project. It implements the IFlashLoanRecipient
interface to receive flash loans from Balancer V2 and executes arbitrage trades on Uniswap V3-compatible DEXs.
-
executeTrade
:- Initiates a flash loan to execute an arbitrage trade.
- Parameters:
_routerPath
: Addresses of the swap routers for each trade._quoterPath
: Addresses of the quoters for price calculations._tokenPath
: Addresses of the tokens involved in the trade._fee
: Pool fee for the swap._flashAmount
: Amount of tokens to flash loan.
-
receiveFlashLoan
:- Callback function invoked by Balancer V2 after providing the flash loan.
- Executes the arbitrage trade by swapping tokens on the specified DEXs.
- Repays the flash loan and transfers profits to the contract owner.
-
_swapOnV3
:- Internal function to execute a token swap on a Uniswap V3-compatible DEX.
- Parameters:
_router
: Address of the swap router._tokenIn
: Address of the input token._amountIn
: Amount of input tokens to swap._tokenOut
: Address of the output token._amountOut
: Minimum amount of output tokens expected._fee
: Pool fee for the swap.
event TokensSwapped(
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
event ArbitrageExecuted(
address indexed tokenA,
address indexed tokenB,
uint256 profit,
uint256 gasUsed
);
- Foundry: Install Foundry for smart contract development and testing.
curl -L https://foundry.paradigm.xyz | bash foundryup
-
Clone the repository:
git clone https://github.com/your-repo/flash-arb-ai.git cd flash-arb-ai
-
Install dependencies:
forge install
-
Compile the smart contract:
forge build
-
Deploy the contract, here is an example for Any Testnet:
forge script script/DeployArbitrage.s.sol:DeployArbitrage <ANYTESTNET_RPC_URL> --private-key <PRIVATE_KEY> --broadcast --verify --verifier blockscout --verifier-url $VERIFIER_URL
Create .env
file in the root directory:
# Network Configuration
SEPOLIA_RPC_URL=https://sepolia.infura.io/v3/YOUR_PROJECT_ID
MAINNET_RPC_URL=https://mainnet.infura.io/v3/YOUR_PROJECT_ID
# Private Keys
PRIVATE_KEY=your_private_key_here
# Contract Addresses
BALANCER_VAULT=0xBA12222222228d8Ba445958a75a0704d566BF2C8
UNISWAP_V3_ROUTER=0xE592427A0AEce92De3Edee1F18E0157C05861564
# API Keys
ETHERSCAN_API_KEY=your_etherscan_api_key
COINGECKO_API_KEY=your_coingecko_api_key
- Update the foundry.toml file with your network RPC URL.
- Configure supported token pairs in
config/tokens.json
:
{
"supportedPairs": [
{
"tokenA": "0xA0b86a33E6441a1e60b5C5B5B5B1b5B5B5B5B5B5",
"tokenB": "0xB0b86a33E6441a1e60b5C5B5B5B1b5B5B5B5B5B5",
"name": "WETH/USDC",
"minProfitThreshold": "0.01"
}
]
}
-
Call the
executeTrade
function on the Arbitrage contract using Foundry:cast send <CONTRACT_ADDRESS> "executeTrade(address[],address[],address[],uint24,uint256)" \ "[<ROUTER1>, <ROUTER2>]" "[<QUOTER1>, <QUOTER2>]" "[<TOKEN1>, <TOKEN2>]" <FEE> <FLASH_AMOUNT> \ --rpc-url <SEPOLIA_RPC_URL> --private-key <PRIVATE_KEY>
-
Monitor the TokensSwapped event to track trade execution and profits:
cast logs --from-block <START_BLOCK> --to-block <END_BLOCK> --address <CONTRACT_ADDRESS> \ --topic "TokensSwapped(address,address,uint256,uint256)" --rpc-url <SEPOLIA_RPC_URL>
- Start the Eliza AI agent:
pnpm run start:agent
Sample queries:
- "Show me profitable arbitrage opportunities"
- "Execute arbitrage for WETH/USDC"
- "What's the profit potential for ETH/DAI?"
- Interact with the agent using natural language:
- "Show me profitable arbitrage opportunities"
- "Execute arbitrage for WETH/USDC pair"
- "What's the current profit potential for ETH/DAI?"
Foundry is used for testing the Arbitrage contract. To run the tests:
-
Write your tests in the test directory.
-
Run the tests using:
forge test
Generage test coverage reports:
forge coverage
- MEV (Maximal Extractable Value): Arbitrage transactions may be front-run by MEV bots
- Flash Loan Attacks: Ensure proper validation of flash loan repayment
- Slippage: Market conditions can change between opportunity detection and execution
- Smart Contract Risk: Potential bugs in contract logic or external dependencies
- Reentrancy guards on critical functions
- Slippage protection with configurable thresholds
- Access control for sensitive operations
- Regular security audits (planned)
- Use of assembly for critical calculations
- Batch operations where possible
- Optimized storage patterns
- Efficient event emission
- Arbitrage success rate
- Average profit per trade
- Gas costs vs. profits
- Network congestion impact
Issue: Flash loan execution fails
- Solution: Check token balances and ensure sufficient liquidity
Issue: High gas costs eating into profits
- Solution: Adjust minimum profit thresholds and monitor network conditions
Issue: Slippage too high
- Solution: Increase slippage tolerance or reduce trade size
executeTrade
Executes an arbitrage trade using flash loans.
_routerPath
(address[]): Array of router addresses_quoterPath
(address[]): Array of quoter addresses_tokenPath
(address[]): Array of token addresses_fee (uint24)
: Pool fee_flashAmount
(uint256): Flash loan amount
getProfit
Calculates potential profit for a given arbitrage opportunity.
tokenA (address)
: First token addresstokenB (address)
: Second token addressamount (uint256)
: Trade amount
Returns: Estimated profit (uint256)
β Core arbitrage contract development β Balancer V2 flash loan integration β Uniswap V3 compatibility π§ AI agent integration
π Multi-DEX support expansion π Advanced profit optimization algorithms π Web dashboard for monitoring π Mobile app development
π Cross-chain arbitrage π Institutional-grade API π Automated portfolio management π Third-party integrations
Contributions to the FlashArbAI project are welcome! Please follow these steps:
-
Fork the repository.
-
Create a new branch for your feature or bug fix.
-
Submit a pull request with a detailed description of your changes.
This project is licensed under the MIT License. See the LICENSE
file for details.
- Balancer Labs for the Balancer V2 flash loan functionality.
- Uniswap Labs for the Uniswap V3 integration.
- Only works with Uniswap V3 forks (for now)
- Needs more slippage protection
- Might fail if liquidity is too low
- What tokens are supported? Check config/tokens.json.
- Which networks are supported? Currently Sepolia and Mainnet.
- Average gas cost per trade? Depends on network congestion.
- How to add a new DEX? Update integration logic and configurations accordingly.
This software is provided "as is" without warranty. Users are responsible for understanding the risks associated with DeFi trading and flash loans. Always test thoroughly on testnets before using with real funds.