Skip to content

Execution

DEX gas fees and failed swaps: calculate execution cost

Follow one swap intention across an approval, a revert and a confirmed replacement, then reconcile network charges without double counting.

Ivory ceramic hand press above intact and cracked discs with lime powder scattered on a dark tray.
Illustration for execution; examples in this article are educational.

On Ethereum, a failed DEX swap still costs gas when the transaction is included in a block and execution reverts. The swap's token changes roll back, but gas already used remains payable. Calculate the execution fee from actual gas used and effective gas price, then add separately confirmed approvals and other included attempts. Pending, rejected and replaced transactions require different treatment.

A wallet's failed-swap message is therefore the start of the investigation. Find which transaction reached the chain, what it did, and which account paid. This guide uses ordinary sender-paid Ethereum layer 1 transactions. All numerical records below are hypothetical; they are not current gas quotations or measured swap costs.

Classify the attempt before assigning a fee

Ethereum charges for computational work whether included execution succeeds or fails, as its gas documentation explains. A simulation error before submission has a different status from an included transaction that runs and reverts.

Observed stateWhat the evidence establishesNetwork-fee treatment
Simulation fails; nothing broadcastProposed call did not become an on-chain transactionNo on-chain execution fee from that simulation
User rejects signingThat proposed transaction was not authorized for submissionNo fee from the rejected proposal
Broadcast hash, still pendingSubmission exists; execution outcome remains unresolvedDo not book an estimated maximum as a settled fee
Included receipt reports failureExecution failed at transaction levelRecord the actual network charge
Included receipt reports successTransaction completed at transaction levelRecord the charge, then verify the intended swap
Original hash replaced by a confirmed same-nonce transactionThe included replacement consumed that sender nonceCharge the included transaction; do not charge an unexecuted original

A missing receipt does not prove permanent failure, cancellation or a zero final bill. Ethereum's JSON-RPC reference states that receipts are unavailable for pending transactions. Preserve the unresolved state until there is enough evidence to classify it.

Use receipt values instead of the wallet ceiling

For an ordinary Ethereum layer 1 swap transaction, calculate the execution fee as:

fee in ETH = gasUsed × effectiveGasPrice in wei ÷ 10¹⁸

If the price is expressed in gwei, use:

fee in ETH = gasUsed × effectiveGasPrice in gwei ÷ 10⁹

The receipt's gasUsed belongs to that transaction. Do not substitute cumulativeGasUsed, which includes earlier transactions in the same block. effectiveGasPrice gives the actual price paid per gas unit. Both fields are defined in the receipt schema.

gasLimit caps available gas; maxFeePerGas caps the per-unit price for a type-2 transaction. They are useful for authorization and funding checks, but their product is not the final charge. EIP-1559 specifies how the base fee and priority fee interact with the maximum fee.

For example, a hypothetical limit of 250,000 gas and a 40-gwei maximum implies a 0.010000 ETH execution-fee ceiling. A receipt showing 165,000 gas at 22 gwei instead produces 0.003630 ETH. Do not record the ceiling and then add the actual fee to it.

A normal contract revert does not automatically consume all remaining gas. That behavior is specified by EIP-140. Running out of gas is a different failure. Neither a successful swap's estimate nor another failed swap's receipt establishes what this attempt consumed.

A four-record ledger for one completed swap

Suppose one trading intention is to exchange tokens with a $1,000 input benchmark. A separate token approval is needed first. The first swap attempt then reverts. A fresh attempt waits pending, and a fee-adjusted replacement of that pending transaction eventually succeeds.

Assume the approval and both included swap attempts belong to the same ordinary Ethereum account. The replacement preserves the intended call in this illustration. The records are verified against one canonical history after the chosen confirmation policy. The unexecuted original has no receipt, and its same-nonce replacement is confirmed included.

Use an invented reporting conversion of $3,000 per ETH for every row, solely to make the example reproducible.

RecordSender nonceVerified outcomeActual gas usedEffective priceExecution fee
A: token approval72Included, success46,00015 gwei0.000690 ETH
B: first swap73Included, reverted88,00018 gwei0.001584 ETH
C: fresh swap, original hash74Superseded; never included——0 ETH charged
D: replacement of C74Included, successful swap verified165,00022 gwei0.003630 ETH
Total for this intention—Three included transactions——0.005904 ETH

The arithmetic is 0.000690 + 0.001584 + 0.003630 = 0.005904 ETH. At the stated conversion, the network charges are $2.07 + $4.752 + $10.89 = $17.712, displayed as $17.71 after summing.

Looking only at D would report $10.89 and omit $6.822 of approved and failed work. The reverted attempt alone contributes about 26.83% of this example's network bill. The total is 177.12 basis points of the stated $1,000 benchmark: $17.712 ÷ $1,000 × 10,000. This is a network-cost comparison, not a full measure of trade performance.

