基于时间的测试

概述

此示例展示了如何通过在LiteSVM中操控slot和时间戳来测试依赖时间的功能。

完整测试

tests/time_test.rs
use litesvm::LiteSVM;
use solana_sdk::clock::Clock;
#[test]
fn test_time_locked_feature() {
let mut svm = LiteSVM::new();
// Get current time
let clock: Clock = svm.get_sysvar();
println!("Starting slot: {}", clock.slot);
println!("Starting timestamp: {}", clock.unix_timestamp);
// Test something at current time
// ... your test logic ...
// Jump forward 100 slots
svm.warp_to_slot(clock.slot + 100);
// Verify time changed
let new_clock: Clock = svm.get_sysvar();
assert_eq!(new_clock.slot, clock.slot + 100);
// Test time-locked feature is now available
// ... your test logic ...
println!("Time travel successful!");
}

测试基于slot的功能

#[test]
fn test_slot_based_unlock() {
let mut svm = LiteSVM::new();
// Get starting slot
let start_slot = svm.get_sysvar::<Clock>().slot;
// Deploy program with slot-based lock
let program_id = deploy_locked_program(&mut svm);
// Try to call before unlock slot (should fail)
let result = call_program(&mut svm, program_id);
assert!(result.is_err());
// Warp to unlock slot
svm.warp_to_slot(start_slot + 1000);
// Now it should succeed
let result = call_program(&mut svm, program_id);
assert!(result.is_ok());
}

测试基于时间戳的功能

#[test]
fn test_timestamp_based_feature() {
let mut svm = LiteSVM::new();
// Get current timestamp
let clock: Clock = svm.get_sysvar();
let current_time = clock.unix_timestamp;
// Warp forward 1 hour (3600 seconds)
let target_slot = clock.slot + (3600.0 / 0.4) as u64; // ~0.4s per slot
svm.warp_to_slot(target_slot);
// Verify timestamp increased
let new_clock: Clock = svm.get_sysvar();
assert!(new_clock.unix_timestamp >= current_time + 3600);
}

关键要点

  1. 时钟系统变量:使用svm.get_sysvar::<Clock>()获取当前时间
  2. Slot跳转:使用warp_to_slot()在时间上向前跳转
  3. 时间戳计算:在Solana上,每个slot大约对应~0.4秒
  4. 测试解锁:通过跳转至解锁时间之后来测试时间锁定功能
  5. 不可回退:只能向前跳转,无法回退到过去的时间

常见使用场景

  • 归属计划
  • 时间锁定提款
  • 质押/解质押冷却期
  • 拍卖结束时间
  • 租赁期限

Is this page helpful?

Table of Contents

Edit Page
©️ 2026 Solana 基金会版权所有