> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Kiểm thử dựa trên thời gian

> Kiểm thử logic phụ thuộc thời gian bằng cách điều khiển đồng hồ trong LiteSVM

Minh họa cách dùng `warpToSlot` để kiểm thử logic chương trình phụ thuộc vào thời gian.

## Điều khiển đồng hồ cơ bản

```typescript
import { createClient, generateKeyPairSigner } from "@solana/kit";
import { litesvm } from "@solana/kit-plugin-litesvm";
import { signer } from "@solana/kit-plugin-signer";

const mySigner = await generateKeyPairSigner();
const client = createClient().use(signer(mySigner)).use(litesvm());

// Check initial clock
const initialClock = client.svm.getClock();
console.log("Initial state:");
console.log("  Slot:", initialClock.slot);
console.log("  Epoch:", initialClock.epoch);
console.log("  Unix timestamp:", initialClock.unixTimestamp);

// Warp 1,000 slots forward
client.svm.warpToSlot(initialClock.slot + 1000n);

const afterWarp = client.svm.getClock();
console.log("\nAfter warping 1,000 slots:");
console.log("  Slot:", afterWarp.slot);
console.log("  Epoch:", afterWarp.epoch);

// Warp further
client.svm.warpToSlot(initialClock.slot + 100_000n);

const afterWarp2 = client.svm.getClock();
console.log("\nAfter warping 100,000 slots:");
console.log("  Slot:", afterWarp2.slot);
console.log("  Epoch:", afterWarp2.epoch);
```

## Kiểm thử logic khóa theo thời gian

Mẫu ví dụ để kiểm thử chức năng khóa theo thời gian:

```typescript
import {
  createClient,
  address,
  generateKeyPairSigner,
  lamports
} from "@solana/kit";
import { litesvm } from "@solana/kit-plugin-litesvm";
import { signer } from "@solana/kit-plugin-signer";

const mySigner = await generateKeyPairSigner();
const client = createClient().use(signer(mySigner)).use(litesvm());

client.svm.withSigverify(false).withBlockhashCheck(false);

// Fund payer
client.svm.airdrop(client.payer.address, lamports(10_000_000_000n));

// Set up a time-locked vault account
// Structure: [u8 discriminator, u64 unlock_slot, u64 amount]
// LiteSVM starts at a recent mainnet slot, so set the unlock relative to it
const unlockSlot = client.svm.getClock().slot + 10_000n;
const lockedAmount = 5_000_000_000n;

const vaultData = new Uint8Array(1 + 8 + 8);
const view = new DataView(vaultData.buffer);
vaultData[0] = 0x01; // discriminator
view.setBigUint64(1, unlockSlot, true); // unlock_slot
view.setBigUint64(9, lockedAmount, true); // amount

const programId = (await generateKeyPairSigner()).address;
const vaultAddress = (await generateKeyPairSigner()).address;
const minBalance = client.svm.minimumBalanceForRentExemption(
  BigInt(vaultData.length)
);

client.svm.setAccount({
  address: vaultAddress,
  data: vaultData,
  executable: false,
  lamports: lamports(minBalance + lockedAmount),
  programAddress: programId,
  space: BigInt(vaultData.length)
});

console.log("Vault created with unlock slot:", unlockSlot);
console.log("Locked amount:", Number(lockedAmount) / 1e9, "SOL");

// Test 1: Try to withdraw before unlock (should fail)
console.log("\n--- Test 1: Before unlock ---");
const currentClock = client.svm.getClock();
console.log("Current slot:", currentClock.slot);

// In a real test, you would:
// 1. Build a withdraw instruction
// 2. Send it and expect it to fail
console.log("Withdrawal attempt: EXPECTED TO FAIL (too early)");

// Test 2: Warp to after unlock slot
console.log("\n--- Test 2: After unlock ---");
client.svm.warpToSlot(unlockSlot + 100n);

const newClock = client.svm.getClock();
console.log("Current slot:", newClock.slot);

// In a real test:
// 1. Build a withdraw instruction
// 2. Send it and expect it to succeed
console.log("Withdrawal attempt: EXPECTED TO SUCCEED (after unlock)");

// Verify vault state
const updatedVault = client.svm.getAccount(vaultAddress);
if (updatedVault.exists) {
  console.log("\nVault balance:", updatedVault.lamports);
}
```

