Semi-erroneous Median Value
The NFT floor oracle's median calculation returns the upper middle value when there is an even number of valid prices, instead of averaging the two middle values. This can produce an incorrect median price, affecting any function that relies on the finalised time-weighted average price (twap).
Originally disclosed on Code4rena
Submitted by RaymondFam
In NFTFloorOracle.sol, _combine() returns a validated medianPrice on line 429 after having validPriceList sorted in ascending order.
It will return a correct median as along as the array entails an odd number of valid prices. However, if there were an even number of valid prices, the median was supposed to be the average of the two middle values according to the median formula below:
Median Formula
= ordered list of values in data set
= number of values in data set
The impact could be significant in edge cases and affect all function calls dependent on the finalized twap.
Proof of Concept
Let’s assume there are four valid ether prices each of which is 1.5 times more than the previous one:
validPriceList = [1000, 1500, 2250, 3375]
Instead of returning (1500 + 2250) / 2 = 1875, 2250 is returned, incurring a 20% increment or 120 price deviation.
Recommended Mitigation Steps
Consider having line 429 refactored as follows:
if (validNum % 2 != 0) {
return (true, validPriceList[validNum / 2]);
}
else
return (true, (validPriceList[validNum / 2] + validPriceList[(validNum / 2) - 1]) / 2);
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the median calculation only handles odd-length arrays correctly and returns the upper middle element for even-length arrays instead of averaging the two middle elements.
Impact
The incorrect median could significantly affect edge cases and all function calls that depend on the finalised twap.
What the attacker needed
Even number of valid prices
The fix
The code should be refactored to check if the number of valid prices is odd and return the middle element, otherwise return the average of the two middle elements.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A median is the middle number in a sorted list. When the list has an even count, the median should be the average of the two middle numbers. This code instead picks the higher of the two, so the reported price can be too high.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.