ChainScore Labs
All Guides

How DeFi Aggregators Handle Failed Transactions

LABS

How DeFi Aggregators Handle Failed Transactions

Chainscore © 2025

Common Causes of Transaction Failure

Transactions in DeFi can fail for various technical and economic reasons, leading to wasted gas and lost opportunities. Understanding these causes is crucial for developers and users to optimize their interactions and manage risk.

Insufficient Gas

Gas estimation errors occur when the provided gas limit is too low for the transaction's computational needs. This is common with complex contract interactions or during network congestion. Aggregators often add a buffer, but user-set limits can still cause failures. Failed transactions still consume gas up to the limit, resulting in a net loss for the user.

Slippage Tolerance Exceeded

Price impact from large trades or low liquidity can move the market price beyond a user's set slippage tolerance. For example, a 5% slippage setting on a token with a thin order book may be insufficient during volatile swings. Aggregators compare real-time quotes to the user's threshold and will revert the transaction if exceeded to prevent unfavorable execution.

Insufficient Liquidity

Liquidity fragmentation across DEXs and pools means the aggregated route may not have enough depth to fulfill the entire order. A swap for 1000 ETH will fail if the best combined liquidity across all sources is only 800 ETH. Aggregators must dynamically split orders and may partially fill or revert if minimum output cannot be met.

Expired Deadline

Transaction deadline is a timestamp parameter that causes a revert if the transaction is not mined before it passes. This protects against stale transactions being executed at outdated prices. For instance, a 20-minute deadline on a slow network during high congestion can easily expire. Aggregators monitor mempool status and may need to resubmit with updated parameters.

Smart Contract Reverts

Revert conditions within the target protocol's logic, such as failing a health check in a lending protocol or a transfer restriction on a token. An attempt to borrow with insufficient collateral or swap a paused token will be rejected by the contract. Aggregators must simulate transactions to catch these errors before broadcasting to the network.

Nonce Conflicts & Replacement

Pending transaction replacement occurs when a new transaction is sent with the same nonce as an existing one stuck in the mempool. If the original transaction gets mined first, the replacement will fail. Aggregators managing user sessions must track nonces carefully and may implement strategies like gas bumping to clear the queue.

Aggregator Error Handling Pipeline

Process overview

1

Simulation and Pre-flight Checks

Execute a dry-run of the transaction to identify potential failures before broadcasting.

Detailed Instructions

Before submitting a transaction to the network, the aggregator performs a local simulation using a forked version of the blockchain state. This involves calling the target contract's functions with the proposed calldata and signer address via eth_call. The simulation checks for common failure modes like insufficient user balance, slippage tolerance breaches, or contract reverts.

  • Sub-step 1: Fork the mainnet state at the latest block using a node provider like Alchemy or Infura.
  • Sub-step 2: Execute the swap or trade logic on the forked chain with the user's address and parameters.
  • Sub-step 3: Parse the simulation result; a revert with a message like "execution reverted: DAI/insufficient-balance" indicates a failure.
javascript
// Example simulation call using ethers.js const simulationResult = await provider.call({ to: routerAddress, data: encodedSwapData, from: userAddress }); if (simulationResult === '0x') { // Transaction would succeed } else { // Decode revert reason const reason = ethers.utils.toUtf8String('0x' + simulationResult.slice(138)); console.log(`Simulation failed: ${reason}`); }

Tip: Always simulate with a gas limit higher than the estimated amount to avoid false positives from out-of-gas simulations.

2

Error Classification and Categorization

Analyze the failure reason and assign it to a specific retryable or non-retryable category.

Detailed Instructions

Once a failure is detected, the system parses the revert reason or error code to classify it. Retryable errors are temporary and may succeed on a subsequent attempt (e.g., temporary price impact, minor slippage). Non-retryable errors are fundamental and will not succeed without user intervention (e.g., insufficient allowance, invalid token).

  • Sub-step 1: Extract the revert string from the simulation or a failed on-chain transaction receipt.
  • Sub-step 2: Map common error signatures like 0x08c379a0 (Error(string)) or custom errors like InsufficientOutputAmount() to internal categories.
  • Sub-step 3: For slippage errors, calculate if adjusting the minReturn parameter by a configurable buffer (e.g., 0.5%) could allow a retry.
