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 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
Flashbots Bundle
// 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
| Operation | Gas Cost | Optimization |
|---|---|---|
| SSTORE (cold) | 21,500 | Pack storage |
| SSTORE (warm) | 2,900 | Reuse slots |
| SLOAD (cold) | 2,100 | Cache values |
| SLOAD (warm) | 100 | Keep in memory |
| CALL (external) | 100+ | Minimize calls |
| CREATE2 | 32,000+ | Use CREATE |
| LOG | 375+ | 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
| Calls | Individual Gas | Batched Gas | Savings |
|---|---|---|---|
| 1 | 21,000 | 21,000 | 0% |
| 5 | 105,000 | 45,000 | 57% |
| 10 | 210,000 | 85,000 | 60% |
| 20 | 420,000 | 165,000 | 61% |
| 50 | 1,050,000 | 405,000 | 61% |
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
| Token | Refund | Minting Cost | Profit Margin |
|---|---|---|---|
| CHI | 24,000 gas | ~50,000 gas | Variable |
| GST2 | 24,000 gas | ~50,000 gas | Variable |
| None | 0 gas | 0 gas | N/A |
Trade-offs
| Strategy | Gas Savings | Complexity | Security | Recommended |
|---|---|---|---|---|
| EIP-1559 | Medium | Low | High | Yes |
| Flashbots | High | Medium | High | Yes |
| Batch Tx | High | Low | High | Yes |
| Gas Tokens | Variable | High | Medium | Expert |
| Storage Packing | High | Medium | High | Yes |
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
-
Explain how EIP-1559's base fee mechanism works. How does it affect transaction prioritization?
-
What is MEV (Maximal Extractable Value) and how does Flashbots Protect users from sandwich attacks?
-
Design a gas-optimized batch transaction system for a DEX that needs to process 100 swaps efficiently.
Quiz Questions
-
What is the maximum base fee adjustment per block in EIP-1559?
- A) 5%
- B) 10%
- C) 12.5%
- D) 25%
-
Which service provides a private mempool to protect against MEV?
- A) MetaMask
- B) Flashbots
- C) Etherscan
- D) Infura
-
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