# Merging tranches could make _loanTermination() accounting incorrect 

Permissionless mergeTranches() reassigns a loan's loanId, so _loanTermination() misattributes repayment to the pool instead of the correct withdrawal queue, corrupting accounting.

- Payout: Audit contest
- Severity: high
- Program: Gondi
- Found by: minhquanym
- Disclosed: 2024-07-25
- Write-up quality: 7/10
- Original: https://github.com/code-423n4/2024-04-gondi-findings/issues/69
- Library page: https://bugbountylibrary.com/r/c4%3A2024-04-gondi%3AH-01
- Tags: area:web3 domain:web3 impact:funds-loss impact:integrity kind:contest platform:code4rena sev:high tech:solidity technique:source-review vuln:accounting-error vuln:business-logic

**Target:** Pool / MultiSourceLoan Solidity contracts
**Root cause:** _loanTermination() locates a loan's withdrawal queue by comparing loanId against getLastLoanId per queue, but mergeTranches() mints a new higher loanId for the merged tranche, so the lookup no longer matches the original queue.
**Steps:**
1. Borrower opens loanId=100 with two tranches both from pool_address; getLastLoanId[1][loan]=100.
2. Attacker calls mergeTranches() on the two same-lender tranches; new tranche gets newLoanId=101.
3. Loan is repaid/liquidated; _loanTermination() runs with _loanId=101.
4. Loop over queues never finds getLastLoanId[idx] >= 101, so i==totalQueues and loan is treated as pool-owned instead of queue index 1.
5. Queue accounting (getTotalReceived, getAvailableToWithdraw, _queueOutstandingValues) is never updated for the real queue.
**How found:** Code reading of _loanTermination()'s queue-selection loop keyed on loanId, cross-referenced with mergeTranches() assigning a fresh _newLoanId, revealing the invariant that loanId ordering maps to queue membership can be broken.
**Exploitation:** Attacker permissionlessly merges tranches of a pool-funded loan to bump its loanId above all queue lastLoanIds; on repayment the accounting is credited to the pool rather than the withdrawal queue, misallocating received funds and outstanding values.
**Insight:** When accounting logic derives a resource's bucket from a monotonically increasing ID compared against per-bucket last-IDs, check every path that can mint a new ID for an existing object (merges, splits, migrations) — those silently move objects across buckets.

## Proof of concept (copied exactly from the original report)

**mergeTranches assigns new loanId to merged tranche**

```
tranche[_minTranche] = IMultiSourceLoan.Tranche(
    _newLoanId, // @audit can be used to change loanId
    _loan.tranche[_minTranche].floor,
    principalAmount,
    lender,
    accruedInterest,
    startTime,
    cumAprBps / principalAmount
);
```

