🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Advanced Gas Management and MEV

Advanced Solidity DevelopmentđŸŸĸ Free Lesson

Advanced Gas Management and MEV

Understanding gas mechanisms and MEV (Maximal Extractable Value) is crucial for optimizing transaction costs and protecting against sandwich attacks.

EIP-1559: Fee Market

EIP-1559 introduced a new fee mechanism with base fee and priority fee.

Fee Calculation

Base Fee Dynamics

EIP-1559 Base Fee AdjustmentBlock Gas Usage vs TargetTarget15M gasBelow TargetBase Fee ↓Above TargetBase Fee ↑Base Fee adjusts by max 12.5% per block

EIP-1559 Implementation

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract EIP1559Consumer is ReentrancyGuard {
    uint256 public constant MAX_PRIORITY_FEE = 2 gwei;
    uint256 public constant MAX_FEE = 100 gwei;
    
    function executeWithEIP1559() external payable nonReentrant {
        require(msg.value >= _estimateFee(), "Insufficient fee");
        
        // Execute transaction
        _performAction();
        
        // Refund excess
        uint256 refund = msg.value - _estimateFee();
        if (refund > 0) {
            (bool success, ) = msg.sender.call{value: refund}("");
            require(success, "Refund failed");
        }
    }
    
    function _estimateFee() internal view returns (uint256) {
        uint256 baseFee = block.basefee;
        uint256 priorityFee = Math.min(MAX_PRIORITY_FEE, baseFee / 10);
        return (baseFee + priorityFee) * 21000; // Estimated gas
    }
    
    function _performAction() internal {
        // Custom logic
    }
}

MEV-Boost and Flashbots

MEV Protection Strategies

MEV Protection FlowUserSubmits TxFlashbotsPrivate MempoolBlock BuilderProposes BlockFlashbots ProtectNo public mempool exposure → No sandwich attacks

Flashbots Bundle

javascript
// Flashbots bundle submission
import { FlashbotsBundleProvider } from '@flashbots/ethers-provider-bundle';

async function submitBundle(signer, provider) {
    const flashbotsProvider = await FlashbotsBundleProvider.create(
        provider,
        signer,
        'https://relay.flashbots.net'
    );
    
    const blockNumber = await provider.getBlockNumber();
    const block = await provider.getBlock(blockNumber);
    
    const bundle = [
        {
            signer: signer,
            transaction: {
                to: '0xContractAddress',
                value: 0,
                gasLimit: 100000,
                maxFeePerGas: block.baseFeePerGas * 2n,
                maxPriorityFeePerGas: 2n ** 20n,
                chainId: 1,
                data: '0x...'
            }
        }
    ];
    
    const targetBlock = blockNumber + 1;
    
    const signedBundle = await flashbotsProvider.signBundle(bundle);
    const simulation = await flashbotsProvider.simulate(signedBundle, targetBlock);
    
    if ('error' in simulation) {
        console.log('Simulation error:', simulation.error);
        return;
    }
    
    console.log('Simulation success:', simulation);
    
    const bundleResponse = await flashbotsProvider.sendBundle(bundle, targetBlock);
    console.log('Bundle submitted:', bundleResponse);
}

MEV Protection Contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract MEVProtection {
    uint256 public constant MIN_DELAY = 1 blocks;
    uint256 public constant MAX_SLIPPAGE = 500; // 5%
    
    struct PendingSwap {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 minAmountOut;
        uint256 deadline;
        address recipient;
    }
    
    mapping(bytes32 => PendingSwap) public pendingSwaps;
    
    function createProtectedSwap(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        uint256 deadline
    ) external returns (bytes32 swapId) {
        swapId = keccak256(
            abi.encodePacked(
                msg.sender,
                tokenIn,
                tokenOut,
                amountIn,
                block.timestamp
            )
        );
        
        pendingSwaps[swapId] = PendingSwap({
            tokenIn: tokenIn,
            tokenOut: tokenOut,
            amountIn: amountIn,
            minAmountOut: minAmountOut,
            deadline: deadline,
            recipient: msg.sender
        });
        
        emit SwapCreated(swapId, msg.sender, tokenIn, tokenOut, amountIn);
    }
    
    function executeProtectedSwap(bytes32 swapId) external {
        PendingSwap memory swap = pendingSwaps[swapId];
        require(swap.recipient == msg.sender, "Not authorized");
        require(block.timestamp <= swap.deadline, "Expired");
        require(block.number >= swap.blockNumber + MIN_DELAY, "Too early");
        
        // Verify slippage protection
        uint256 currentAmountOut = _getQuote(swap.tokenIn, swap.tokenOut, swap.amountIn);
        require(
            currentAmountOut >= swap.minAmountOut,
            "Slippage exceeded"
        );
        
        // Execute swap
        _executeSwap(swap);
        
        delete pendingSwaps[swapId];
        emit SwapExecuted(swapId, currentAmountOut);
    }
}

Gas Limit Optimization

