# absolute difference is not calculated properly when a > b in MathUtils

MathUtils.difference underflows when a > b, breaking within1 checks in HybridPool and enabling manipulation of pool invariant calculations.

- Payout: Audit contest
- Severity: high
- Program: Sushi
- Found by: hack3r-0m
- Disclosed: 2021-11-22
- Write-up quality: 6/10
- Original: https://github.com/code-423n4/2021-09-sushitrident-findings/issues/139
- Library page: https://bugbountylibrary.com/r/c4%3A2021-09-sushitrident%3AH-12
- Tags: area:web3 domain:web3 impact:funds-loss kind:contest platform:code4rena sev:high tech:evm tech:solidity technique:source-review vuln:accounting-error vuln:business-logic

**Target:** Solidity library MathUtils / HybridPool invariant checks
**Root cause:** difference(a,b) computes b - a unconditionally inside unchecked, so when a > b it underflows to a huge value instead of returning a - b.
**Steps:**
1. Read MathUtils.sol L22: `unchecked { diff = b - a; }`
2. Observe difference(a, a-1) returns type(uint256).max, so within1(a, a-1) is false
3. Observe difference(type(uint256).max, 0) returns 1, so within1 wrongly true
4. Trace within1 usage at HybridPool.sol L359, L383, L413 in the y-calculation
5. Craft constants/inputs to decrease denominator and increase numerator so within1 fails, breaking the invariant check
**How found:** Code review of MathUtils.difference; noticed the unchecked subtraction lacks an a > b branch, then enumerated boundary cases and traced within1 call sites in HybridPool.
**Exploitation:** Manipulate pool inputs so the within1 invariant check on the computed y value fails or passes incorrectly, allowing the HybridPool invariant to be violated during swaps/liquidity operations.
**Insight:** In unchecked Solidity math, always test both orderings of subtraction; a helper used only inside a tolerance check can silently invert its boolean at the uint256 boundary and disable an invariant guard.

