Skip to content
Business logic Audit finding Advanced

Fee market post handler misses to account for gas consumed after taking the gas snapshot, leading to higher refunds and unpaid gas

The fee market post handler refunds unspent gas based on a gas snapshot taken before burning fees and refunding the tip, so the user is not charged for gas consumed by those later operations. An attacker could exploit this to pay less gas than actually consumed, leading to unaccounted gas consumption.

berndartmueller Follow

Originally disclosed on Code4rena

Submitted by berndartmueller

Finding description and impact

Mantra’s xfeemarket post handler refunds unspent gas after the transaction is executed. For this, in line 99, a snapshot of the gas consumed is taken, which is then used to calculate the refund (tip) via skip-mev’s CheckTxFee() in line 112.

However, this gas snapshot does not account for any gas consumed after the snapshot is taken, such as the gas consumed by burning the gas fees and the bank transfer that refunds the tip. As a result, the user is not charged for the gas consumed by these operations, leading to unaccounted gas consumption and potential abuse.

Proof of Concept

x/xfeemarket/post/fee.go#L99-L116

A gas snapshot is taken in line 99 to calculate the refund in CheckTxFee() in line 112.

099: feeGas := int64(feeTx.GetGas()) // @audit-info snapshot of gas consumed
...  // [...]
110:
111: if !simulate {
112: 	payCoin, tip, err = ante.CheckTxFee(ctx, minGasPrice, payCoin, feeGas, false)
113: 	if err != nil {
114: 		return ctx, err
115: 	}
116: }

skip-mev/[email protected]/x/feemarket/ante/fee.go::CheckTxFee()

The CheckTxFee() function calculates the refund based on the gas snapshot and returns the payCoin and tip, which are burned/locked and refunded, respectively.

But those operations consume gas, which the user is not charged for.

Recommended mitigation steps

Consider defining a gas constant for those operations (e.g., BankSendGasConsumption = 12490 + 37325, which is only used during simulations) and charge the user for the gas consumed by them. This will prevent potential abuse and ensure that the user is charged for all gas consumed during the transaction.

3docSec (judge) commented:

Maybe a misunderstanding. Looking at the code it seems to me that the refund is lower than it should (gas consumed in the burn/lock and refund operations is paid but not refunded).

Lance Lan (MANTRA) disputed and commented:

L99 is actually just the gas limit, the naming is confusing. L112 it calculates the payCoin and tip which the tip is refunded. I agree that operations the burn and refund is not paid gas; however, this is very low impact.

3docSec (judge) commented:

Marking as valid Low. The warden is welcome to provide a coded PoC during QA session if they believe this finding can leak meaningful (i.e. more than slightly incorrect gas calculation) value.

berndartmueller (warden) commented:

It’s true that L99 is the gas limit, not a gas snapshot. I was confusing things. But it does not affect the validity of the issue, because CheckTxFee(..) calculates the tip that will be refunded based on the gas used by getting a gas snapshot in https://github.com/skip-mev/feemarket/blob/f1f216e15aa6bcc05075a7079496764820a0f545/x/feemarket/ante/fee.go#L240. Any subsequent gas usage will not be paid for by the user, i.e., the tip will be larger than it should.

Here’s a simple PoC that shows how much gas is used after ante.CheckTxFee(..) internally takes a gas snapshot, which is not paid for by the user as it will increase the refunded tip.

Add the following lines after x/xfeemarket/post/fee.go#L117

+ snapshot := ctx.GasMeter().GasConsumed()

and after L141

Add lines after x/xfeemarket/post/fee.go#L141

err = dfd.feemarketKeeper.SetState(ctx, state)
if err != nil {
    return ctx, errorsmod.Wrapf(err, "unable to set fee market state")
}

+ // figure out the diff of gas consumed since snapshot
+ gasDiff := ctx.GasMeter().GasConsumed() - snapshot
+ fmt.Println("gasDiff", gasDiff)

if simulate {
    // consume the gas that would be consumed during normal execution
    ctx.GasMeter().ConsumeGas(BankSendGasConsumption, "simulation send gas consumption")
}

Copy paste the following test case to x/xfeemarket/post/fee_test.go

func TestPostHandle_Audit(t *testing.T) {
	// Same data for every test case
	const (
		baseDenom           = "stake"
		resolvableDenom     = "atom"
		expectedConsumedGas = 59122

		gasLimit = 100000
	)

	validFeeAmount := types.DefaultMinBaseGasPrice.MulInt64(int64(gasLimit))
	validFee := sdk.NewCoins(sdk.NewCoin(baseDenom, validFeeAmount.TruncateInt()))

	testCases := []postsuite.TestCase{
		{
			Name: "signer has enough funds, should pass, with tip",
			Malleate: func(s *postsuite.TestSuite) postsuite.TestCaseArgs {
				accs := s.CreateTestAccounts(1)

				balance := postsuite.TestAccountBalance{
					TestAccount: accs[0],
					Coins:       validFee,
				}
				s.SetAccountBalances([]postsuite.TestAccountBalance{balance})

				return postsuite.TestCaseArgs{
					Msgs:      []sdk.Msg{testdata.NewTestMsg(accs[0].Account.GetAddress())},
					GasLimit:  gasLimit,
					FeeAmount: validFee,
				}
			},
			RunAnte:           true,
			RunPost:           true,
			Simulate:          false,
			ExpPass:           true,
			ExpErr:            nil,
			ExpectConsumedGas: 34836,
			Mock:              false,
		},
	}

	for _, tc := range testCases {
		t.Run(fmt.Sprintf("Case %s", tc.Name), func(t *testing.T) {
			s := postsuite.SetupTestSuite(t, tc.Mock)
			s.TxBuilder = s.ClientCtx.TxConfig.NewTxBuilder()
			args := tc.Malleate(s)

			s.RunTestCase(t, tc, args)
			s.Fail("fail")
		})
	}
}

Running the test logs shows the leaked gas diff since taking a snapshot after CheckTxFee(..) (which is not 100% accurate, but it demonstrates the issue):

gasDiff 28909

Compared to a simple bank send tx (https://explorer.mantrachain.io/MANTRA-1/tx/FBA240100B1D4115C2D2D53A23AC0036787EE241E30C9AA10441B3400380E668), which e.g. consumed 151517 gas, that’s 28,909 / 151,517 = 19% of the gas of such a tx which is significant gas leakage.

3docSec (judge) commented:

Agreed, that percentage of the gas accounting being off for reasonably popular transactions is enough impact for Medium severity.


The original report as published on Code4rena, by berndartmueller. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the gas snapshot used to calculate the refund is taken before additional gas-consuming operations (burning fees and refunding the tip), so those costs are not deducted from the refund.

What the attacker needed

None

The fix

The code should define a gas constant for the burn and refund operations and charge the user for that gas.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

When you send a transaction on a blockchain, you pay for the computing power used, called gas. This report found that the system refunded some gas fees without charging for the gas used to process the refund itself, so users could end up paying less than they should.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by berndartmueller

View all

97 more disclosed reports, best first.

More from MANTRA Chain

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.