# Users are credited more tokens when paying back debt with registerTradeAndBorrow

Marginswap's registerTradeAndBorrow credits the full outAmount as deposit after also using it to repay debt, letting users double-credit and drain funds.

- Payout: Audit contest
- Severity: high
- Program: Marginswap
- Disclosed: 2021-05-03
- Write-up quality: 6/10
- Original: https://github.com/code-423n4/2021-04-marginswap-findings/issues/24
- Library page: https://bugbountylibrary.com/r/c4%3A2021-04-marginswap%3AH-06
- Tags: area:web3 domain:web3 impact:funds-loss kind:contest platform:code4rena sev:high technique:source-review vuln:accounting-error vuln:business-logic

**Target:** registerTradeAndBorrow / adjustAmounts accounting in Marginswap lending contract
**Root cause:** registerTradeAndBorrow repays debt with outAmount then calls adjustAmounts crediting the full outAmount again as deposit, instead of only outAmount - extinguishableDebt as registerDeposit does.
**Steps:**
1. Call `registerTradeAndBorrow` with trade results (`inAmount`, `outAmount`) while holding debt.
2. Contract repays debt using `outAmount`.
3. Contract calls `adjustAmounts(account, tokenFrom, tokenTo, sellAmount, outAmount)` crediting full `outAmount` as deposit.
4. User is credited twice the `outAmount`; withdraw the extra profit.
5. Repeat until protocol funds are empty.
**How found:** Compared registerTradeAndBorrow against registerDeposit, noticing registerDeposit credits only outAmount - extinguishableDebt while registerTradeAndBorrow credits the full outAmount after repayment.
**Exploitation:** User with outstanding debt performs a trade via registerTradeAndBorrow; the outAmount both extinguishes debt and is fully re-credited as deposit, yielding one outAmount of free credit per call. Withdrawing and repeating drains protocol liquidity.
**Insight:** When two functions share accounting logic (deposit vs trade-and-repay), diff how each computes the credited amount after debt repayment; a full-amount credit where a net-amount credit is expected signals double-counting.

