# When calling LeverageMacroBase.doOperation to open a CDP, the POST CALL CHECK may use the wrong cdpId

LeverageMacroBase post-call check assumes new CDP is last index, but NICR ordering can place it earlier, so wrong cdpId is validated.

- Payout: Contest reward
- Severity: medium
- Program: eBTC Protocol
- Credited: nobody2018
- Disclosed: 2024-02-13
- Write-up quality: 6/10
- Original: https://github.com/code-423n4/2023-10-badger-findings/issues/152
- Library page: https://bugbountylibrary.com/r/c4%3A2023-10-badger%3AM-05
- Tags: domain:web3 impact:funds-loss kind:contest platform:code4rena sev:medium tech:evm tech:solidity technique:source-review vuln:business-logic

**Target:** LeverageMacroBase.doOperation CDP open post-check
**Root cause:** initialCdpIndex is the pre-existing CDP count, but cdpOfOwnerByIndex walks the NICR-sorted list from tail; a new CDP with lower NICR than an existing owned CDP is not at that index, so the wrong cdpId is returned.
**Steps:**
1. Have `this` own CDP A; sorted list has 10 CDPs.
2. Call `doOperation` with `postCheckType=openCdp`; `initialCdpIndex = cdpCountOf(this) = 1`.
3. Open new CDP B whose NICR is lower than A's, so B is inserted before A in the descending-NICR list.
4. Post-check calls `cdpOfOwnerByIndex(this, 1)`, which walks from tail and returns A instead of B.
5. Checks `expectedDebt`/`expectedCollateral`/`expectedStatus` run against A, not B.
**How found:** Code reading of doOperation's post-call check: noticed initialCdpIndex is a count, then traced cdpOfOwnerByIndex walking the NICR-sorted linked list from tail, realizing insertion order can differ from index order.
**Exploitation:** Not weaponized; impact is either tx revert (gas waste) or post-check passing against the wrong CDP, potentially allowing funds loss from the macro contract or caller.
**Insight:** When a contract derives an index from a count and later resolves it against a sorted linked list, verify the list's ordering invariant; new inserts may not land at the tail, so count-based indexing is unsafe.
