Tổng Quan
Ví dụ này hướng dẫn cách kiểm thử các tính năng phụ thuộc vào thời gian bằng cách thao túng slot và dấu thời gian trong LiteSVM.
Bài Kiểm Thử Hoàn Chỉnh
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 timelet 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 slotssvm.warp_to_slot(clock.slot + 100);// Verify time changedlet 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!");}
Kiểm Thử Các Tính Năng Dựa Trên Slot
#[test]fn test_slot_based_unlock() {let mut svm = LiteSVM::new();// Get starting slotlet start_slot = svm.get_sysvar::<Clock>().slot;// Deploy program with slot-based locklet 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 slotsvm.warp_to_slot(start_slot + 1000);// Now it should succeedlet result = call_program(&mut svm, program_id);assert!(result.is_ok());}
Kiểm Thử Các Tính Năng Dựa Trên Dấu Thời Gian
#[test]fn test_timestamp_based_feature() {let mut svm = LiteSVM::new();// Get current timestamplet 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 slotsvm.warp_to_slot(target_slot);// Verify timestamp increasedlet new_clock: Clock = svm.get_sysvar();assert!(new_clock.unix_timestamp >= current_time + 3600);}
Các Điểm Quan Trọng
- Clock Sysvar: Sử dụng
svm.get_sysvar::<Clock>()để lấy thời gian hiện tại - Dịch Chuyển Slot: Sử dụng
warp_to_slot()để nhảy về phía trước trong thời gian - Tính Toán Dấu Thời Gian: Mỗi slot tương đương khoảng ~0,4 giây trên Solana
- Kiểm Thử Mở Khóa: Kiểm thử các tính năng bị khóa theo thời gian bằng cách dịch chuyển qua thời điểm mở khóa
- Không Thể Quay Lại: Bạn chỉ có thể dịch chuyển về phía trước, không thể quay ngược thời gian
Các Trường Hợp Sử Dụng Phổ Biến
- Lịch trình trao quyền
- Rút tiền có khóa thời gian
- Thời gian chờ stake/unstake
- Thời điểm kết thúc đấu giá
- Thời hạn thuê
Is this page helpful?