solidity
// Common error signatures from popular DEX routers bytes4 internal constant ERROR_SLIPPAGE = bytes4(keccak256("TooLittleReceived(uint256)")); bytes4 internal constant ERROR_EXPIRED = bytes4(keccak256("TransactionExpired()")); function classifyError(bytes memory revertData) internal pure returns (ErrorType) { bytes4 errorSig = bytes4(revertData); if (errorSig == ERROR_SLIPPAGE) return ErrorType.RETRYABLE; if (errorSig == ERROR_EXPIRED) return ErrorType.NON_RETRYABLE; // ... other checks }

Tip: Maintain a registry of error signatures from integrated protocols (Uniswap V3, Curve, etc.) for accurate classification.

3

Parameter Adjustment and Route Re-calculation

Modify transaction parameters or find an alternative liquidity route for retryable errors.

Detailed Instructions

For errors classified as retryable, the system dynamically adjusts parameters or searches for a new route. The core mechanism involves querying the aggregator's routing engine again with updated constraints, such as a higher slippage tolerance or a different deadline.

  • Sub-step 1: For a slippage failure, increment the slippageBps parameter. For example, increase from 50 basis points (0.5%) to 75 basis points, respecting a maximum user-defined cap.
  • Sub-step 2: Re-run the pathfinding algorithm, potentially excluding the DEX pool that caused the failure or splitting the trade across different protocols.
  • Sub-step 3: Re-simulate the new transaction with the adjusted route and parameters to confirm it passes pre-flight checks.
javascript
// Example of adjusting parameters for a retry async function adjustForRetry(failedRoute, error) { let newParams = { ...failedRoute.params }; if (error.type === 'SLIPPAGE') { // Increase slippage tolerance by 25 bps, max 200 bps newParams.slippageBps = Math.min(newParams.slippageBps + 25, 200); } if (error.type === 'EXPIRY') { // Set new deadline 10 minutes in the future newParams.deadline = Math.floor(Date.now() / 1000) + 600; } // Find a new route with adjusted parameters return await routingEngine.findBestRoute(newParams); }

Tip: Implement a circuit breaker to limit the number of re-calculation attempts per user request to prevent infinite loops.

4

Fallback Execution and State Reconciliation

Execute the fallback transaction and update internal state to reflect completion or permanent failure.

Detailed Instructions

This final step involves broadcasting the adjusted transaction or, if all retries fail, reporting the error. The system must also handle state reconciliation to ensure the user's on-chain position matches the aggregator's internal ledger, especially for partial successes.

  • Sub-step 1: Send the signed, adjusted transaction to the network with a higher priority fee to ensure timely inclusion in a block.
  • Sub-step 2: Monitor the transaction receipt. A status of 1 indicates success; 0 indicates a confirmed on-chain revert.
  • Sub-step 3: On success, parse the event logs to confirm the exact output amounts and update the user's balance in the aggregator's database. On final failure, log the error with all context for analysis and notify the user.
solidity
// Example of parsing a successful swap event (Uniswap V2) event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); function reconcileSwap(bytes memory receiptLogs) internal { (uint amountIn, uint amountOut) = abi.decode(receiptLogs, (uint, uint)); userBalance[tokenIn] -= amountIn; userBalance[tokenOut] += amountOut; }

Tip: Implement idempotency keys for user requests to prevent duplicate transactions if a retry is initiated while a previous one is still pending.

Gas Estimation and Optimization Strategies

Understanding Gas in Failed Transactions

Gas is the fee paid to execute operations on the Ethereum Virtual Machine. When a transaction fails, the gas spent on computation up to the point of failure is still consumed, known as gas spent on reversion. This is a critical cost for aggregators.

Why Transactions Fail

  • Slippage exceeded: The price moved beyond the user's specified tolerance before the transaction was mined.
  • Insufficient liquidity: A pool may not have enough tokens for the requested swap size at execution time.
  • Network congestion: High activity can cause unpredictable state changes, making pre-calculated routes invalid.

Aggregator's Role

Platforms like 1inch and Matcha estimate required gas and simulate transactions before submission. They use historical data to predict base fee and priority fee (tip) to ensure timely inclusion without overpaying. A failed transaction still costs gas, so accurate estimation is a direct user cost-saving measure.

Slippage Tolerance vs. MEV Protection

Comparison of user-defined slippage settings versus protocol-level MEV protection mechanisms in transaction routing.

ParameterHigh Slippage Tolerance (User-Set)Low Slippage Tolerance (User-Set)MEV-Protected Routing (Protocol)

Primary Goal

Guarantee transaction success

Minimize price impact

Prevent front-running & sandwich attacks

Typical Setting Range

1.0% - 5.0%

0.1% - 0.5%

N/A (Protocol logic)

Failure Rate on Volatile Pairs

< 5%

40%

Varies by protection efficacy

Avg. Cost of Failed Tx (Gas)

~$15 - $50 (wasted)

~$15 - $50 (wasted)

$0 (if revert-on-attack)

Susceptibility to MEV

High (easy target for sandwiches)

Low (often fails before attack)

Very Low (uses private RPCs, time boosts)

Price Improvement Potential

None (uses public mempool)

None (uses public mempool)

Up to 50 bps via order flow auctions

Implementation Layer

User wallet interface

User wallet interface

Aggregator smart contract & RPC network

Example Service/Feature

Uniswap UI default setting

Advanced trader setting

1inch Fusion mode, CowSwap

Refund and Recovery Mechanisms

How aggregators manage transaction failures, from gas estimation to automatic retries, ensuring user funds are protected and execution is optimized.

Gas Estimation and Buffer

Dynamic gas estimation is critical for success. Aggregators pull real-time data from mempools and use historical models to predict required gas. They then apply a gas buffer (e.g., 20-30%) to account for network volatility. This prevents "out of gas" failures, which otherwise result in lost transaction fees for the user.

Automatic Transaction Retry

Upon a revert, aggregators can automatically retry the transaction with adjusted parameters. This involves recalculating gas, potentially increasing the gas price, or using a different routing path. For example, a failed swap on Uniswap V3 might be retried on a different pool or DEX. This improves success rates without user intervention.

Simulation and Revert Analysis

Before broadcasting, transactions undergo pre-flight simulation on a forked network node. If a simulation fails, the aggregator analyzes the revert reason (e.g., "insufficient liquidity", "slippage exceeded"). This diagnostic allows the system to adjust the quote or abort the transaction preemptively, saving the user from paying for a guaranteed failure.

Partial Fill and Batch Refunds

For complex multi-step routes, partial fill protection ensures users get the best possible outcome. If one leg of a cross-chain swap fails, the aggregator may refund the unused portion of the input asset. Batch refunds are processed efficiently in a single transaction, minimizing gas costs when returning dust or leftover amounts from a failed multi-DEX operation.

Slippage Protection and Deadline

Slippage tolerance is a user-defined parameter that, if exceeded, causes the transaction to revert to prevent unfavorable swaps. Aggregators enforce a transaction deadline, a timestamp after which the trade is invalid. This protects users from pending transactions being executed minutes later at a worse price due to network congestion or MEV attacks.

Fallback Providers and RPC Management

To mitigate infrastructure-level failures, aggregators use fallback RPC providers. If the primary node is slow or unresponsive, the system switches to a secondary endpoint to submit the transaction. They also manage nonce tracking to prevent conflicts. This redundancy is crucial for maintaining reliability during public RPC outages or high network load periods.

SECTION-USER_SIDE_MITIGATION

User-Side Failure Mitigation

Ready to Start Building?

Let's bring your Web3 vision to life.

From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.