# MarginTrading.sol: The whole balance and not just the traded funds are deposited into Aave when a trade is opened

MarginTrading._openTrade deposits the contract's entire token balance into Aave as margin, not just swap-acquired funds, exposing idle balances to unintended trade losses.

- Payout: Contest reward
- Severity: medium
- Program: Dodo
- Credited: roguereddwarf
- Disclosed: 2023-05-04
- Write-up quality: 6/10
- Original: https://github.com/sherlock-audit/2023-05-dodo-judging/issues/72
- Library page: https://bugbountylibrary.com/r/sherlock%3A2023-05-dodo%3AM-1
- Tags: domain:web3 impact:funds-loss kind:contest platform:sherlock sev:medium tech:evm tech:solidity vuln:accounting-error vuln:business-logic

**Target:** MarginTrading.sol _openTrade / MarginTradingFactory deposit functions
**Root cause:** _openTrade reads IERC20(_tradeAssets[i]).balanceOf(address(this)) after the swap and deposits that full balance into Aave, instead of only the delta acquired by the swap, sweeping pre-existing idle funds into margin.
**Steps:**
1. Deposit funds via MarginTradingFactory.depositMarginTradingERC20/ETH with `margin=false` so tokens sit in the MarginTrading contract but are not lent to Aave.
2. Open a trade calling MarginTrading._openTrade with `_tradeAssets` including that token.
3. Observe `_tradeAmounts[i] = IERC20(_tradeAssets[i]).balanceOf(address(this))` captures the pre-existing balance plus swap output.
4. `_lendingPoolDeposit(_tradeAssets[i], _tradeAmounts[i], 1)` deposits the entire amount into Aave as margin.
5. Trade incurs larger loss than intended because idle funds now back the position.
**How found:** Read the factory deposit functions and noticed `margin=false` intentionally leaves funds in the MarginTrading contract, then compared that expectation against `_openTrade` using full `balanceOf` rather than a delta.
**Insight:** When a contract supports both 'idle balance' and 'deposited collateral' states, check every code path that reads `balanceOf(address(this))` — full-balance reads silently sweep idle funds into collateral; compare pre/post balances to isolate the intended delta.
