I have an ICO program created using Anchor, and I want to test with a future timestamp. How can I write unit tests with a future timestamp?
3 Answers
You can use Solana Bankrun time travel to do this: https://kevinheavey.github.io/solana-bankrun/tutorial/#time-travel
const timestamp = Math.floor(Date.now() / 1000);
// Turn forward the clock for 11 minutes
const currentClock = await client.getClock();
context.setClock(
new Clock(
currentClock.slot,
currentClock.epochStartTimestamp,
currentClock.epoch,
currentClock.leaderScheduleEpoch,
BigInt(timestamp) + BigInt(60 * 11)
)
);
Here is an example: https://github.com/solana-developers/solana-game-preset/blob/main/program/jesttests/energy-refill-time.test.ts
luzid.app supports similar features. Havent tried it yet though.
I like this summary at Ackee bootcamp https://github.com/Ackee-Blockchain/Solana-Auditors-Bootcamp/tree/master/Lesson-2#testing-using-typescript-1
- Wait for the amount of time you need to get over the threshold.
- It's good to set short thresholds in your program for testing
- Setup test validator to set shorter time for epoch length https://github.com/marinade-finance/marinade-ts-sdk/blob/v5.0.6/Anchor.toml#L28
For example in our SDK tests, we wait to get the stake account activated https://github.com/marinade-finance/marinade-ts-sdk/blob/v5.0.6/test/test-world.ts#L210
- Use solana bankrun https://github.com/kevinheavey/solana-bankrun/ for testing where you can fast forward (or backwards) the time with
warp_to_slot
orwarp_to_epoch
or https://github.com/kevinheavey/solana-bankrun/blob/main/tests/clock-example/clock.test.ts#L28
i am not sure to understand where is the problem here ? Just get the current timestamp and add X seconds to it ?