Twav. getTwav() will return a wrong result when twavObservations[TWAV BLOCK_NUMBERS - 1].timestamp = 0.
The Twav contract's _getTwav() function checks if the timestamp of the last observation is zero, but timestamps are stored modulo 2^32, so a valid timestamp can be zero. This causes the function to return 0 instead of the correct time-weighted average value, affecting buy and sell functions.
Originally disclosed on Code4rena
Submitted by hansfriese
The “if” condition of Twav._getTwav() is missing some edge cases.
In this case, this function will return 0 which is different from the correct value and it will affect the main functions like NibblVault.buy() and NibblVault.sell().
Proof of Concept
I think this condition is to confirm at least 4 values were saved for twav calculation.
Btw this timestamp would be zero even though there are more than 4 values properly as it’s modularized by 2**32.
In this case, the if condition will be false and this function will return 0.
Tools Used
Solidity Visual Developer of VSCode
Recommended Mitigation Steps
I see “cumulativeValuation” is increasing all the time and recommend replacing “timestamp” with “cumulativeValuation”.
if (twavObservations[TWAV_BLOCK_NUMBERS - 1].cumulativeValuation != 0) {
mundhrakeshav (Nibbl) confirmed and resolved
HardlyDifficult (judge) commented:
Interesting catch. This is related to #178 but presents a distinct issue.
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 timestamp field is stored as a 32-bit value that wraps around, so a valid timestamp can be zero, and the check for zero incorrectly treats it as missing data.
Impact
The incorrect average could affect the buy and sell functions, potentially leading to wrong pricing or calculations.
What the attacker needed
None
The fix
The check should use cumulativeValuation instead of timestamp, as cumulativeValuation is always increasing and never zero after the first observation.
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 smart contract calculates an average price using stored observations. It checks if the last observation's timestamp is zero to decide if enough data exists. But timestamps are stored in a way that wraps around, so a real timestamp can be zero, making the check fail and return a wrong average.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.