Skip to content
DoS Audit finding Intermediate

Incorrect assumption in PoolMath.sol can cause underflow when zapping is used

The smart contract's zap swap calculation assumes that after right-shifting large numbers to fit within 80 bits, the condition r1 * z0 > r0 * z1 still holds, but shifting can reduce z0 to zero, causing an underflow and a revert. An attacker could trigger this by calling depositLiquidityAndIncreaseShare with useZapping set to true and specific amounts, causing the transaction to fail.

t0x1c Follow with Draiakoo and AgileJune

Originally disclosed on Code4rena

Submitted by t0x1c, also found by Draiakoo and AgileJune

_zapSwapAmount() assumes that:

191:		// r1 * z0 guaranteed to be greater than r0 * z1 per the conditional check in _determineZapSwapAmount
192:        uint256 C = r0 * ( r1 * z0 - r0 * z1 ) / ( r1 + z1 );

The protocol’s assumption of r1 * z0 guaranteed to be greater than r0 * z1 is based on the following check in _determineZapSwapAmount():

214:		// zapAmountA / zapAmountB exceeds the ratio of reserveA / reserveB? - meaning too much zapAmountA
215:		if ( zapAmountA * reserveB > reserveA * zapAmountB )
216:			(swapAmountA, swapAmountB) = (_zapSwapAmount( reserveA, reserveB, zapAmountA, zapAmountB ), 0);
217:
218:		// zapAmountA / zapAmountB is less than the ratio of reserveA / reserveB? - meaning too much zapAmountB
219:		if ( zapAmountA * reserveB < reserveA * zapAmountB )
220:			(swapAmountA, swapAmountB) = (0, _zapSwapAmount( reserveB, reserveA, zapAmountB, zapAmountA ));

The assumption would had been true for all cases if not for this piece of logic inside _zapSwapAmount()#L158-L168 which right shifts the arguments if the maximumMSB is greater than 80:

    	// Assumes the largest number has more than 80 bits - but if not then shifts zero effectively as a straight assignment.
    	// C will be calculated as: C = r0 * ( r1 * z0 - r0 * z1 ) / ( r1 + z1 );
    	// Multiplying three 80 bit numbers will yield 240 bits - within the 256 bit limit.
		if ( maximumMSB > 80 )
			shift = maximumMSB - 80;

    	// Normalize the inputs to 80 bits.
    	uint256 r0 = reserve0 >> shift;
		uint256 r1 = reserve1 >> shift;
		uint256 z0 = zapAmount0 >> shift;
		uint256 z1 = zapAmount1 >> shift;

This can lead to z0 being reduced to 0 and hence causing underflow on L192.

Since _determineZapSwapAmount() is internally called whenever depositLiquidityAndIncreaseShare() is called with useZapping = true, it will cause a revert when a situation like the following exists:

        uint256 reserveA = 1500000000;
        uint256 reserveB = 2000000000 ether;
        uint256 zapAmountA = 150;
        uint256 zapAmountB = 100 ether;

maximumMSB in this case is 90 (for reserveB) and also an excess of zapAmountA is being provided as compared to the existing reserve ratio. Hence, right shift by 90 - 80 = 10 bits will occur resulting z0 to be 0.

Proof of Concept

Create a new file src/stable/tests/BugPoolMath.t.sol and add the following code. Run it via forge test -vv --mt test_poolMath to see the test revert:

// SPDX-License-Identifier: Unlicensed
pragma solidity =0.8.22;

import "../../pools/PoolMath.sol";
import { console, Test } from "forge-std/Test.sol";

contract BugPoolMath is Test
{
    function test_poolMath() public view {
        uint256 reserveA = 1500000000;
        uint256 reserveB = 2000000000 ether;
        uint256 zapAmountA = 150;
        uint256 zapAmountB = 100 ether;

        (uint256 swapAmountA, uint256 swapAmountB) = PoolMath._determineZapSwapAmount(reserveA, reserveB, zapAmountA, zapAmountB);
        console.log("swapAmountA = %s, swapAmountB = %s", swapAmountA, swapAmountB);
    }
}

Tools used

Foundry

Recommended Mitigation Steps