Gas Estimation Strategies

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract GasOptimized {
    struct Data {
        uint256 value;
        bool flag;
        address target;
    }
    
    mapping(uint256 => Data) public data;
    
    // Gas-efficient batch update
    function batchUpdate(
        uint256[] calldata ids,
        uint256[] calldata values,
        bool[] calldata flags
    ) external {
        uint256 len = ids.length;
        require(len == values.length && len == flags.length, "Length mismatch");
        
        for (uint256 i = 0; i < len; ) {
            data[ids[i]].value = values[i];
            data[ids[i]].flag = flags[i];
            unchecked { ++i; }
        }
    }
    
    // Gas-efficient storage packing
    struct PackedData {
        uint128 value1;
        uint128 value2;
        address target;
        bool isActive;
    }
    
    mapping(uint256 => PackedData) public packedData;
    
    function updatePacked(
        uint256 id,
        uint128 value1,
        uint128 value2,
        bool isActive
    ) external {
        packedData[id] = PackedData({
            value1: value1,
            value2: value2,
            target: msg.sender,
            isActive: isActive
        });
    }
}

Gas Limit Estimation Table

OperationGas CostOptimization
SSTORE (cold)21,500Pack storage
SSTORE (warm)2,900Reuse slots
SLOAD (cold)2,100Cache values
SLOAD (warm)100Keep in memory
CALL (external)100+Minimize calls
CREATE232,000+Use CREATE
LOG375+Minimize events

Batch Transactions

Multicall Pattern

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract Multicall {
    struct Call {
        address target;
        bytes data;
        uint256 value;
    }
    
    struct Result {
        bool success;
        bytes returnData;
    }
    
    function aggregate(
        Call[] calldata calls
    ) external returns (Result[] memory results) {
        results = new Result[](calls.length);
        
        for (uint256 i = 0; i < calls.length; ) {
            (bool success, bytes memory returnData) = calls[i].target.call{
                value: calls[i].value
            }(calls[i].data);
            
            results[i] = Result({
                success: success,
                returnData: returnData
            });
            
            unchecked { ++i; }
        }
    }
    
    function tryAggregate(
        Call[] calldata calls
    ) external returns (Result[] memory results) {
        results = new Result[](calls.length);
        
        for (uint256 i = 0; i < calls.length; ) {
            (bool success, bytes memory returnData) = calls[i].target.call{
                value: calls[i].value
            }(calls[i].data);
            
            results[i] = Result({
                success: success,
                returnData: returnData
            });
            
            unchecked { ++i; }
        }
    }
}

Batch Transaction Gas Savings

CallsIndividual GasBatched GasSavings
121,00021,0000%
5105,00045,00057%
10210,00085,00060%
20420,000165,00061%
501,050,000405,00061%

Gas Tokens

CHI Gas Token

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract CHIGasToken {
    mapping(address => uint256) public balanceOf;
    
    uint256 public constant TOTAL_SUPPLY = 13_611_294_676_837_538_538_537_994;
    
    function mint(uint256 amount) external {
        require(amount <= 150, "Amount too high");
        
        for (uint256 i = 0; i < amount; ) {
            address clone;
            assembly {
                let ptr := mload(0x40)
                mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
                mstore(add(ptr, 20), address())
                mstore(add(ptr, 34), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
                clone := create(0, ptr, 53)
            }
            balanceOf[clone] += 1;
            unchecked { ++i; }
        }
    }
    
    function burn(address token) external {
        uint256 amount = balanceOf[token];
        require(amount > 0, "No balance");
        
        balanceOf[token] = 0;
        
        // Gas refund from SELFDESTRUCT
        (bool success, ) = token.call("");
        require(success, "Burn failed");
    }
}

Gas Token Economics

TokenRefundMinting CostProfit Margin
CHI24,000 gas~50,000 gasVariable
GST224,000 gas~50,000 gasVariable
None0 gas0 gasN/A

Trade-offs

StrategyGas SavingsComplexitySecurityRecommended
EIP-1559MediumLowHighYes
FlashbotsHighMediumHighYes
Batch TxHighLowHighYes
Gas TokensVariableHighMediumExpert
Storage PackingHighMediumHighYes

Real-World Example: Uniswap V3 Router

Uniswap V3 implements advanced gas optimization:

// Simplified Uniswap V3 Router
contract SwapRouter {
    struct SwapState {
        uint256 amountSpecified;
        uint256 sqrtPriceX96;
        int24 tick;
    }
    
    function exactInputSingle(
        ExactInputSingleParams calldata params
    ) external returns (uint256 amountOut) {
        // Gas-optimized swap execution
        SwapState memory state = SwapState({
            amountSpecified: params.amountIn,
            sqrtPriceX96: pool.sqrtPriceX96(),
            tick: pool.tick()
        });
        
        // Execute swap with minimal gas
        while (state.amountSpecified > 0) {
            // Process swap step
        }
        
        return state.amountSpecified;
    }
}

Interview Questions

  1. Explain how EIP-1559's base fee mechanism works. How does it affect transaction prioritization?

  2. What is MEV (Maximal Extractable Value) and how does Flashbots Protect users from sandwich attacks?

  3. Design a gas-optimized batch transaction system for a DEX that needs to process 100 swaps efficiently.

Quiz Questions

  1. What is the maximum base fee adjustment per block in EIP-1559?

    • A) 5%
    • B) 10%
    • C) 12.5%
    • D) 25%
  2. Which service provides a private mempool to protect against MEV?

    • A) MetaMask
    • B) Flashbots
    • C) Etherscan
    • D) Infura
  3. What is the primary purpose of gas tokens like CHI?

    • A) Reduce gas price
    • B) Store gas for later use
    • C) Get gas refunds
    • D) Pay for transactions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement