# Wrong implementation of orderbook can make user can't get their fund back

OrderBook._remove decrements index.length, so next _insert reuses the removed slot's id and overwrites the latest order, locking that owner's funds.

- Payout: Contest reward
- Severity: high
- Program: Knox
- Credited: Trumpero
- Disclosed: 2022-09-21
- Write-up quality: 7/10
- Original: https://github.com/sherlock-audit/2022-09-knox-judging/issues/66
- Library page: https://bugbountylibrary.com/r/sherlock%3A2022-09-knox%3AH-4
- Tags: domain:web3 impact:funds-loss impact:integrity kind:contest platform:sherlock sev:high tech:solidity technique:source-review vuln:accounting-error vuln:business-logic

**Target:** OrderBook.sol auction limit-order storage (addLimitOrder/cancelLimitOrder)
**Root cause:** _remove decrements index.length instead of tracking freed ids, and _insert assigns id = index.length + 1, so a new order reuses the id of the most recently removed order and overwrites the existing order at that id.
**Steps:**
1. buyer1 addLimitOrder(epoch, 10, size) -> id=1, index.length=1
2. buyer2 addLimitOrder(epoch, 20, size) -> id=2, index.length=2
3. buyer1 cancelLimitOrder(epoch, 1) -> index.length=1
4. buyer3 addLimitOrder(epoch, 30, size) -> id=index.length+1=2, overwrites buyer2's order price 20->30
5. assert getOrderById(epoch,2).price64x64 == 30
**How found:** Code reading of _remove and _insert: noticed _remove shrinks index.length while _insert derives id from index.length+1, implying id reuse; confirmed with a Hardhat test showing order id=2 price flipping from 20 to 30.
**Exploitation:** Any user can cancel an order then place a new limit order; the new order's id collides with the most recent live order and overwrites its price/size/buyer fields. The displaced owner can no longer withdraw their refunded ERC20 or exercised tokens.
**Insight:** In array-backed order books, shrinking a length counter on delete while deriving new ids from that counter causes id collision with the last live element; check delete/insert id derivation symmetry, not just bounds.
