Assessment reports>Avon>Medium findings>Incorrect heapify index in OrderbookLib._matchOrder causing heap corruption
Category: Coding Mistakes

Incorrect heapify index in OrderbookLib._matchOrder causing heap corruption

Medium Impact
Medium Severity
High Likelihood

Description

The _matchOrder function in OrderbookLib contains a heap corruption bug when handling partial order fills. After reducing an entry's amount in a partial fill, the code incorrectly increments the index i before calling _heapifyDown, causing the heap maintenance operation to be performed on the wrong index.

The heap is ordered by available liquidity (descending), meaning larger liquidity amounts should be at the root. When an entry's amount is reduced, it needs to be moved down the heap to maintain this property. However, the code performs heapify on index i+1 instead of index i where the modification occurred.

Impact

This bug progressively corrupts the min-heap structure used for order matching, leading to:

  • Orders not being matched in the correct priority order (best liquidity/rates first)

  • Lenders with better rates potentially being skipped

  • Borrowers receiving worse rates than available in the orderbook

  • Violation of the protocol's core promise of efficient order matching

While this doesn't directly cause loss of funds, it undermines the fundamental fairness and efficiency of the orderbook mechanism, potentially causing users to receive suboptimal matches.

} else {
    i++;                               // Bug: increment happens before heapify
    tree._heapifyDown(compositeKey, i); // This operates on i+1, not the modified index
}

Recommendations

Maintain the heap property at the correct index by performing heapify before incrementing:

} else {
    tree._heapifyDown(compositeKey, i); // Heapify at the index we just modified
    i++;                                // Then move to next index
}

Remediation

This issue has been acknowledged by AVON TECH LTD, and a fix was implemented in commit 1c7ea3d2.

Zellic © 2025Back to top ↑