# `leverageAmount` is incorrect in  `SGLLeverage.sellCollateral` function due to calculation based on the new states of YieldBox after withdrawal

SGLLeverage.sellCollateral computes leverageAmount via yieldBox.toAmount after withdrawal, overstating tokens and reverting getAsset, DoSing sellCollateral.

- Payout: Contest reward
- Severity: medium
- Program: Tapioca
- Credited: bin2chen
- Disclosed: 2024-02-14
- Write-up quality: 6/10
- Original: https://github.com/sherlock-audit/2024-02-tapioca-judging/issues/61
- Library page: https://bugbountylibrary.com/r/sherlock%3A2024-02-tapioca%3AM-9
- Tags: domain:web3 impact:dos kind:contest platform:sherlock sev:medium tech:evm tech:solidity technique:source-review vuln:accounting-error vuln:business-logic vuln:dos

**Target:** SGLLeverage/BBLeverage sellCollateral in Tapioca-bar
**Root cause:** leverageAmount is derived from yieldBox.toAmount after the withdraw already mutated total shares/tokens, so rounding makes it exceed the actual withdrawn amount.
**Steps:**
1. Call `SGLLeverage.sellCollateral` with `calldata_.share` shares.
2. Function calls `yieldBox.withdraw(collateralId, address(this), address(leverageExecutor), 0, calldata_.share)` first.
3. Then computes `leverageAmount = yieldBox.toAmount(collateralId, calldata_.share, false)` on post-withdraw state.
4. With 100 shares/109 tokens, withdrawing 10 shares yields 10 tokens but toAmount returns 11.
5. `leverageExecutor.getAsset(...)` pulls leverageAmount and reverts for insufficient balance.
**How found:** Code reading of sellCollateral ordering: noticed toAmount called after withdraw mutates YieldBox totals, and rounding-down makes the recomputed amount larger than actual.
**Insight:** When a share-to-asset conversion is needed after a state-mutating withdraw, use the withdraw return value; recomputing toAmount post-mutation with rounding-down inflates the figure.
