Skip to content
Business logic Audit finding Advanced

Selling partial base tokens are more profitable then selling in one go

The WooFi swap formula makes selling base tokens in multiple smaller swaps more profitable than selling the same total amount in one swap, allowing users to bypass the maxNotionalSwap and maxGamma limits and receive more quote tokens.

Bandit Follow with mstpr-brainbot

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-03-woofi-swap-judging/issues/20

The protocol has acknowledged this issue.

Found by

Bandit, mstpr-brainbot

Summary

Selling base tokens partially instead of one go is always more profitable

Vulnerability Detail

First, let's write down our formulas of sellBase tokens for quoteTokens: g: gamma s: spread c: coefficient p: price np: new price (price after selling base tokens)

g = deltaBase * p * c deltaQuote = deltaBase * p * (1 - (g + s)) np = p * (1 - g)

Code snippet for the above formulas: https://github.com/sherlock-audit/2024-03-woofi-swap/blob/65185691c91541e33f84b77d4c6290182f137092/WooPoolV2/contracts/WooPPV2.sol#L591-L619

Here I graphed both sellQuote and sellBase functions: https://www.desmos.com/calculator/svmjlxhavw

As we can observe, if the price is >1 then the selling base tokens (red in the graph) will start decreasing after it reaches the middle value. Same happens vice versa when price is <1 for selling quote tokens (blue in the graph). This heavily incentivise smaller swaps and heavily disincentives bigger swaps. Also, since selling smaller amounts are ALWAYS more profitable, maxGamma and maxNotionalSwap values can be bypassed without a loss (even for profits)

Textual PoC: Now, let's do a textual example to see whether selling 20 base tokens is profitable then selling 2 times 10 base tokens For this example, let's assume: p = 1 c = 0.01 s = 0.1 and there are no swap fees for simplicity.

First, let's sell 20 base tokens: g = 20 * 1 * 0.01 = 0.2 deltaQuote = 20 * 1 * (1 - (0.1 + 0.1)) = 14 quote tokens received will be 14

Now, let's sell 10 base tokens in 2 times in a single transaction: g1 = 10 * 1 * 0.01 = 0.1 deltaQuote1 = 10 * 1 * (1- (0.1 + 0.1)) = 8 np = 1 * (1 - 0.1) = 0.9 received 8 quote tokens in first sell of 10 base tokens

g2 = 10 * 0.9 * 0.01 = 0.09 deltaQuote2 = 10 * 0.9 * (1 - (0.1 + 0.09)) = 7.29 received 7.29 quote tokens in second sell of 10 base tokens

in total 7.29 + 8 = 15.29 quote tokens received! however, if we were to swap 10 tokens in one go we would end up with 14 quote tokens!

This also means that swaps that are not possible because of maxNotionalSwap can be divided into partial swaps and the end result would be even higher! If the maxNotionalSwap is 100K USDC, someone can swap 2 times 50K USDC to receive even higher amount of quote tokens! Hence, the exploit that happent to WooFi would still be possible and even worse since the partial swaps are better than single go.

Here a test where it compares selling 1000 WETH in one go, 500-500 and 1-1-1-... 1000 times in a single tx:

Solidity
// @dev fee is "100", coeff = 0.000000001 * 1e18, spread = 0.001 * 1e18 as in the tests
    // setting fee to a different value is not relevant, attack is still there, just slighly less profitable
    
    // @dev sell 1000 in single tx
    function test_SellBase1Part() public {
        uint sellWethAmount = 1000 * 1e18;
        _fundAndApproveAdminAndTapir(1000_0000 * 1e6, sellWethAmount);

        vm.prank(TAPIR);
        uint receivedUSDC = router.swap(WETH, USDC, sellWethAmount, 0, payable(TAPIR), TAPIR);

        console.log("Received USDC", receivedUSDC);
        console.log("contract usdc balance", IERC20(USDC).balanceOf(address(pool)));
    }

    // @dev sell 500-500 in single tx
    function test_Sell2Parts() public {
        uint sellWethAmount = 1000 * 1e18;
        _fundAndApproveAdminAndTapir(1000_0000 * 1e6, sellWethAmount);
        
        uint cumulative;
        for (uint i; i < 2; ++i) {
            // sell 5 wei dust
            vm.prank(TAPIR);
            uint receivedUSDC = router.swap(WETH, USDC, sellWethAmount / 2, 0, payable(TAPIR), TAPIR);
            (uint128 price, ) = oracle.woPrice(WETH);
            cumulative += receivedUSDC;
        }

        console.log("Received USDC", cumulative);
        console.log("contract usdc balance", IERC20(USDC).balanceOf(address(pool)));
    }

    // @dev sell 1-1-1-1.... in single tx
    function test_Sell1000Parts() public {
        uint sellWethAmount = 1000 * 1e18;
        _fundAndApproveAdminAndTapir(1000_0000 * 1e6, sellWethAmount);
        
        uint cumulative;
        for (uint i; i < 1000; ++i) {
            // sell 5 wei dust
            vm.prank(TAPIR);
            uint receivedUSDC = router.swap(WETH, USDC, sellWethAmount / 1000, 0, payable(TAPIR), TAPIR);
            (uint128 price, ) = oracle.woPrice(WETH);
            cumulative += receivedUSDC;
        }

        console.log("Received USDC", cumulative);
        console.log("contract usdc balance", IERC20(USDC).balanceOf(address(pool)));
    }

