simplify time-based logic in tests, and fix requestEnd()

- use the `allowBlocksWithSameTimestamp` hardhat option
- remove block time gymnastics from marketplace tests
- fix erroneous implementation of requestEnd() which
  surfaced because of the the improved tests
This commit is contained in:
Mark Spanbroek 2025-01-30 09:34:42 +01:00
parent 6eeffb3c62
commit 0cc8f6c73f
7 changed files with 65 additions and 134 deletions

View File

@ -512,13 +512,14 @@ contract Marketplace is SlotReservations, Proofs, StateRetrieval, Endian {
} }
function requestEnd(RequestId requestId) public view returns (uint256) { function requestEnd(RequestId requestId) public view returns (uint256) {
uint256 end = _requestContexts[requestId].endsAt;
RequestState state = requestState(requestId); RequestState state = requestState(requestId);
if (state == RequestState.New || state == RequestState.Started) { if (state == RequestState.New || state == RequestState.Started) {
return end; return _requestContexts[requestId].endsAt;
} else {
return Math.min(end, block.timestamp - 1);
} }
if (state == RequestState.Cancelled) {
return _requestContexts[requestId].expiresAt;
}
return Math.min(_requestContexts[requestId].endsAt, block.timestamp);
} }
function requestExpiry(RequestId requestId) public view returns (uint256) { function requestExpiry(RequestId requestId) public view returns (uint256) {

View File

@ -24,6 +24,7 @@ module.exports = {
networks: { networks: {
hardhat: { hardhat: {
tags: ["local"], tags: ["local"],
allowBlocksWithSameTimestamp: true
}, },
codexdisttestnetwork: { codexdisttestnetwork: {
url: `${process.env.DISTTEST_NETWORK_URL}`, url: `${process.env.DISTTEST_NETWORK_URL}`,

View File

@ -23,14 +23,13 @@ const {
waitUntilSlotFailed, waitUntilSlotFailed,
patchOverloads, patchOverloads,
} = require("./marketplace") } = require("./marketplace")
const { maxPrice, payoutForDuration } = require("./price") const { maxPrice } = require("./price")
const { const {
snapshot, snapshot,
revert, revert,
mine,
ensureMinimumBlockHeight, ensureMinimumBlockHeight,
advanceTimeForNextBlock, advanceTime,
advanceTimeToForNextBlock, advanceTimeTo,
currentTime, currentTime,
} = require("./evm") } = require("./evm")
const { arrayify } = require("ethers/lib/utils") const { arrayify } = require("ethers/lib/utils")
@ -172,9 +171,7 @@ describe("Marketplace", function () {
it("emits event when storage is requested", async function () { it("emits event when storage is requested", async function () {
await token.approve(marketplace.address, maxPrice(request)) await token.approve(marketplace.address, maxPrice(request))
const expectedExpiry = (await currentTime()) + request.expiry
// We +1 second to the expiry because the time will advance with the mined transaction for requestStorage because of Hardhat
const expectedExpiry = (await currentTime()) + request.expiry + 1
await expect(marketplace.requestStorage(request)) await expect(marketplace.requestStorage(request))
.to.emit(marketplace, "StorageRequested") .to.emit(marketplace, "StorageRequested")
.withArgs(requestId(request), askToArray(request.ask), expectedExpiry) .withArgs(requestId(request), askToArray(request.ask), expectedExpiry)
@ -274,7 +271,7 @@ describe("Marketplace", function () {
// We need to advance the time to next period, because filling slot // We need to advance the time to next period, because filling slot
// must not be done in the same period as for that period there was already proof // must not be done in the same period as for that period there was already proof
// submitted with the previous `fillSlot` and the transaction would revert with "Proof already submitted". // submitted with the previous `fillSlot` and the transaction would revert with "Proof already submitted".
await advanceTimeForNextBlock(config.proofs.period + 1) await advanceTime(config.proofs.period + 1)
const startBalance = await token.balanceOf(host.address) const startBalance = await token.balanceOf(host.address)
const discountedCollateral = const discountedCollateral =
@ -421,7 +418,7 @@ describe("Marketplace", function () {
await token.approve(marketplace.address, request.ask.collateral) await token.approve(marketplace.address, request.ask.collateral)
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await advanceTimeForNextBlock(config.proofs.period) await advanceTime(config.proofs.period)
}) })
it("allows proofs to be submitted", async function () { it("allows proofs to be submitted", async function () {
@ -464,13 +461,12 @@ describe("Marketplace", function () {
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await expect( await expect(
(await marketplace.requestEnd(requestId(request))).toNumber() (await marketplace.requestEnd(requestId(request))).toNumber()
).to.be.closeTo(requestTime + request.ask.duration, 1) ).to.equal(requestTime + request.ask.duration)
}) })
it("sets request end time to the past once failed", async function () { it("sets request end time to the past once failed", async function () {
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilFailed(marketplace, request) await waitUntilFailed(marketplace, request)
let slot0 = { ...slot, index: request.ask.maxSlotLoss + 1 }
const now = await currentTime() const now = await currentTime()
await expect(await marketplace.requestEnd(requestId(request))).to.be.eq( await expect(await marketplace.requestEnd(requestId(request))).to.be.eq(
now - 1 now - 1
@ -481,7 +477,6 @@ describe("Marketplace", function () {
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
const now = await currentTime() const now = await currentTime()
await expect(await marketplace.requestEnd(requestId(request))).to.be.eq( await expect(await marketplace.requestEnd(requestId(request))).to.be.eq(
now - 1 now - 1
@ -491,11 +486,7 @@ describe("Marketplace", function () {
it("checks that request end time is in the past once finished", async function () { it("checks that request end time is in the past once finished", async function () {
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilFinished(marketplace, requestId(request)) await waitUntilFinished(marketplace, requestId(request))
await mine()
const now = await currentTime() const now = await currentTime()
// in the process of calling currentTime and requestEnd,
// block.timestamp has advanced by 1, so the expected proof end time will
// be block.timestamp - 1.
await expect(await marketplace.requestEnd(requestId(request))).to.be.eq( await expect(await marketplace.requestEnd(requestId(request))).to.be.eq(
now - 1 now - 1
) )
@ -558,7 +549,7 @@ describe("Marketplace", function () {
// We are advancing the time because most of the slots will be filled somewhere // We are advancing the time because most of the slots will be filled somewhere
// in the "expiry window" and not at its beginning. This is more "real" setup // in the "expiry window" and not at its beginning. This is more "real" setup
// and demonstrates the partial payout feature better. // and demonstrates the partial payout feature better.
await advanceTimeForNextBlock(request.expiry / 2) await advanceTime(request.expiry / 2)
const expectedPayouts = await waitUntilStarted( const expectedPayouts = await waitUntilStarted(
marketplace, marketplace,
@ -636,7 +627,7 @@ describe("Marketplace", function () {
).toNumber() ).toNumber()
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await advanceTimeToForNextBlock(filledAt) await advanceTimeTo(filledAt)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilCancelled(request) await waitUntilCancelled(request)
await marketplace.freeSlot(slotId(slot)) await marketplace.freeSlot(slotId(slot))
@ -656,7 +647,7 @@ describe("Marketplace", function () {
).toNumber() ).toNumber()
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await advanceTimeToForNextBlock(filledAt) await advanceTimeTo(filledAt)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilCancelled(request) await waitUntilCancelled(request)
const startBalanceHost = await token.balanceOf(host.address) const startBalanceHost = await token.balanceOf(host.address)
@ -791,6 +782,10 @@ describe("Marketplace", function () {
switchAccount(client) switchAccount(client)
await token.approve(marketplace.address, maxPrice(request)) await token.approve(marketplace.address, maxPrice(request))
await marketplace.requestStorage(request) await marketplace.requestStorage(request)
// wait a bit, so that there are funds for the client to withdraw
await advanceTime(10)
switchAccount(host) switchAccount(host)
await token.approve(marketplace.address, request.ask.collateral) await token.approve(marketplace.address, request.ask.collateral)
}) })
@ -932,7 +927,7 @@ describe("Marketplace", function () {
).toNumber() ).toNumber()
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await advanceTimeToForNextBlock(filledAt) await advanceTimeTo(filledAt)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilCancelled(request) await waitUntilCancelled(request)
const expectedPartialhostRewardRecipient = const expectedPartialhostRewardRecipient =
@ -989,7 +984,6 @@ describe("Marketplace", function () {
it("changes to 'Cancelled' once request is cancelled", async function () { it("changes to 'Cancelled' once request is cancelled", async function () {
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
expect(await marketplace.requestState(slot.request)).to.equal(Cancelled) expect(await marketplace.requestState(slot.request)).to.equal(Cancelled)
}) })
@ -1011,7 +1005,6 @@ describe("Marketplace", function () {
it("changes to 'Failed' once too many slots are freed", async function () { it("changes to 'Failed' once too many slots are freed", async function () {
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilFailed(marketplace, request) await waitUntilFailed(marketplace, request)
await mine()
expect(await marketplace.requestState(slot.request)).to.equal(Failed) expect(await marketplace.requestState(slot.request)).to.equal(Failed)
}) })
@ -1035,7 +1028,6 @@ describe("Marketplace", function () {
it("changes to 'Finished' when the request ends", async function () { it("changes to 'Finished' when the request ends", async function () {
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilFinished(marketplace, requestId(request)) await waitUntilFinished(marketplace, requestId(request))
await mine()
expect(await marketplace.requestState(slot.request)).to.equal(Finished) expect(await marketplace.requestState(slot.request)).to.equal(Finished)
}) })
@ -1064,16 +1056,14 @@ describe("Marketplace", function () {
}) })
async function waitUntilProofIsRequired(id) { async function waitUntilProofIsRequired(id) {
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime()))) await advanceTimeTo(periodEnd(periodOf(await currentTime())))
await mine()
while ( while (
!( !(
(await marketplace.isProofRequired(id)) && (await marketplace.isProofRequired(id)) &&
(await marketplace.getPointer(id)) < 250 (await marketplace.getPointer(id)) < 250
) )
) { ) {
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
} }
@ -1090,7 +1080,6 @@ describe("Marketplace", function () {
it("changes to 'Finished' when request finishes", async function () { it("changes to 'Finished' when request finishes", async function () {
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilFinished(marketplace, slot.request) await waitUntilFinished(marketplace, slot.request)
await mine()
expect(await marketplace.slotState(slotId(slot))).to.equal(Finished) expect(await marketplace.slotState(slotId(slot))).to.equal(Finished)
}) })
@ -1098,7 +1087,6 @@ describe("Marketplace", function () {
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
expect(await marketplace.slotState(slotId(slot))).to.equal(Cancelled) expect(await marketplace.slotState(slotId(slot))).to.equal(Cancelled)
}) })
@ -1114,8 +1102,7 @@ describe("Marketplace", function () {
while ((await marketplace.slotState(slotId(slot))) === Filled) { while ((await marketplace.slotState(slotId(slot))) === Filled) {
await waitUntilProofIsRequired(slotId(slot)) await waitUntilProofIsRequired(slotId(slot))
const missedPeriod = periodOf(await currentTime()) const missedPeriod = periodOf(await currentTime())
await advanceTimeForNextBlock(period) await advanceTime(period + 1)
await mine()
await marketplace.markProofAsMissing(slotId(slot), missedPeriod) await marketplace.markProofAsMissing(slotId(slot), missedPeriod)
} }
expect(await marketplace.slotState(slotId(slot))).to.equal(Repair) expect(await marketplace.slotState(slotId(slot))).to.equal(Repair)
@ -1124,7 +1111,6 @@ describe("Marketplace", function () {
it("changes to 'Failed' when request fails", async function () { it("changes to 'Failed' when request fails", async function () {
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilSlotFailed(marketplace, request, slot) await waitUntilSlotFailed(marketplace, request, slot)
await mine()
expect(await marketplace.slotState(slotId(slot))).to.equal(Failed) expect(await marketplace.slotState(slotId(slot))).to.equal(Failed)
}) })
@ -1152,20 +1138,19 @@ describe("Marketplace", function () {
async function waitUntilProofWillBeRequired(id) { async function waitUntilProofWillBeRequired(id) {
while (!(await marketplace.willProofBeRequired(id))) { while (!(await marketplace.willProofBeRequired(id))) {
await mine() await advanceTime(period)
} }
} }
async function waitUntilProofIsRequired(id) { async function waitUntilProofIsRequired(id) {
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime()))) await advanceTimeTo(periodEnd(periodOf(await currentTime())))
while ( while (
!( !(
(await marketplace.isProofRequired(id)) && (await marketplace.isProofRequired(id)) &&
(await marketplace.getPointer(id)) < 250 (await marketplace.getPointer(id)) < 250
) )
) { ) {
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
} }
@ -1183,7 +1168,6 @@ describe("Marketplace", function () {
await waitUntilProofWillBeRequired(id) await waitUntilProofWillBeRequired(id)
await expect(await marketplace.willProofBeRequired(id)).to.be.true await expect(await marketplace.willProofBeRequired(id)).to.be.true
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
await expect(await marketplace.willProofBeRequired(id)).to.be.false await expect(await marketplace.willProofBeRequired(id)).to.be.false
}) })
@ -1194,7 +1178,6 @@ describe("Marketplace", function () {
await waitUntilProofIsRequired(id) await waitUntilProofIsRequired(id)
await expect(await marketplace.isProofRequired(id)).to.be.true await expect(await marketplace.isProofRequired(id)).to.be.true
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
await expect(await marketplace.isProofRequired(id)).to.be.false await expect(await marketplace.isProofRequired(id)).to.be.false
}) })
@ -1203,11 +1186,9 @@ describe("Marketplace", function () {
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilProofIsRequired(id) await waitUntilProofIsRequired(id)
await mine()
const challenge1 = await marketplace.getChallenge(id) const challenge1 = await marketplace.getChallenge(id)
expect(BigNumber.from(challenge1).gt(0)) expect(BigNumber.from(challenge1).gt(0))
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
const challenge2 = await marketplace.getChallenge(id) const challenge2 = await marketplace.getChallenge(id)
expect(BigNumber.from(challenge2).isZero()) expect(BigNumber.from(challenge2).isZero())
}) })
@ -1217,11 +1198,9 @@ describe("Marketplace", function () {
await marketplace.reserveSlot(slot.request, slot.index) await marketplace.reserveSlot(slot.request, slot.index)
await marketplace.fillSlot(slot.request, slot.index, proof) await marketplace.fillSlot(slot.request, slot.index, proof)
await waitUntilProofIsRequired(id) await waitUntilProofIsRequired(id)
await mine()
const challenge1 = await marketplace.getChallenge(id) const challenge1 = await marketplace.getChallenge(id)
expect(BigNumber.from(challenge1).gt(0)) expect(BigNumber.from(challenge1).gt(0))
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
const challenge2 = await marketplace.getChallenge(id) const challenge2 = await marketplace.getChallenge(id)
expect(BigNumber.from(challenge2).isZero()) expect(BigNumber.from(challenge2).isZero())
}) })
@ -1242,16 +1221,14 @@ describe("Marketplace", function () {
}) })
async function waitUntilProofIsRequired(id) { async function waitUntilProofIsRequired(id) {
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime()))) await advanceTimeTo(periodEnd(periodOf(await currentTime())))
await mine()
while ( while (
!( !(
(await marketplace.isProofRequired(id)) && (await marketplace.isProofRequired(id)) &&
(await marketplace.getPointer(id)) < 250 (await marketplace.getPointer(id)) < 250
) )
) { ) {
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
} }
@ -1274,7 +1251,7 @@ describe("Marketplace", function () {
for (let i = 0; i < slashCriterion; i++) { for (let i = 0; i < slashCriterion; i++) {
await waitUntilProofIsRequired(id) await waitUntilProofIsRequired(id)
let missedPeriod = periodOf(await currentTime()) let missedPeriod = periodOf(await currentTime())
await advanceTimeForNextBlock(period + 1) await advanceTime(period + 1)
await marketplace.markProofAsMissing(id, missedPeriod) await marketplace.markProofAsMissing(id, missedPeriod)
} }
const expectedBalance = const expectedBalance =
@ -1302,7 +1279,7 @@ describe("Marketplace", function () {
) )
await waitUntilProofIsRequired(slotId(slot)) await waitUntilProofIsRequired(slotId(slot))
const missedPeriod = periodOf(await currentTime()) const missedPeriod = periodOf(await currentTime())
await advanceTimeForNextBlock(period + 1) await advanceTime(period + 1)
await marketplace.markProofAsMissing(slotId(slot), missedPeriod) await marketplace.markProofAsMissing(slotId(slot), missedPeriod)
} }
expect(await marketplace.slotState(slotId(slot))).to.equal( expect(await marketplace.slotState(slotId(slot))).to.equal(
@ -1328,7 +1305,7 @@ describe("Marketplace", function () {
) )
await waitUntilProofIsRequired(slotId(slot)) await waitUntilProofIsRequired(slotId(slot))
const missedPeriod = periodOf(await currentTime()) const missedPeriod = periodOf(await currentTime())
await advanceTimeForNextBlock(period + 1) await advanceTime(period + 1)
expect(await marketplace.missingProofs(slotId(slot))).to.equal( expect(await marketplace.missingProofs(slotId(slot))).to.equal(
missedProofs missedProofs
) )
@ -1361,7 +1338,6 @@ describe("Marketplace", function () {
it("keeps request in list when cancelled", async function () { it("keeps request in list when cancelled", async function () {
await marketplace.requestStorage(request) await marketplace.requestStorage(request)
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
expect(await marketplace.myRequests()).to.deep.equal([requestId(request)]) expect(await marketplace.myRequests()).to.deep.equal([requestId(request)])
}) })
@ -1380,7 +1356,6 @@ describe("Marketplace", function () {
switchAccount(host) switchAccount(host)
await waitUntilStarted(marketplace, request, proof, token) await waitUntilStarted(marketplace, request, proof, token)
await waitUntilFailed(marketplace, request) await waitUntilFailed(marketplace, request)
await mine()
switchAccount(client) switchAccount(client)
expect(await marketplace.myRequests()).to.deep.equal([requestId(request)]) expect(await marketplace.myRequests()).to.deep.equal([requestId(request)])
}) })
@ -1439,7 +1414,6 @@ describe("Marketplace", function () {
await marketplace.reserveSlot(slot.request, slot1.index) await marketplace.reserveSlot(slot.request, slot1.index)
await marketplace.fillSlot(slot.request, slot1.index, proof) await marketplace.fillSlot(slot.request, slot1.index, proof)
await waitUntilCancelled(request) await waitUntilCancelled(request)
await mine()
expect(await marketplace.mySlots()).to.have.members([ expect(await marketplace.mySlots()).to.have.members([
slotId(slot), slotId(slot),
slotId(slot1), slotId(slot1),

View File

@ -7,8 +7,8 @@ const {
mine, mine,
ensureMinimumBlockHeight, ensureMinimumBlockHeight,
currentTime, currentTime,
advanceTimeForNextBlock, advanceTime,
advanceTimeToForNextBlock, advanceTimeTo,
} = require("./evm") } = require("./evm")
const { periodic } = require("./time") const { periodic } = require("./time")
const { loadProof, loadPublicInput } = require("../verifier/verifier") const { loadProof, loadPublicInput } = require("../verifier/verifier")
@ -52,15 +52,13 @@ describe("Proofs", function () {
const samples = 256 // 256 samples avoids bias due to pointer downtime const samples = 256 // 256 samples avoids bias due to pointer downtime
await proofs.startRequiringProofs(slotId, probability) await proofs.startRequiringProofs(slotId, probability)
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
let amount = 0 let amount = 0
for (let i = 0; i < samples; i++) { for (let i = 0; i < samples; i++) {
if (await proofs.isProofRequired(slotId)) { if (await proofs.isProofRequired(slotId)) {
amount += 1 amount += 1
} }
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
const p = 1 / probability // expected probability const p = 1 / probability // expected probability
@ -72,8 +70,7 @@ describe("Proofs", function () {
it("supports probability 1 (proofs are always required)", async function () { it("supports probability 1 (proofs are always required)", async function () {
await proofs.startRequiringProofs(slotId, 1) await proofs.startRequiringProofs(slotId, 1)
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
while ((await proofs.getPointer(slotId)) < downtime) { while ((await proofs.getPointer(slotId)) < downtime) {
await mine() await mine()
} }
@ -86,8 +83,7 @@ describe("Proofs", function () {
await proofs.startRequiringProofs(slotId, probability) await proofs.startRequiringProofs(slotId, probability)
while (Math.floor((await currentTime()) / period) == startPeriod) { while (Math.floor((await currentTime()) / period) == startPeriod) {
expect(await proofs.isProofRequired(slotId)).to.be.false expect(await proofs.isProofRequired(slotId)).to.be.false
await advanceTimeForNextBlock(Math.floor(period / 10)) await advanceTime(Math.floor(period / 10))
await mine()
} }
}) })
@ -104,14 +100,11 @@ describe("Proofs", function () {
req1 = await proofs.isProofRequired(id1) req1 = await proofs.isProofRequired(id1)
req2 = await proofs.isProofRequired(id2) req2 = await proofs.isProofRequired(id2)
req3 = await proofs.isProofRequired(id3) req3 = await proofs.isProofRequired(id3)
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
}) })
it("moves pointer one block at a time", async function () { it("moves pointer one block at a time", async function () {
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime())))
await mine()
for (let i = 0; i < 256; i++) { for (let i = 0; i < 256; i++) {
let previous = await proofs.getPointer(slotId) let previous = await proofs.getPointer(slotId)
await mine() await mine()
@ -124,14 +117,13 @@ describe("Proofs", function () {
describe("when proof requirement is upcoming", function () { describe("when proof requirement is upcoming", function () {
async function waitUntilProofWillBeRequired() { async function waitUntilProofWillBeRequired() {
while (!(await proofs.willProofBeRequired(slotId))) { while (!(await proofs.willProofBeRequired(slotId))) {
await mine() await advanceTime(period)
} }
} }
beforeEach(async function () { beforeEach(async function () {
await proofs.setSlotState(slotId, SlotState.Filled) await proofs.setSlotState(slotId, SlotState.Filled)
await proofs.startRequiringProofs(slotId, probability) await proofs.startRequiringProofs(slotId, probability)
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime())))
await waitUntilProofWillBeRequired() await waitUntilProofWillBeRequired()
}) })
@ -169,23 +161,20 @@ describe("Proofs", function () {
}) })
async function waitUntilProofIsRequired(slotId) { async function waitUntilProofIsRequired(slotId) {
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime())))
await mine()
while ( while (
!( !(
(await proofs.isProofRequired(slotId)) && (await proofs.isProofRequired(slotId)) &&
(await proofs.getPointer(slotId)) < 250 (await proofs.getPointer(slotId)) < 250
) )
) { ) {
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
} }
it("provides different challenges per period", async function () { it("provides different challenges per period", async function () {
await waitUntilProofIsRequired(slotId) await waitUntilProofIsRequired(slotId)
const challenge1 = await proofs.getChallenge(slotId) const challenge1 = await proofs.getChallenge(slotId)
await advanceTime(period)
await waitUntilProofIsRequired(slotId) await waitUntilProofIsRequired(slotId)
const challenge2 = await proofs.getChallenge(slotId) const challenge2 = await proofs.getChallenge(slotId)
expect(challenge2).not.to.equal(challenge1) expect(challenge2).not.to.equal(challenge1)
@ -225,7 +214,6 @@ describe("Proofs", function () {
}) })
it("fails proof submission when already submitted", async function () { it("fails proof submission when already submitted", async function () {
await advanceTimeToForNextBlock(periodEnd(periodOf(await currentTime())))
await proofs.proofReceived(slotId, proof, pubSignals) await proofs.proofReceived(slotId, proof, pubSignals)
await expect( await expect(
proofs.proofReceived(slotId, proof, pubSignals) proofs.proofReceived(slotId, proof, pubSignals)
@ -236,8 +224,7 @@ describe("Proofs", function () {
expect(await proofs.missingProofs(slotId)).to.equal(0) expect(await proofs.missingProofs(slotId)).to.equal(0)
await waitUntilProofIsRequired(slotId) await waitUntilProofIsRequired(slotId)
let missedPeriod = periodOf(await currentTime()) let missedPeriod = periodOf(await currentTime())
await advanceTimeToForNextBlock(periodEnd(missedPeriod)) await advanceTimeTo(periodEnd(missedPeriod) + 1)
await mine()
await proofs.markProofAsMissing(slotId, missedPeriod) await proofs.markProofAsMissing(slotId, missedPeriod)
expect(await proofs.missingProofs(slotId)).to.equal(1) expect(await proofs.missingProofs(slotId)).to.equal(1)
}) })
@ -253,7 +240,7 @@ describe("Proofs", function () {
it("does not mark a proof as missing after timeout", async function () { it("does not mark a proof as missing after timeout", async function () {
await waitUntilProofIsRequired(slotId) await waitUntilProofIsRequired(slotId)
let currentPeriod = periodOf(await currentTime()) let currentPeriod = periodOf(await currentTime())
await advanceTimeToForNextBlock(periodEnd(currentPeriod) + timeout) await advanceTimeTo(periodEnd(currentPeriod) + timeout + 1)
await expect( await expect(
proofs.markProofAsMissing(slotId, currentPeriod) proofs.markProofAsMissing(slotId, currentPeriod)
).to.be.revertedWith("Proofs_ValidationTimedOut") ).to.be.revertedWith("Proofs_ValidationTimedOut")
@ -263,8 +250,7 @@ describe("Proofs", function () {
await waitUntilProofIsRequired(slotId) await waitUntilProofIsRequired(slotId)
let receivedPeriod = periodOf(await currentTime()) let receivedPeriod = periodOf(await currentTime())
await proofs.proofReceived(slotId, proof, pubSignals) await proofs.proofReceived(slotId, proof, pubSignals)
await advanceTimeToForNextBlock(periodEnd(receivedPeriod)) await advanceTimeTo(periodEnd(receivedPeriod) + 1)
await mine()
await expect( await expect(
proofs.markProofAsMissing(slotId, receivedPeriod) proofs.markProofAsMissing(slotId, receivedPeriod)
).to.be.revertedWith("Proofs_ProofNotMissing") ).to.be.revertedWith("Proofs_ProofNotMissing")
@ -272,12 +258,10 @@ describe("Proofs", function () {
it("does not mark proof as missing when not required", async function () { it("does not mark proof as missing when not required", async function () {
while (await proofs.isProofRequired(slotId)) { while (await proofs.isProofRequired(slotId)) {
await advanceTimeForNextBlock(period) await advanceTime(period)
await mine()
} }
let currentPeriod = periodOf(await currentTime()) let currentPeriod = periodOf(await currentTime())
await advanceTimeToForNextBlock(periodEnd(currentPeriod)) await advanceTimeTo(periodEnd(currentPeriod) + 1)
await mine()
await expect( await expect(
proofs.markProofAsMissing(slotId, currentPeriod) proofs.markProofAsMissing(slotId, currentPeriod)
).to.be.revertedWith("Proofs_ProofNotRequired") ).to.be.revertedWith("Proofs_ProofNotRequired")
@ -286,8 +270,7 @@ describe("Proofs", function () {
it("does not mark proof as missing twice", async function () { it("does not mark proof as missing twice", async function () {
await waitUntilProofIsRequired(slotId) await waitUntilProofIsRequired(slotId)
let missedPeriod = periodOf(await currentTime()) let missedPeriod = periodOf(await currentTime())
await advanceTimeToForNextBlock(periodEnd(missedPeriod)) await advanceTimeTo(periodEnd(missedPeriod) + 1)
await mine()
await proofs.markProofAsMissing(slotId, missedPeriod) await proofs.markProofAsMissing(slotId, missedPeriod)
await expect( await expect(
proofs.markProofAsMissing(slotId, missedPeriod) proofs.markProofAsMissing(slotId, missedPeriod)

View File

@ -3,7 +3,7 @@ const { ethers } = require("hardhat")
const { randomBytes } = ethers.utils const { randomBytes } = ethers.utils
const { const {
currentTime, currentTime,
advanceTimeToForNextBlock, advanceTimeTo,
mine, mine,
setAutomine, setAutomine,
snapshot, snapshot,
@ -324,7 +324,7 @@ describe("Vault", function () {
it("does not allow withdrawal before lock expires", async function () { it("does not allow withdrawal before lock expires", async function () {
await vault.lock(context, expiry, expiry) await vault.lock(context, expiry, expiry)
await advanceTimeToForNextBlock(expiry - 1) await advanceTimeTo(expiry - 1)
const withdrawing = vault.withdraw(context, account.address) const withdrawing = vault.withdraw(context, account.address)
await expect(withdrawing).to.be.revertedWith("Locked") await expect(withdrawing).to.be.revertedWith("Locked")
}) })
@ -350,7 +350,7 @@ describe("Vault", function () {
it("allows withdrawal after lock expires", async function () { it("allows withdrawal after lock expires", async function () {
await vault.lock(context, expiry, expiry) await vault.lock(context, expiry, expiry)
await advanceTimeToForNextBlock(expiry) await advanceTimeTo(expiry)
const before = await token.balanceOf(account.address) const before = await token.balanceOf(account.address)
await vault.withdraw(context, account.address) await vault.withdraw(context, account.address)
const after = await token.balanceOf(account.address) const after = await token.balanceOf(account.address)
@ -379,7 +379,7 @@ describe("Vault", function () {
it("cannot extend an expired lock", async function () { it("cannot extend an expired lock", async function () {
await vault.lock(context, expiry, maximum) await vault.lock(context, expiry, maximum)
await advanceTimeToForNextBlock(expiry) await advanceTimeTo(expiry)
const extending = vault.extendLock(context, maximum) const extending = vault.extendLock(context, maximum)
await expect(extending).to.be.revertedWith("LockRequired") await expect(extending).to.be.revertedWith("LockRequired")
}) })
@ -392,7 +392,7 @@ describe("Vault", function () {
it("deletes lock when funds are withdrawn", async function () { it("deletes lock when funds are withdrawn", async function () {
await vault.lock(context, expiry, expiry) await vault.lock(context, expiry, expiry)
await advanceTimeToForNextBlock(expiry) await advanceTimeTo(expiry)
await vault.withdraw(context, account.address) await vault.withdraw(context, account.address)
expect((await vault.getLock(context))[0]).to.equal(0) expect((await vault.getLock(context))[0]).to.equal(0)
expect((await vault.getLock(context))[1]).to.equal(0) expect((await vault.getLock(context))[1]).to.equal(0)
@ -419,11 +419,6 @@ describe("Vault", function () {
return await vault.getBalance(context, recipient) return await vault.getBalance(context, recipient)
} }
async function advanceTimeTo(timestamp) {
await advanceTimeToForNextBlock(timestamp)
await mine()
}
it("requires that a lock is set", async function () { it("requires that a lock is set", async function () {
await expect(vault.flow(context, sender, receiver, 2)).to.be.revertedWith( await expect(vault.flow(context, sender, receiver, 2)).to.be.revertedWith(
"LockRequired" "LockRequired"
@ -512,7 +507,7 @@ describe("Vault", function () {
await vault.flow(context, sender, receiver2, 2) await vault.flow(context, sender, receiver2, 2)
await mine() await mine()
const start = await currentTime() const start = await currentTime()
advanceTimeToForNextBlock(start + 4) advanceTimeTo(start + 4)
await vault.flow(context, receiver2, receiver, 1) await vault.flow(context, receiver2, receiver, 1)
await mine() await mine()
expect(await getBalance(sender)).to.equal(deposit - 12) expect(await getBalance(sender)).to.equal(deposit - 12)

View File

@ -12,7 +12,7 @@ async function snapshot() {
async function revert() { async function revert() {
const { id, time, automine } = snapshots.pop() const { id, time, automine } = snapshots.pop()
await ethers.provider.send("evm_revert", [id]) await ethers.provider.send("evm_revert", [id])
await ethers.provider.send("evm_setNextBlockTimestamp", [time + 1]) await ethers.provider.send("evm_setNextBlockTimestamp", [time])
await ethers.provider.send("evm_setAutomine", [automine]) await ethers.provider.send("evm_setAutomine", [automine])
} }
@ -20,13 +20,6 @@ async function setAutomine(enabled) {
await ethers.provider.send("evm_setAutomine", [enabled]) await ethers.provider.send("evm_setAutomine", [enabled])
} }
/**
* Mines new block.
*
* This call increases the block's timestamp by 1!
*
* @returns {Promise<void>}
*/
async function mine() { async function mine() {
await ethers.provider.send("evm_mine") await ethers.provider.send("evm_mine")
} }
@ -42,30 +35,14 @@ async function currentTime() {
return block.timestamp return block.timestamp
} }
/** async function advanceTime(seconds) {
* Function that advances time by adding seconds to current timestamp for **next block**.
*
* If you need the timestamp to be already applied for current block then mine a new block with `mine()` after this call.
* This is mainly needed when doing assertions on top of view calls that does not create transactions and mine new block.
*
* @param timestamp
* @returns {Promise<void>}
*/
async function advanceTimeForNextBlock(seconds) {
await ethers.provider.send("evm_increaseTime", [seconds]) await ethers.provider.send("evm_increaseTime", [seconds])
await mine()
} }
/** async function advanceTimeTo(timestamp) {
* Function that sets specific timestamp for **next block**.
*
* If you need the timestamp to be already applied for current block then mine a new block with `mine()` after this call.
* This is mainly needed when doing assertions on top of view calls that does not create transactions and mine new block.
*
* @param timestamp
* @returns {Promise<void>}
*/
async function advanceTimeToForNextBlock(timestamp) {
await ethers.provider.send("evm_setNextBlockTimestamp", [timestamp]) await ethers.provider.send("evm_setNextBlockTimestamp", [timestamp])
await mine()
} }
module.exports = { module.exports = {
@ -75,6 +52,6 @@ module.exports = {
mine, mine,
ensureMinimumBlockHeight, ensureMinimumBlockHeight,
currentTime, currentTime,
advanceTimeForNextBlock, advanceTime,
advanceTimeToForNextBlock, advanceTimeTo,
} }

View File

@ -1,6 +1,6 @@
const { advanceTimeToForNextBlock, currentTime } = require("./evm") const { advanceTimeTo, currentTime, mine } = require("./evm")
const { slotId, requestId } = require("./ids") const { slotId, requestId } = require("./ids")
const { maxPrice, payoutForDuration } = require("./price") const { payoutForDuration } = require("./price")
/** /**
* @dev This will not advance the time right on the "expiry threshold" but will most probably "overshoot it" * @dev This will not advance the time right on the "expiry threshold" but will most probably "overshoot it"
@ -11,7 +11,7 @@ const { maxPrice, payoutForDuration } = require("./price")
*/ */
async function waitUntilCancelled(request) { async function waitUntilCancelled(request) {
// We do +1, because the expiry check in contract is done as `>` and not `>=`. // We do +1, because the expiry check in contract is done as `>` and not `>=`.
await advanceTimeToForNextBlock((await currentTime()) + request.expiry + 1) await advanceTimeTo((await currentTime()) + request.expiry + 1)
} }
async function waitUntilSlotsFilled(contract, request, proof, token, slots) { async function waitUntilSlotsFilled(contract, request, proof, token, slots) {
@ -46,7 +46,7 @@ async function waitUntilStarted(contract, request, proof, token) {
async function waitUntilFinished(contract, requestId) { async function waitUntilFinished(contract, requestId) {
const end = (await contract.requestEnd(requestId)).toNumber() const end = (await contract.requestEnd(requestId)).toNumber()
// We do +1, because the end check in contract is done as `>` and not `>=`. // We do +1, because the end check in contract is done as `>` and not `>=`.
await advanceTimeToForNextBlock(end + 1) await advanceTimeTo(end + 1)
} }
async function waitUntilFailed(contract, request) { async function waitUntilFailed(contract, request) {