From e7b8f479c7105bae5245e11851acbe2a99b7c9e9 Mon Sep 17 00:00:00 2001 From: Sergey Ponomarev Date: Fri, 10 Mar 2023 17:37:42 +0300 Subject: [PATCH] Adapt round lookup in case of empty history ringbuffer (#21) --- contracts/libraries/Utils.sol | 2 +- test/libraries/utils.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/contracts/libraries/Utils.sol b/contracts/libraries/Utils.sol index a14c96e..3d87e29 100644 --- a/contracts/libraries/Utils.sol +++ b/contracts/libraries/Utils.sol @@ -127,7 +127,7 @@ library Utils { { uint32 liveStartRoundId = saturatingSub(latestRoundId, liveLength - 1); uint32 historicalEndRoundId = latestRoundId - (latestRoundId % granularity); - uint32 historicalStartRoundId = saturatingSub(historicalEndRoundId, granularity * (historicalLength - 1)); + uint32 historicalStartRoundId = saturatingSub(historicalEndRoundId, granularity * saturatingSub(historicalLength, 1)); // If withing the live range, fetch from it. Otherwise, fetch from the closest previous in history. if (roundId >= liveStartRoundId && roundId <= latestRoundId) { diff --git a/test/libraries/utils.js b/test/libraries/utils.js index 1cda1d3..e9e84e9 100644 --- a/test/libraries/utils.js +++ b/test/libraries/utils.js @@ -253,5 +253,33 @@ contract("Utils", () => { assert.equal(position, 7); }); }) + + describe('when historical data does not present', async () => { + const liveCursor = 0 + const liveLength = 1 + const latestRoundId = 38 + const historicalCursor = 0 + const historicalLength = 0 + const granularity = 1 + + it('reverts', async () => { + try { + await utils.locateRound( + 42, + liveCursor, + liveLength, + latestRoundId, + historicalCursor, + historicalLength, + granularity + ); + throw null; + } + catch (error) { + assert(error, "Expected an error but did not get one"); + assert(error.message.endsWith("No data present"), "Expected no data present error, but received " + error); + } + }); + }) }) });