Make sure to check the assertion again:

    function _zapSwapAmount( uint256 reserve0, uint256 reserve1, uint256 zapAmount0, uint256 zapAmount1 ) internal pure returns (uint256 swapAmount)
    	{
    	uint256 maximumMSB = _maximumMSB( reserve0, reserve1, zapAmount0, zapAmount1);

		uint256 shift = 0;

    	// Assumes the largest number has more than 80 bits - but if not then shifts zero effectively as a straight assignment.
    	// C will be calculated as: C = r0 * ( r1 * z0 - r0 * z1 ) / ( r1 + z1 );
    	// Multiplying three 80 bit numbers will yield 240 bits - within the 256 bit limit.
		if ( maximumMSB > 80 )
			shift = maximumMSB - 80;

    	// Normalize the inputs to 80 bits.
    	uint256 r0 = reserve0 >> shift;
		uint256 r1 = reserve1 >> shift;
		uint256 z0 = zapAmount0 >> shift;
		uint256 z1 = zapAmount1 >> shift;

		// In order to swap and zap, require that the reduced precision reserves and one of the zapAmounts exceed DUST.
		// Otherwise their value was too small and was crushed by the above precision reduction and we should just return swapAmounts of zero so that default addLiquidity will be attempted without a preceding swap.
        if ( r0 < PoolUtils.DUST)
        	return 0;

        if ( r1 < PoolUtils.DUST)
        	return 0;

        if ( z0 < PoolUtils.DUST)
        if ( z1 < PoolUtils.DUST)
        	return 0;

        // Components of the quadratic formula mentioned in the initial comment block: x = [-B + sqrt(B^2 - 4AC)] / 2A
		uint256 A = 1;
        uint256 B = 2 * r0;

		// Here for reference
//        uint256 C = r0 * ( r0 * z1 - r1 * z0 ) / ( r1 + z1 );
//        uint256 discriminant = B * B - 4 * A * C;

-		// Negate C (from above) and add instead of subtract.
-		// r1 * z0 guaranteed to be greater than r0 * z1 per the conditional check in _determineZapSwapAmount
-       uint256 C = r0 * ( r1 * z0 - r0 * z1 ) / ( r1 + z1 );
-       uint256 discriminant = B * B + 4 * A * C;
+       uint256 C;
+       uint256 discriminant;
+       if ((r1 * z0) >= (r0 * z1)) {
+           C = r0 * ( r1 * z0 - r0 * z1 ) / ( r1 + z1 );
+           discriminant = B * B + 4 * A * C;
+       } else {
+           C = r0 * ( r0 * z1 - r1 * z0 ) / ( r1 + z1 );
+           discriminant = B * B - 4 * A * C;
+       }

        // Compute the square root of the discriminant.
        uint256 sqrtDiscriminant = Math.sqrt(discriminant);

		// Safety check: make sure B is not greater than sqrtDiscriminant
		if ( B > sqrtDiscriminant )
			return 0;

        // Only use the positive sqrt of the discriminant from: x = (-B +/- sqrtDiscriminant) / 2A
		swapAmount = ( sqrtDiscriminant - B ) / ( 2 * A );

		// Denormalize from the 80 bit representation
		swapAmount <<= shift;
    	}

othernet-global (Salty.IO) confirmed and commented:

Zapping no longer uses scaling:

https://github.com/othernet-global/salty-io/commit/44320a8cc9b94de433e437e025f072aa850b995a

Status: Mitigation confirmed. Full details in reports from zzebra83, 0xpiken, and t0x1c.


The original report as published on Code4rena, by t0x1c. 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

The code assumes that after right-shifting to normalise inputs to 80 bits, the inequality r1 * z0 > r0 * z1 still holds, but shifting can make z0 zero, violating the assumption and causing an underflow.

Impact

A user calling depositLiquidityAndIncreaseShare with useZapping set to true and certain amounts will experience a transaction revert, preventing them from adding liquidity.

What the attacker needed

UseZapping set to true; specific reserve and zap amounts

The fix

The fix was to remove scaling from zapping, as confirmed by the protocol team.

How it was found

  1. Call depositLiquidityAndIncreaseShare with useZapping set to true and amounts that cause maximumMSB > 80 and an excess of zapAmountA.
  2. The function _determineZapSwapAmount is called, which calls _zapSwapAmount with the given reserves and zap amounts.
  3. Inside _zapSwapAmount, the inputs are right-shifted by maximumMSB - 80, which can reduce z0 to zero.
  4. The calculation r1 * z0 - r0 * z1 underflows because r1 * z0 is zero and r0 * z1 is positive, causing a revert.

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.

In a smart contract, numbers are stored with fixed precision. To avoid overflow when multiplying large numbers, the code shifts them right (dividing by a power of two), which loses precision. If a small number is shifted too far, it becomes zero, and a later subtraction can go negative, which is not allowed and causes the transaction to fail. This means a user trying to add liquidity with a zap could see their transaction revert unexpectedly.

What is DoS?

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.

More by t0x1c

View all

19 more disclosed reports, best first.

More from Salty.IO

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.