Results: Selling 500-500 instead of 1000 in one go: 3395.800042 USDC more received Selling 1-1-1-1-... 1000 times instead 1000 in one go: 6776.505788 USDC more received!

Impact

Breaking the maxNotionalSwap amount and unfair AMM model

Code Snippet

Tool used

Manual Review

Recommendation

Discussion

fb-alexcq

Thanks for the feedback. This is a known scope when designing our SPMM formula. Again we want to follow up with:

  1. Seems like you're not considering the swap fee
  2. Split into multiple small swaps, only can save users from huge slippage, but it won't cause our protocol lose funds, right? 1000 times for 1 each looks like still not profitable to the attacker, right?

mstpr

The protocol will not lose funds, correct. However, the maxGamma and maxNotionalSwap variables will be rendered useless since partial swaps can be used to bypass these checks, making it even profitable to do so.

fb-alexcq

This extreme price-deviation case has already been handled by price check (against Chainlink) in our Wooracle's price function.

WangSecurity

Initially, it was a duplicate of 68, but these are different issues and it presents an unfair formule, therefore, we decided to keep this one as valid.

WangSecurity

Sponsor said that this AMM model is in fact intended, cause 99% of their swaps are small. But, it wasn't mentioned in the README, therefore, we validate this report as Med due to validation of maxGamma and maxNotionalSwap (core functionality break).

Banditx0x

@mstpr I believe the protocol does actually lose funds here:

  • The protocol acts as the liquidity provider
  • The net-result for a trader and LP in a trade is zero-sum.
  • If a trader unfairly avoids slippage by gaming the AMM formula, each $ saved by the trader is lost by the LP

Lmk your thoughts

Banditx0x

@fb-alexcq in response to something you brought up in issue 20 (duplicate):

Thanks for the feedback.

Technically it is okay to avoid huge slippage by splitting into small swaps, right? BTW, is there a way for attacker to get profits (instead of saving the loss) from the split swap? Better to consider there's a 2-5 bps swap fee.

I would like to emphasie that although splitting a very large swap into smaller ones reduces slippage in basically all AMM's, this slippage reduction is due to a trade in between swaps arbitraging the price of the AMM back to the correct price in between your multiple swaps. This is a core invariant of all widely used AMM formulas, and has significant second order consequences as detailed in issue #47 . Woofi's current formula is different from any widely used AMM formula in that it requires no -inbetween price corrections to get this slippage discount.

For example, in Uniswap v2, Uniswap v3, Curve, Balancer etc it doesn't matter if you swap 100 tokens or 1 token 100 times. As long as no transactions happen in between, the tokens returned will be the same.

I'd highly reccomend going back to the old formula which was consistent with this invariant unless it allows another type of vulnerability.

Banditx0x

Escalate.

I think it's high severity for above reasons.

Please consider this issue along with the reasoning provided in #47 . I believe me and @mstpr are providing different perspectives to the issue despite the same root cause.

Note that #47 demonstrates an example with a 2% slippage, and will continue to apply at lower slippage %'s so this actually applies even when 99% of the swaps are small.

Seems like you're not considering the swap fee

Addressing this: the swap fee is a percentage of the swap size. Therefore splitting a swap into multiple smaller swaps will result in basically the same sum of swap fees.

