# Incorrect Debt Tracking in `_updateRepaymentState`

Off-by-one array-length check after removal in CrossChainRouter._updateRepaymentState mis-tracks userBorrowedAssets, enabling collateral withdrawal with debt or blocking liquidation.

- Payout: Audit contest
- Severity: high
- Program: Lend Audit Contest
- Found by: 37H3RN17Y2
- Disclosed: 2025-05-22
- Write-up quality: 6/10
- Original: https://github.com/sherlock-audit/2025-05-lend-audit-contest-judging/issues/672
- Library page: https://bugbountylibrary.com/r/sherlock%3A2025-05-lend-audit-contest%3AH-13
- Tags: area:web3 domain:web3 impact:funds-loss kind:contest platform:sherlock sev:high tech:solidity technique:source-review vuln:accounting-error vuln:business-logic vuln:liquidation

**Target:** CrossChainRouter.sol _updateRepaymentState (LayerZero cross-chain lending)
**Root cause:** The code checks userCrossChainCollaterals.length == 1 after removeCrossChainCollateral already shrank the array, so the last-debt case (length 1→0) skips removeUserBorrowedAsset and the two-debt case (2→1) wrongly removes it.
**Steps:**
1. User has one cross-chain borrow (e.g. 100 USDC) on chain B with collateral on chain A.
2. Call repayCrossChainBorrow with _amount = type(uint256).max to fully repay.
3. _updateRepaymentState removes the collateral entry, then checks length==1 on the now-empty array, so removeUserBorrowedAsset is skipped.
4. _lToken remains in userBorrowedAssets despite zero debt, allowing collateral withdrawal without debt validation.
5. With two borrows, repaying one shrinks length 2→1 and wrongly removes _lToken from userBorrowedAssets while debt remains, breaking liquidation.
**How found:** Code reading of _updateRepaymentState: noticed the length check occurs after removeCrossChainCollateral mutates the array, producing an off-by-one in both the 1-element and 2-element cases.
**Exploitation:** Borrower fully repays a single cross-chain debt, leaving a phantom entry in userBorrowedAssets; the stale tracking lets them withdraw collateral that should be locked against debt, or in the two-debt case hides remaining debt from liquidation logic.
**Insight:** When auditing array-mutation helpers, verify whether length/emptiness checks run before or after the removal call; post-removal checks silently shift the boundary by one and flip both the last-element and second-to-last cases.

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

**Buggy length check after removeCrossChainCollateral**

```
if (repayAmountFinal == borrowedAmount) {
    lendStorage.removeCrossChainCollateral(borrower, _token, index);
    if (userCrossChainCollaterals.length == 1) {
        lendStorage.removeUserBorrowedAsset(borrower, _lToken);
    }
}
```

