The function calculateTimeWeightedAverage in contracts/libraries/math/TimeWeightedAverage.sol is advertised as capable of handling both sequential and overlapping periods with associated weights. However, the function currently fails to handle overlapping periods correctly, leading to inaccurate Time-Weighted Average Price (TWAP) calculations.
In TimeWeightedAverage.sol#L194, the calculateTimeWeightedAverage function is intended to compute the TWAP by considering multiple periods with their corresponding weights. However, the function assumes that periods do not overlap, which results in an incorrect calculation when periods do overlap.
In the example provided, two periods have identical start and end times, causing them to overlap. As a result, the TWAP is computed incorrectly because the function does not account for the overlap and treats the periods as separate. The function does not merge overlapping periods before calculating the weighted average.
In this example, periods 0 and 1 overlap, both starting at time 1 and ending at time 4. The expected TWAP for these periods should be 115, calculated as the average of the values 100 (from periods 0 and 1) and 130 (from period 2). However, since the function does not handle overlapping periods correctly, the result is incorrectly computed as 110, effectively double-counting the value from time 1 to time 4.
The failure of the calculateTimeWeightedAverage function to correctly handle overlapping periods can lead to inaccurate TWAP calculations. Inaccurate TWAP values may cause financial losses or incorrect decisions to be made based on faulty data. This vulnerability is particularly impactful in decentralized finance (DeFi) protocols or applications that rely on accurate price or value calculations.
Manual code review
Foundry (for testing and verification)
Modify the calculateTimeWeightedAverage function to properly handle overlapping periods by merging them before performing the TWAP calculation.
Implement checks to detect overlapping periods and ensure they are handled correctly, such as merging periods with identical start and end times.
Test the function thoroughly with various overlapping and sequential periods to ensure that the TWAP calculation is robust and accurate under all scenarios.
The contest is live. Earn rewards by submitting a finding.
This is your time to appeal against judgements on your submissions.
Appeals are being carefully reviewed by our judges.