From bc22fc862ad309be83aa5c86802e48e6623404f8 Mon Sep 17 00:00:00 2001 From: Trevor Richard Date: Wed, 4 Oct 2023 19:05:45 +0000 Subject: [PATCH] delete old observations to save gas --- src/libraries/DrawAccumulatorLib.sol | 15 +++++++++------ test/libraries/DrawAccumulatorLib.t.sol | 12 ++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/libraries/DrawAccumulatorLib.sol b/src/libraries/DrawAccumulatorLib.sol index 66152db..c4a9e78 100644 --- a/src/libraries/DrawAccumulatorLib.sol +++ b/src/libraries/DrawAccumulatorLib.sol @@ -88,6 +88,15 @@ library DrawAccumulatorLib { uint256 remainingAmount = integrateInf(_alpha, relativeDraw, newestObservation_.available); uint256 disbursedAmount = integrate(_alpha, 0, relativeDraw, newestObservation_.available); + uint16 cardinality = ringBufferInfo.cardinality; + if (ringBufferInfo.cardinality < MAX_CARDINALITY) { + cardinality += 1; + } else { + // Delete the old observation to save gas (older than 1 year) + uint24 overwritingDrawId = accumulator.drawRingBuffer[ringBufferInfo.nextIndex]; + delete accumulatorObservations[overwritingDrawId]; + } + accumulator.drawRingBuffer[ringBufferInfo.nextIndex] = _drawId; accumulatorObservations[_drawId] = Observation({ available: SafeCast.toUint96(_amount + remainingAmount), @@ -99,12 +108,6 @@ library DrawAccumulatorLib { ) }); - uint16 cardinality = ringBufferInfo.cardinality; - - if (ringBufferInfo.cardinality < MAX_CARDINALITY) { - cardinality += 1; - } - accumulator.ringBufferInfo = RingBufferInfo({ nextIndex: uint16(RingBufferLib.nextIndex(ringBufferInfo.nextIndex, MAX_CARDINALITY)), cardinality: cardinality diff --git a/test/libraries/DrawAccumulatorLib.t.sol b/test/libraries/DrawAccumulatorLib.t.sol index ae448e3..1f1a4f5 100644 --- a/test/libraries/DrawAccumulatorLib.t.sol +++ b/test/libraries/DrawAccumulatorLib.t.sol @@ -75,6 +75,18 @@ contract DrawAccumulatorLibTest is Test { assertEq(accumulator.observations[3].available, 281); } + function testAddOne_deleteExpired() public { + // set up accumulator as if we had just completed a buffer loop: + accumulator.drawRingBuffer[0] = 101; // set to some draw ID that isn't 0 or the one we'll be writing + accumulator.observations[101] = Observation(2, 3); + + DrawAccumulatorLib.add(accumulator, 100, 1, alpha); + assertEq(accumulator.ringBufferInfo.cardinality, 1); + assertEq(accumulator.ringBufferInfo.nextIndex, 1); + assertEq(accumulator.drawRingBuffer[0], 1); + assertEq(accumulator.observations[1].available, 100); + } + function testGetTotalRemaining() public { add(1);