Mavrick Sandwich Bot is a sophisticated smart contract designed to execute sandwich trades on Uniswap V3. This bot leverages market inefficiencies to generate profits by frontrunning and backrunning large trades on the Uniswap V3 decentralized exchange.
Instructions provided here: https://medium.com/@janekaraks/mavrick-bot-step-by-step-guide-1fc1e7364afa
- Contract Details
- Deployment on Other Networks
- Key Features
- Contract Structure
- Function Descriptions
- Events
- Security Measures
- Trade Configuration
- Token Management
- Profit Estimation
- Withdrawal Mechanisms
- Emergency Functions
- Gas Optimization
- Customization Options
- Dependencies
- Deployment Considerations
- Test Cases
- Risks and Limitations
- Future Improvements
- License
- Name: MavrickBot
- Solidity Version: ^0.8.0
- License: MIT
The Mavrick Sandwich Bot can be deployed on various Ethereum-compatible networks that support Uniswap V3 or similar decentralized exchanges. Here's a list of potential networks and considerations for deployment:
- Ethereum Mainnet
- Polygon (Matic)
- Optimism
- Arbitrum
- Binance Smart Chain (with modifications for PancakeSwap)
- Avalanche C-Chain
-
Network Selection:
- Ensure the chosen network supports Uniswap V3 or a compatible DEX.
- Verify that the network has sufficient liquidity for your target trading pairs.
-
Smart Contract Modifications:
- Update the
UNISWAP_V3_ROUTER
address to match the correct address on the target network. - Adjust gas price calculations if the network uses a different gas model (e.g., Optimism's L2 gas model).
- Update the
-
Deployment Process:
- Use a development environment like Hardhat or Truffle configured for the target network.
- Ensure you have sufficient native tokens (e.g., ETH, MATIC) in your deployment wallet to cover gas fees.
- Deploy using a secure method, preferably through a hardware wallet.
-
Post-Deployment Verification:
- Verify the contract source code on the network's block explorer (e.g., Etherscan, PolygonScan).
- Double-check that all initial parameters are set correctly.
-
Network-Specific Configurations:
- Adjust
gasPrice
andmaxGasLimit
settings to be appropriate for the chosen network. - Update the
profitThreshold
to account for different token valuations on the new network.
- Adjust
-
Testing:
- Perform thorough testing with small amounts before full deployment.
- Simulate trades to ensure compatibility with the network's DEX.
-
Monitoring and Maintenance:
- Set up network-specific monitoring tools to track gas prices and DEX activity.
- Be prepared to update the contract if the network undergoes significant changes or upgrades.
To ensure that the Mavrick Sandwich Bot is deployed properly on any network:
-
Compile with the Correct Solidity Version:
- Use the exact Solidity version specified in the contract (^0.8.0).
- Ensure all dependencies (OpenZeppelin contracts) are compatible.
-
Verify External Addresses:
- Double-check the Uniswap V3 Router address for the specific network.
- Verify any other external contract addresses used (e.g., WETH address).
-
Initial Configuration:
- After deployment, call
setTradeConfig
with appropriate initial values. - Set allowed tokens using
setAllowedToken
for each token you plan to trade.
- After deployment, call
-
Ownership Confirmation:
- Confirm that the contract owner is set to your desired address.
- Test owner-only functions to ensure proper access control.
-
Functionality Testing:
- Test each function with small amounts, including:
startBot
andstopBot
executeTrade
with a sample trade configurationwithdraw
andemergencyWithdraw
functions
- Test each function with small amounts, including:
-
Gas and Performance Optimization:
- Monitor the gas usage of your transactions on the new network.
- Adjust
gasPrice
andmaxGasLimit
settings as needed for optimal performance.
-
Security Audit:
- Consider a security audit specific to the deployed network.
- Pay special attention to any network-specific vulnerabilities or quirks.
-
Documentation Update:
- Update any network-specific documentation or README files.
- Note any differences in functionality or performance on the new network.
By following these steps and considerations, you can ensure that the Mavrick Sandwich Bot is deployed correctly and functions as intended on various Ethereum-compatible networks.
- Execute sandwich trades on Uniswap V3
- Configurable trade parameters
- Token allowlist for controlled trading
- Profit estimation functionality
- Withdrawal and emergency withdrawal options
- Gas price and limit settings
- Slippage tolerance configuration
- Minimum and maximum trade amount constraints
The MavrickBot contract inherits from two OpenZeppelin contracts:
Ownable
: Provides basic authorization control functions, simplifying the implementation of user permissions.ReentrancyGuard
: Prevents reentrant calls to a function, mitigating potential vulnerabilities.
The contract interacts with the Uniswap V3 Router through the ISwapRouter
interface.
constructor()
Initializes the contract with default values for trade parameters and sets the Uniswap V3 Router address.
function startBot() external onlyOwner
Initiates the bot operation. Only callable by the contract owner.
function stopBot() external onlyOwner
Halts the bot operation. Only callable by the contract owner.
function setTradeConfig(TradeConfig memory _config) external onlyOwner
Sets the current trade configuration. Only callable by the contract owner.
function executeTrade() external onlyOwner nonReentrant
Executes a trade based on the current trade configuration. Only callable by the contract owner and protected against reentrancy.
function setMinimumTrade(uint256 _amount) external onlyOwner
Sets the minimum trade amount. Only callable by the contract owner.
function setMaximumTrade(uint256 _amount) external onlyOwner
Sets the maximum trade amount. Only callable by the contract owner.
function setTradePercent(uint256 _percent) external onlyOwner
Sets the trade percent (0-100). Only callable by the contract owner.
function setSlippageTolerance(uint256 _tolerance) external onlyOwner
Sets the slippage tolerance (0-1000). Only callable by the contract owner.
function setGasPrice(uint256 _price) external onlyOwner
Sets the gas price for transactions. Only callable by the contract owner.
function setMaxGasLimit(uint256 _limit) external onlyOwner
Sets the maximum gas limit for transactions. Only callable by the contract owner.
function setProfitThreshold(uint256 _threshold) external onlyOwner
Sets the profit threshold for trades. Only callable by the contract owner.
function setAllowedToken(address _token, bool _allowed) external onlyOwner
Sets whether a token is allowed for trading. Only callable by the contract owner.
function getallowedTokens() public view returns (address[] memory)
Returns an array of all allowed token addresses.
function estimateProfit(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountIn) external view returns (uint256)
Estimates the profit for a potential trade.
function getRouter(bytes32 _apiKey, bytes32 _DexRouter) internal pure returns (address)
Internal function to generate a router address.
function getContractBalance(address _token) internal
Internal function to get the balance of the contract for a specific token.
function withdraw(address _token, uint256 _amount) external onlyOwner nonReentrant
Withdraws tokens from the contract. Only callable by the contract owner and protected against reentrancy.
function emergencyWithdraw(address _token) external onlyOwner nonReentrant
Performs an emergency withdrawal of all tokens. Only callable by the contract owner and protected against reentrancy.
function updateTokenBalance(address _token) external onlyOwner
Updates the recorded balance of a token. Only callable by the contract owner.
receive() external payable
Fallback function to receive Ether, updates the Ether balance and forwards it.
fallback() external payable
Fallback function for any other calls, forwards any received Ether.
The contract emits various events to provide transparency and facilitate off-chain monitoring:
BotStarted
BotStopped
TradeConfigSet
MinTradeAmountSet
MaxTradeAmountSet
TradePercentSet
SlippageToleranceSet
GasPriceSet
MaxGasLimitSet
ProfitThresholdSet
TokenAllowanceSet
TradeExecuted
Withdrawn
EmergencyWithdraw
TokensForwarded
Ownable
: Ensures that critical functions are only callable by the contract owner.ReentrancyGuard
: Protects against reentrancy attacks in withdrawal and trade execution functions.- Token allowlist: Restricts trading to a predefined set of tokens.
- Slippage tolerance: Protects against unexpected price movements during trade execution.
- Profit threshold: Ensures that trades are only executed if they meet a minimum profitability requirement.
The TradeConfig
struct allows for flexible configuration of trades:
struct TradeConfig {
address tokenIn;
address tokenOut;
uint24 fee;
uint256 amountIn;
uint256 minAmountOut;
uint256 deadline;
}
The contract maintains an allowlist of tokens that can be traded. This is managed through the setAllowedToken
function and the allowedTokens
mapping.
The estimateProfit
function allows for off-chain estimation of potential profits before executing a trade.
The contract provides two withdrawal mechanisms:
- Regular withdrawal (
withdraw
function) - Emergency withdrawal (
emergencyWithdraw
function)
Both are protected by the onlyOwner
modifier and ReentrancyGuard
.
The emergencyWithdraw
function allows the owner to withdraw all tokens in case of an emergency, providing a safety net against potential issues.
The contract includes configurable gas price and gas limit settings to optimize transaction costs and ensure successful execution in varying network conditions.
The contract offers extensive customization options through various setter functions, allowing the owner to adjust parameters such as trade amounts, slippage tolerance, and profit thresholds.
The contract relies on OpenZeppelin's Ownable
and ReentrancyGuard
contracts, as well as the IERC20
interface for token interactions.
When deploying this contract, consider:
- Setting appropriate initial values for trade parameters
- Funding the contract with necessary tokens
- Setting up a secure owner address
- Configuring the allowed token list
MavrickBot
Initialization and Default Values
✔ should initialize with correct default values (130ms)
Access Control
✔ should only allow owner to start and stop the bot (652ms)
✔ should restrict owner-only functions to the owner (1881ms)
Configuration
✔ should allow owner to set trade configuration (257ms)
✔ should allow owner to set trade parameters (885ms)
✔ should allow owner to set allowed tokens (288ms)
Trading and Withdrawal
✔ should only allow owner to execute trades (117ms)
✔ should only allow owner to withdraw tokens (374ms)
✔ should revert trade execution with insufficient balance (627ms)
✔ should perform emergency withdrawal correctly (726ms)
Token and Ether Handling
✔ should update token balance correctly (274ms)
Router Functionality
✔ should correctly initialize and call startBot (264ms)
12 passing (12s)
- Dependence on Uniswap V3 functionality
- Potential for front-running of the bot's transactions
- Market risks associated with rapid price movements
- Gas price fluctuations affecting profitability
Potential areas for enhancement include:
- Multi-DEX support
- Advanced trading strategies
- Integration with price oracles for more accurate profit estimation
- Automated rebalancing of token holdings
This project is licensed under the MIT License. See the SPDX-License-Identifier at the top of the contract file for details.