The zero for C depends on the confirmed replacement evidence. It does not follow merely from a missing receipt. Ethereum's transaction documentation describes the sender nonce as a sequential counter. It follows that, in a single canonical history, the original and replacement cannot both execute as ordinary transactions from the same account with nonce 74. Keep both hashes under that nonce so they remain auditable.

Contrast this with B: its included revert consumed nonce 73 and incurred its own fee. The later transaction at nonce 74 is another attempt, not a replacement that erases B's charge. If a cancellation transaction wins the nonce race instead, record that included cancellation's fee and verify that the swap did not execute.

Keep network charges separate from the swap price

The ledger above contains network execution fees only. It does not add liquidity-provider fees, interface charges, token transfer deductions, or an execution-price difference against a benchmark. Those items need their own evidence and units.

A quoted or received token amount may already reflect pool trading fees and the route's price impact. Subtracting the quote-to-receipt difference and then adding an estimated pool fee can count overlapping effects twice. The transaction-cost analysis worksheet shows how to declare a benchmark and keep explicit charges separate from price differences.

For a transaction that fully reverts, the swap's execution state changes roll back. A separately successful approval remains a separate record; the later revert does not erase its fee or revoke the allowance. This distinction follows from the transaction boundary, not from a wallet's grouping of activities under one swap label.

Also inspect what “success” means for the router. The documented Uniswap Universal Router allow-revert flag can let a command fail while the overall transaction continues. A successful receipt therefore needs reconciliation with recipient balances, executed commands and residual funds before it becomes a verified completed swap.

Token mechanics can create another gap between a route preview and actual receipt. The guide to fee-on-transfer and rebasing tokens explains the accounting evidence to preserve. Record those token effects separately from ETH paid for network processing.

Retry from the failure evidence

A higher gas budget cannot correct every failed swap. First identify which condition failed. Uniswap Labs' transaction-failure guidance identifies slippage limits, expired deadlines, insufficient funds for network costs and token mechanics among its troubleshooting categories. The exact check still depends on the call being executed.

Use the failure to choose the next validation:

  • Amount protection failed: compare the signed minimum output or maximum input with a fresh route. Increasing tolerance authorizes a different result; inspect the absolute amounts before retrying.
  • Deadline expired: rebuild with an intentional time window and current quote. A fee increase does not repair an expired contract condition.
  • Execution ran out of gas: inspect the call and estimation assumptions before raising the gas limit. A larger limit can permit more work without fixing an underlying contract error.
  • Allowance or token transfer failed: verify token contract, spender, balance and supported router behavior. Repeating unchanged calldata may simply repeat the charge.
  • Outcome remains unknown: reconcile the sender nonce and candidate hashes before submitting another independent transaction.

The deadline-versus-slippage guide follows the independent time and amount guards. This fee ledger answers a later question: which attempts were included, and what did each actually cost?

Fresh data also matters before authorization. A quote from one time and a receipt from another do not describe the same observation. The REST-versus-WebSocket market-data comparison helps distinguish data delivery from the chain evidence needed to settle a fee record.

Save a receipt-based worksheet

Keep one parent record for the trading intention and one child record for each candidate transaction. A useful minimum is:

FieldEvidence to saveValidation
Network and payerChain ID, sender, fee-paying accountCorrect chain and account scope
Attempt identityHash, nonce, replacement linksDistinct hashes do not become duplicate charges
InclusionReceipt, block number and block hashHistory meets the recorded confirmation policy
Execution feeGas used, effective gas price, native amountRecompute using integer wei values
Swap resultToken contracts, recipient amounts, relevant logs and balancesIntended exchange actually completed
Cost scopeApproval, failed attempts, cancellation and extra chargesIncluded or excluded with a reason
Reporting conversionETH price source, timestamp and policyReproduce fiat values without changing native records

Convert for display after retaining the native amounts. If different transactions use different timestamped ETH prices, save each conversion. Do not silently apply today's price to an old fee ledger.

Change the fee model when the chain changes

The multiplication above is scoped to Ethereum layer 1 execution. For example, OP Mainnet's fee documentation describes execution gas, an L1 data fee and an operator fee after the relevant upgrade. The active fork affects the formula. Importing only gasUsed × effectiveGasPrice into an all-in rollup report can omit charges.

For another chain, relayed transaction or sponsored execution, identify the actual payer and documented fee components first. Then close the ledger only when every included attempt has a reconciled charge and every claimed completed swap has a verified token outcome. That produces a useful retry budget: actual spending to date, the next authorization ceiling, and a stated point at which to stop submitting attempts.

Keep the context with the example.

Each worked example is illustrative, with its sources and assumptions in the article. Read our editorial standards for authorship, verification and corrections.