# Vault: The attacker can sandwich attack himself on swaps in open_position, close_position and reduce_position to make a bad debt

Vault checks leverage before swapping borrowed tokens; attacker sets infinite slippage and self-sandwiches the swap, leaving an undercollateralized bad-debt position.

- Payout: Contest reward
- Severity: high
- Program: Unstoppable
- Credited: 0xyPhilic
- Disclosed: 2023-06-21
- Write-up quality: 6/10
- Original: https://github.com/sherlock-audit/2023-06-unstoppable-judging/issues/140
- Library page: https://bugbountylibrary.com/r/sherlock%3A2023-06-unstoppable%3AH-3
- Tags: domain:web3 impact:funds-loss kind:contest platform:sherlock sev:high tech:evm tech:solidity technique:chained vuln:accounting-error vuln:business-logic vuln:oracle-manipulation

**Target:** MarginDex Vault.vy open_position/close_position/reduce_position swaps
**Root cause:** max_leverage is validated before the borrow-and-swap, and the swap slippage is attacker-controlled with no post-swap liquidity check, so the recorded position amount reflects a manipulated swap output.
**Steps:**
1. Call MarginDex open_position with attacker-controlled slippage set to infinite (min output ~0)
2. Within the same transaction, sandwich the Vault's swap: manipulate pool reserves before the swap and reverse after, capturing nearly all swapped tokens
3. Vault records the tiny swap output as position collateral, leaving the position undercollateralized
4. Repeat on close_position/reduce_position swaps to extract value and leave bad debt
**How found:** Code review of Vault.vy: noticed max_leverage check occurs before the swap and that swap slippage is caller-controlled, so the health check is stale relative to the actual swap outcome.
**Exploitation:** Attacker opens a leveraged position via MarginDex; the Vault borrows and swaps into the position token. By sandwiching its own swap (front-run reserve manipulation, back-run reversal) with infinite slippage tolerance, the attacker pockets the swap output while the Vault books an undercollateralized position, leaving protocol bad debt.
**Escalation:** Same primitive applied to close_position and reduce_position swaps to repeatedly drain value; flash loans can supply liquidity to manipulate reserves.
**Insight:** When a health/leverage check runs before a price-sensitive swap, the check is stale: look for caller-controlled slippage plus no post-swap liquidity re-check, enabling self-sandwich to manufacture bad debt.