The formula allows certain users (one's that optimise and perfectly calculate swap splitting) a lower slippage. Normal users that use the User Interface or don't perfectly calculate their split sizes don't get the same privilege. Giving extremely advanced users lower AMM prices than everybody else is equivalent to loss of funds for the not-so-savvy swappers.

sherlock-admin2

Escalate.

I think it's high severity for above reasons.

Please consider this issue along with the reasoning provided in #47 . I believe me and @mstpr are providing different perspectives to the issue despite the same root cause.

Note that #47 demonstrates an example with a 2% slippage, and will continue to apply at lower slippage %'s so this actually applies even when 99% of the swaps are small.

Seems like you're not considering the swap fee

Addressing this: the swap fee is a percentage of the swap size. Therefore splitting a swap into multiple smaller swaps will result in basically the same sum of swap fees.

The formula allows certain users (one's that optimise and perfectly calculate swap splitting) a lower slippage. Normal users that use the User Interface or don't perfectly calculate their split sizes don't get the same privilege. Giving extremely advanced users lower AMM prices than everybody else is equivalent to loss of funds for the not-so-savvy swappers.

You've created a valid escalation!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

mstpr

@Banditx0x

If this is design choice, then someone making partial swaps will get more tokens, and yes, this would be loss of funds. Additionally, the maxGamma and maxNotionalSwap can easily be bypassed.

Example: If selling 10 base tokens should receive 5 quote tokens, and if someone selling 2-2-2-2-2 base tokens and receives 7 quote tokens at the end, than the 2 quote tokens would be the loss of protocol since they don't want this to happen in their AMM. Hence, high could be considered.

I think you are right with your comments, if this is design choice, then high would be appropriate.

WangSecurity

I believe it should remain medium cause, essentially, it is expected behaviour by the protocol which was confirmed by the sponsor. But, I believe breaking maxGamma and maxNotionalSwap is breaking core functionality, therefore, it's medium and not enough for a high.

I don't say that watsons above are wrong, I see and understand their points and will accept any decision by the head of judging.

Czar102

Kudos to @Banditx0x @mstpr for the deep understanding of the math.

As much as I like this finding, I don't think it presents a loss of funds per se, and there are no earnings to the "exploiters", the total (and marginal!) slippage still increases as more volume goes in any way. This is a math inconsistency, and I would be considering it as a borderline Low/Medium severity issue.

Given that an escalation only exists to increase the severity, I'm planning to reject it and leave the issue as is, and I will not consider downgrading this issue.

fb-alexcq

@mstpr @Banditx0x thanks for detailed follow and explanation.

Could you please send me the whole file of your foundry test, so that I can run it here in my environment? so that to better verify your raised issues.

BTW, could you also try your attach vector on our newly deployed WooPP going live this Monday? https://arbiscan.io/address/0xed9e3f98bbed560e66b89aac922e29d4596a9642 Is that possible to profit or swap for more tokens here in our new version?

mstpr

@fb-alexcq I plugged in the numbers from deployment to my desmos graph. With current values, if someone swaps 14_350 BTC they get "0" usdc token in exchange.

Another example: if you sell 1M USDC in one go you get: 14.41563574 WBTC

if you sell 1M USDC in 1000 iterations (1000, 1000, 1000....) you get: 14.42278414 WBTC

the difference is 0.0071484 WBTC, 500$

test (directly points the current deployment shared above) https://gist.github.com/mstpr/0a099688cb48cdc6bec42ceb1c322e8c

fb-alexcq

OK. Cool, Thanks.

This result is with Chainlink Oracle Guardian (+-5%) set up right ?

mstpr

Kudos to @Banditx0x @mstpr for the deep understanding of the math.

As much as I like this finding, I don't think it presents a loss of funds per se, and there are no earnings to the "exploiters", the total (and marginal!) slippage still increases as more volume goes in any way. This is a math inconsistency, and I would be considering it as a borderline Low/Medium severity issue.

Given that an escalation only exists to increase the severity, I'm planning to reject it and leave the issue as is, and I will not consider downgrading this issue.

What about looking at this angle?

If this is design choice, then swapping 1M USDC should result at 10 BTC. However, if you swap partially up to 1M USDC then you will end up with say 100 BTC. This 90 BTC difference is basically loss of funds for Woofi considering their design choice, right?

Czar102

@mstpr this is not a design choice, this is a math inconsistency, as I noted above.

As long as "it's fine" for the user to get 100 BTC for 1m USDC, then it's not loss of funds, but suboptimal strategy of the 1M USDC <> 10 BTC swapper. But given that the discrepancy in this case is rather minimal (we won't have 90% slippage), I stand by my previous comment.

Czar102

Result: Medium Has duplicates

sherlock-admin3

Escalations have been resolved successfully!

Escalation status:

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

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 automated market maker formula applies a price impact that depends on the size of each individual swap rather than the cumulative volume, so splitting a swap reduces the total price impact.

Impact

Users can bypass the maxNotionalSwap and maxGamma limits and receive more quote tokens than intended, which the protocol considers a medium-severity break of core functionality; the sponsor argued the model is intended and that the protocol does not lose funds.

What the attacker needed

Access to the swap function; sufficient base tokens to swap

The fix

The formula should be changed so that splitting a swap does not reduce the total price impact, for example by making the price impact depend on cumulative volume rather than individual swap size.

How it was found

  1. Set up a test with the pool and a user funded with base tokens.
  2. Sell the entire amount of base tokens in a single swap and record the quote tokens received.
  3. Sell the same total amount in two equal swaps within one transaction and record the cumulative quote tokens received.
  4. Sell the same total amount in many tiny swaps within one transaction and record the cumulative quote tokens received.
  5. Compare the results to see that splitting yields more quote tokens.

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 decentralised exchange, the price changes as you trade. Normally, splitting a large trade into smaller ones doesn't change the total amount you get, because the price moves between trades. Here, the formula itself gives a better average price for smaller trades, so someone can get more by breaking up a trade, and the limits meant to stop large trades can be avoided.

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 Bandit

View all

6 more disclosed reports, best first.

More from WOOFi Swap

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.