## Đọc lịch epoch

Bạn có thể đọc lịch epoch để hiểu mối quan hệ giữa slot/epoch trên
cluster:

```typescript
import { createClient, generateKeyPairSigner } from "@solana/kit";
import { litesvm } from "@solana/kit-plugin-litesvm";
import { signer } from "@solana/kit-plugin-signer";

const mySigner = await generateKeyPairSigner();
const client = createClient().use(signer(mySigner)).use(litesvm());

const epochSchedule = client.svm.getEpochSchedule();
console.log("Slots per epoch:", epochSchedule.slotsPerEpoch);
console.log("First normal epoch:", epochSchedule.firstNormalEpoch);
console.log("First normal slot:", epochSchedule.firstNormalSlot);
```

<Warning>
  `warpToSlot` đẩy trường `slot` của đồng hồ tiến lên nhưng **không** tự động
  cập nhật `epoch` hoặc `unixTimestamp`. Hãy dùng `setClock` để kiểm soát hoàn toàn các
  trường của đồng hồ.
</Warning>

## Điều khiển đồng hồ thủ công

Khi chương trình của bạn đọc `epoch` hoặc `unix_timestamp` từ sysvar Clock, hãy dùng
`setClock` để đặt trực tiếp các trường đó:

```typescript
import { createClient, generateKeyPairSigner } from "@solana/kit";
import { litesvm } from "@solana/kit-plugin-litesvm";
import { signer } from "@solana/kit-plugin-signer";

const mySigner = await generateKeyPairSigner();
const client = createClient().use(signer(mySigner)).use(litesvm());
client.svm.withSysvars();

// Get clock, mutate, write back
const clock = client.svm.getClock();
clock.slot = 50000n;
clock.epoch = 5n;
clock.unixTimestamp = 1700000000n;
client.svm.setClock(clock);

const after = client.svm.getClock();
console.log("Slot:", after.slot); // 50000n
console.log("Epoch:", after.epoch); // 5n
console.log("Timestamp:", after.unixTimestamp); // 1700000000n
```

Cách này phản chiếu mẫu `set_sysvar(&clock)` trong Rust. Dùng `warpToSlot` để tiến slot
đơn giản, dùng `setClock` khi bạn cần kiểm soát epoch hoặc timestamp.

## Các trường hợp sử dụng

Điều khiển thời gian hữu ích để kiểm thử:

| Kịch bản                | Cách tiếp cận                           |
| ----------------------- | ---------------------------------- |
| Token vesting           | Warp qua các mốc cliff/milestone của vesting |
| Kết thúc phiên đấu giá         | Warp qua slot kết thúc đấu giá         |
| Phần thưởng staking         | Dùng `setClock` để đặt epoch        |
| Rút tiền bị khóa theo thời gian | Warp qua slot mở khóa              |
| Giới hạn tốc độ           | Warp giữa các khoảng thời gian được phép     |
| Lệnh hết hạn         | Warp qua thời điểm hết hạn của lệnh         |

<Info>
  Hãy nhớ rằng `warpToSlot` chỉ thay đổi slot. Unix timestamp có thể không
  được cập nhật tương ứng, tùy thuộc vào cách triển khai SVM.
</Info>

## Điểm chính

1. **Sysvar đã sẵn sàng**: Clock và các sysvar khác đều khả dụng trên một client
   mới. `withSysvars()` sẽ đặt lại chúng về mặc định, vì vậy đừng gọi hàm này sau
   `setClock` hoặc `warpToSlot`
2. **Warp tiến lên**: Dùng `warpToSlot(slot)` để tiến slot
3. **Kiểm soát hoàn toàn**: Dùng `setClock` khi bạn cần đặt `epoch`,
   `unixTimestamp` hoặc các trường khác của đồng hồ
4. **Đọc Clock**: Dùng `getClock()` để đọc slot, epoch, timestamp hiện tại
5. **Mẫu kiểm thử**: Kiểm thử trước và sau các mốc thời gian
