Skip to content

Commit

Permalink
delete old observations to save gas
Browse files Browse the repository at this point in the history
  • Loading branch information
trmid committed Oct 4, 2023
1 parent 439c6f3 commit bc22fc8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/libraries/DrawAccumulatorLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions test/libraries/DrawAccumulatorLib.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit bc22fc8

Please sign in to comment.