@typesol/cli 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.md +9 -5
  3. package/dist/ai.d.ts +10 -0
  4. package/dist/ai.js +43 -0
  5. package/dist/cli.js +15 -1
  6. package/dist/compiler/analyze.js +44 -3
  7. package/dist/compiler/diagnostics.d.ts +2 -0
  8. package/dist/compiler/emit/base.d.ts +40 -7
  9. package/dist/compiler/emit/base.js +33 -0
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +102 -2
  13. package/dist/compiler/emit/calls.js +671 -50
  14. package/dist/compiler/emit/cpi-core.d.ts +9 -3
  15. package/dist/compiler/emit/cpi-core.js +12 -7
  16. package/dist/compiler/emit/cpi.js +8 -14
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +51 -2
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +7 -2
  24. package/dist/compiler/emit/shared.d.ts +35 -1
  25. package/dist/compiler/emit/shared.js +9 -1
  26. package/dist/compiler/emit/statements.d.ts +31 -0
  27. package/dist/compiler/emit/statements.js +272 -14
  28. package/dist/compiler/emit/storage.d.ts +27 -1
  29. package/dist/compiler/emit/storage.js +124 -11
  30. package/dist/compiler/emit/token.d.ts +11 -8
  31. package/dist/compiler/emit/token.js +233 -104
  32. package/dist/compiler/hints.js +6 -0
  33. package/dist/compiler/model.d.ts +20 -1
  34. package/dist/compiler/model.js +5 -0
  35. package/dist/testing-stake.d.ts +216 -0
  36. package/dist/testing-stake.js +526 -0
  37. package/dist/testing.d.ts +1 -0
  38. package/dist/testing.js +1 -0
  39. package/dist/tools/mcp.d.ts +11 -0
  40. package/dist/tools/mcp.js +208 -0
  41. package/dist/workspace.js +8 -0
  42. package/docs/ai.md +52 -0
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +16 -14
  45. package/docs/case-study-raydium-cp-swap.md +77 -41
  46. package/docs/case-study-spl-stake-pool.md +122 -0
  47. package/docs/errors.md +1 -1
  48. package/docs/language.md +107 -14
  49. package/docs/security-model.md +4 -0
  50. package/docs/stability.md +69 -0
  51. package/docs/test-your-program.md +47 -0
  52. package/docs/testing.md +19 -0
  53. package/lib/typesol.d.ts +241 -40
  54. package/llms-full.txt +1352 -0
  55. package/llms.txt +30 -0
  56. package/package.json +4 -2
  57. package/runtime/typesol_rt.h +69 -0
@@ -0,0 +1,526 @@
1
+ /**
2
+ * Epochs and staking for `typesol/testing` (re-exported from there): move LiteSVM's Clock to an epoch, keep a
3
+ * StakeHistory sysvar that rate-limits warmup and cooldown as a cluster does, and build vote and stake accounts.
4
+ *
5
+ * LiteSVM alone does neither: `warpToSlot` leaves Clock.epoch where it was, and its StakeHistory stays empty, so the
6
+ * Stake program finds no history and takes every delegation as fully active one epoch after it was made.
7
+ */
8
+ import { AccountRole, appendTransactionMessageInstructions, createTransactionMessage, generateKeyPairSigner, getAddressDecoder, getAddressEncoder, pipe, setTransactionMessageFeePayerSigner, signTransactionMessageWithSigners, } from "@solana/kit";
9
+ import { FailedTransactionMetadata, StakeHistory, StakeHistoryEntry } from "litesvm";
10
+ export const STAKE_PROGRAM_ADDRESS = "Stake11111111111111111111111111111111111111";
11
+ export const VOTE_PROGRAM_ADDRESS = "Vote111111111111111111111111111111111111111";
12
+ const SYSTEM_PROGRAM = "11111111111111111111111111111111";
13
+ const CLOCK_SYSVAR = "SysvarC1ock11111111111111111111111111111111";
14
+ const RENT_SYSVAR = "SysvarRent111111111111111111111111111111111";
15
+ const STAKE_HISTORY_SYSVAR = "SysvarStakeHistory1111111111111111111111111";
16
+ const STAKE_CONFIG = "StakeConfig11111111111111111111111111111111";
17
+ const U64_MAX = (1n << 64n) - 1n;
18
+ const U128_MAX = (1n << 128n) - 1n;
19
+ /** Size of a stake account (StakeStateV2). */
20
+ export const STAKE_ACCOUNT_SIZE = 200n;
21
+ /** Size of a vote account. */
22
+ export const VOTE_ACCOUNT_SIZE = 3762n;
23
+ /** StakeHistory keeps this many epochs, newest first. */
24
+ export const STAKE_HISTORY_MAX_ENTRIES = 512;
25
+ const MINIMUM_SLOTS_PER_EPOCH = 32n;
26
+ const log2Ceil = (n) => {
27
+ // trailing_zeros(next_power_of_two(n)) for n >= 1
28
+ let k = 0n;
29
+ while (1n << k < n)
30
+ k++;
31
+ return k;
32
+ };
33
+ const satSub = (a, b) => (a > b ? a - b : 0n);
34
+ /** The epoch of `slot` and the slot's index in it (EpochSchedule::get_epoch_and_slot_index). */
35
+ export function epochAndSlotIndex(schedule, slot) {
36
+ if (slot < schedule.firstNormalSlot) {
37
+ const epoch = satSub(satSub(log2Ceil(slot + MINIMUM_SLOTS_PER_EPOCH + 1n), 5n), 1n);
38
+ const epochLen = 1n << (epoch + 5n);
39
+ return { epoch, slotIndex: satSub(slot, satSub(epochLen, MINIMUM_SLOTS_PER_EPOCH)) };
40
+ }
41
+ const normal = slot - schedule.firstNormalSlot;
42
+ const per = schedule.slotsPerEpoch;
43
+ return { epoch: schedule.firstNormalEpoch + (per === 0n ? 0n : normal / per), slotIndex: per === 0n ? 0n : normal % per };
44
+ }
45
+ /** The first slot of `epoch` (EpochSchedule::get_first_slot_in_epoch). */
46
+ export function firstSlotInEpoch(schedule, epoch) {
47
+ if (epoch <= schedule.firstNormalEpoch)
48
+ return ((1n << epoch) - 1n) * MINIMUM_SLOTS_PER_EPOCH;
49
+ return (epoch - schedule.firstNormalEpoch) * schedule.slotsPerEpoch + schedule.firstNormalSlot;
50
+ }
51
+ /** The epoch whose leader schedule is known at `slot` (EpochSchedule::get_leader_schedule_epoch). */
52
+ export function leaderScheduleEpoch(schedule, slot) {
53
+ if (slot < schedule.firstNormalSlot)
54
+ return epochAndSlotIndex(schedule, slot).epoch + 1n;
55
+ const since = slot - schedule.firstNormalSlot + schedule.leaderScheduleSlotOffset;
56
+ return schedule.firstNormalEpoch + (schedule.slotsPerEpoch === 0n ? 0n : since / schedule.slotsPerEpoch);
57
+ }
58
+ /** The Clock at the first slot of `epoch`, from `svm`'s Clock and EpochSchedule. */
59
+ function clockAtEpoch(svm, epoch, opts = {}) {
60
+ const clock = svm.getClock();
61
+ if (epoch < clock.epoch)
62
+ throw new Error(`warpToEpoch: epoch ${epoch} is before the current epoch ${clock.epoch}`);
63
+ if (epoch === clock.epoch)
64
+ return null;
65
+ const schedule = svm.getEpochSchedule();
66
+ const slot = firstSlotInEpoch(schedule, epoch);
67
+ // The time that passes: from the current slot, or from the start of the Clock's epoch when the slot is not in it
68
+ // (a new LiteSVM's Clock has epoch 0 at slot 454464000).
69
+ const from = epochAndSlotIndex(schedule, clock.slot).epoch === clock.epoch ? clock.slot : firstSlotInEpoch(schedule, clock.epoch);
70
+ const msPerSlot = BigInt(Math.round((opts.secondsPerSlot ?? 0.4) * 1000));
71
+ const unixTimestamp = clock.unixTimestamp + ((slot - from) * msPerSlot) / 1000n;
72
+ return { slot, epoch, leaderScheduleEpoch: leaderScheduleEpoch(schedule, slot), epochStartTimestamp: unixTimestamp, unixTimestamp };
73
+ }
74
+ function applyClock(svm, c) {
75
+ const clock = svm.getClock();
76
+ clock.slot = c.slot;
77
+ clock.epoch = c.epoch;
78
+ clock.leaderScheduleEpoch = c.leaderScheduleEpoch;
79
+ clock.epochStartTimestamp = c.epochStartTimestamp;
80
+ clock.unixTimestamp = c.unixTimestamp;
81
+ svm.setClock(clock);
82
+ svm.expireBlockhash();
83
+ }
84
+ /**
85
+ * Move the cluster to the first slot of `epoch`: the Clock's slot, epoch, leader schedule epoch and timestamps
86
+ * (unixTimestamp advances by `secondsPerSlot` per slot and the epoch starts then), by the VM's EpochSchedule, warmup
87
+ * epochs included. The blockhash expires, so a transaction sent again is a new one. The StakeHistory is left as it is:
88
+ * use a `StakeCluster` to have it filled in.
89
+ */
90
+ export function warpToEpoch(svm, epoch, opts) {
91
+ const c = clockAtEpoch(svm, epoch, opts);
92
+ if (c)
93
+ applyClock(svm, c);
94
+ }
95
+ /** `warpToEpoch` to the next epoch; returns it. */
96
+ export function nextEpoch(svm, opts) {
97
+ const epoch = svm.getClock().epoch + 1n;
98
+ warpToEpoch(svm, epoch, opts);
99
+ return epoch;
100
+ }
101
+ /** A StakeHistory entry. */
102
+ export function stakeHistoryEntry(effective = 0n, activating = 0n, deactivating = 0n) {
103
+ return { effective, activating, deactivating };
104
+ }
105
+ /** Sum of entries, saturating at u64::MAX per field (StakeHistoryEntry's `+`). */
106
+ export function addStakeHistoryEntries(...entries) {
107
+ const sat = (x) => (x > U64_MAX ? U64_MAX : x);
108
+ return entries.reduce((s, e) => ({ effective: sat(s.effective + e.effective), activating: sat(s.activating + e.activating), deactivating: sat(s.deactivating + e.deactivating) }), stakeHistoryEntry());
109
+ }
110
+ const ORIGINAL_RATE_BPS = 2500n;
111
+ const TOWER_RATE_BPS = 900n;
112
+ /** warmup_cooldown_allowance.rs: `account`'s share of the cluster's allowed change for `epoch`, integer math. */
113
+ function allowanceInteger(epoch, account, clusterPortion, clusterEffective, rateEpoch) {
114
+ if (account === 0n || clusterPortion === 0n || clusterEffective === 0n)
115
+ return 0n;
116
+ const bps = rateEpoch !== null && epoch >= rateEpoch ? TOWER_RATE_BPS : ORIGINAL_RATE_BPS;
117
+ const sat = (x) => (x > U128_MAX ? U128_MAX : x);
118
+ const numerator = sat(sat(account * clusterEffective) * bps);
119
+ const denominator = sat(clusterPortion * 10000n);
120
+ const delta = numerator / denominator;
121
+ return delta < account ? delta : account;
122
+ }
123
+ /** `f64 as u64` in Rust: truncates, saturates, NaN is 0. */
124
+ const f64ToU64 = (x) => (Number.isNaN(x) || x <= 0 ? 0n : x >= 18446744073709551616 ? U64_MAX : BigInt(Math.trunc(x)));
125
+ /** The deprecated f64 path: `((account / cluster) * (effective * rate)) as u64`, before `.max(1)`. */
126
+ function allowanceFloat(epoch, account, clusterPortion, clusterEffective, rateEpoch) {
127
+ const rate = epoch < (rateEpoch ?? U64_MAX) ? 0.25 : 0.09;
128
+ const weight = Number(account) / Number(clusterPortion);
129
+ return f64ToU64(weight * (Number(clusterEffective) * rate));
130
+ }
131
+ /**
132
+ * The effective, activating and deactivating stake of a delegation at `targetEpoch`, given the cluster's stake history:
133
+ * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0), BigInt math with
134
+ * its u128 saturation. `newRateActivationEpoch` is the epoch from which warmup and cooldown are 9% per epoch rather
135
+ * than 25%: 0 (the default) as the Stake program has it on every cluster; `null` for 25% throughout (Rust's None).
136
+ */
137
+ export function stakeActivation(delegation, targetEpoch, history, newRateActivationEpoch = 0n, opts = {}) {
138
+ const float = opts.math === "float";
139
+ const allowance = float ? allowanceFloat : allowanceInteger;
140
+ const entry = (epoch) => history.get(epoch) ?? undefined;
141
+ const { stake: delegated, activationEpoch, deactivationEpoch } = delegation;
142
+ // stake_and_activating_v2: (effective, activating)
143
+ let effective;
144
+ let activating;
145
+ if (activationEpoch === U64_MAX)
146
+ [effective, activating] = [delegated, 0n]; // bootstrap: fully effective
147
+ else if (activationEpoch === deactivationEpoch)
148
+ [effective, activating] = [0n, 0n];
149
+ else if (targetEpoch === activationEpoch)
150
+ [effective, activating] = [0n, delegated];
151
+ else if (targetEpoch < activationEpoch)
152
+ [effective, activating] = [0n, 0n];
153
+ else {
154
+ let prev = entry(activationEpoch);
155
+ if (!prev)
156
+ [effective, activating] = [delegated, 0n]; // no history, or dropped out of it: fully effective
157
+ else {
158
+ let prevEpoch = activationEpoch;
159
+ let activated = 0n;
160
+ for (;;) {
161
+ const current = prevEpoch + 1n;
162
+ if (prev.activating === 0n)
163
+ break;
164
+ const remaining = delegated - activated;
165
+ const newly = allowance(current, remaining, prev.activating, prev.effective, newRateActivationEpoch);
166
+ activated += newly > 1n ? newly : 1n;
167
+ if (activated >= delegated) {
168
+ activated = delegated;
169
+ break;
170
+ }
171
+ if (current >= targetEpoch || current >= deactivationEpoch)
172
+ break;
173
+ const next = entry(current);
174
+ if (!next)
175
+ break;
176
+ prevEpoch = current;
177
+ prev = next;
178
+ }
179
+ [effective, activating] = [activated, delegated - activated];
180
+ }
181
+ }
182
+ if (targetEpoch < deactivationEpoch)
183
+ return { effective, activating, deactivating: 0n };
184
+ if (targetEpoch === deactivationEpoch)
185
+ return { effective, activating: 0n, deactivating: effective };
186
+ let prev = entry(deactivationEpoch);
187
+ if (!prev)
188
+ return stakeHistoryEntry(); // no history, or dropped out of it: fully deactivated
189
+ let prevEpoch = deactivationEpoch;
190
+ let remaining = effective;
191
+ for (;;) {
192
+ const current = prevEpoch + 1n;
193
+ if (prev.deactivating === 0n)
194
+ break;
195
+ const newly = allowance(current, remaining, prev.deactivating, prev.effective, newRateActivationEpoch);
196
+ const step = newly > 1n ? newly : 1n;
197
+ remaining = remaining > step ? remaining - step : 0n;
198
+ if (remaining === 0n)
199
+ break;
200
+ if (current >= targetEpoch)
201
+ break;
202
+ const next = entry(current);
203
+ if (!next)
204
+ break;
205
+ prevEpoch = current;
206
+ prev = next;
207
+ }
208
+ return { effective: remaining, activating: 0n, deactivating: remaining };
209
+ }
210
+ // ---------------------------------------------------------------------------------------------------------------
211
+ // The StakeHistory sysvar
212
+ /** The StakeHistory sysvar of `svm`, by epoch (read from the sysvar account: newest first, as stored). */
213
+ export function readStakeHistory(svm) {
214
+ const out = new Map();
215
+ const a = svm.getAccount(STAKE_HISTORY_SYSVAR);
216
+ if (!a.exists || a.data.length < 8)
217
+ return out;
218
+ const v = new DataView(a.data.buffer, a.data.byteOffset, a.data.byteLength);
219
+ const n = Number(v.getBigUint64(0, true));
220
+ for (let i = 0; i < n && 8 + 32 * (i + 1) <= a.data.length; i++) {
221
+ const o = 8 + 32 * i;
222
+ out.set(v.getBigUint64(o, true), stakeHistoryEntry(v.getBigUint64(o + 8, true), v.getBigUint64(o + 16, true), v.getBigUint64(o + 24, true)));
223
+ }
224
+ return out;
225
+ }
226
+ /** Replace the StakeHistory sysvar of each VM with these entries (the newest 512 are kept). */
227
+ export function writeStakeHistory(svms, history) {
228
+ for (const svm of Array.isArray(svms) ? svms : [svms]) {
229
+ const h = new StakeHistory();
230
+ for (const [epoch, e] of history)
231
+ h.add(epoch, new StakeHistoryEntry(e.effective, e.activating, e.deactivating));
232
+ svm.setStakeHistory(h);
233
+ }
234
+ }
235
+ /** Decode StakeStateV2 bytes. */
236
+ export function decodeStakeState(data) {
237
+ if (data.length < 4)
238
+ throw new Error(`stake account data is ${data.length} bytes`);
239
+ const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
240
+ const dec = getAddressDecoder();
241
+ const key = (o) => dec.decode(data.subarray(o, o + 32));
242
+ const tag = v.getUint32(0, true);
243
+ if (tag === 0)
244
+ return { kind: "Uninitialized" };
245
+ if (tag === 3)
246
+ return { kind: "RewardsPool" };
247
+ if (tag !== 1 && tag !== 2)
248
+ throw new Error(`not a stake account (tag ${tag})`);
249
+ const need = tag === 1 ? 124 : 197;
250
+ if (data.length < need)
251
+ throw new Error(`stake account data is ${data.length} bytes; ${need} needed`);
252
+ const meta = {
253
+ rentExemptReserve: v.getBigUint64(4, true),
254
+ authorized: { staker: key(12), withdrawer: key(44) },
255
+ lockup: { unixTimestamp: v.getBigInt64(76, true), epoch: v.getBigUint64(84, true), custodian: key(92) },
256
+ };
257
+ if (tag === 1)
258
+ return { kind: "Initialized", meta };
259
+ return {
260
+ kind: "Stake",
261
+ meta,
262
+ stake: {
263
+ delegation: {
264
+ voterPubkey: key(124),
265
+ stake: v.getBigUint64(156, true),
266
+ activationEpoch: v.getBigUint64(164, true),
267
+ deactivationEpoch: v.getBigUint64(172, true),
268
+ warmupCooldownRate: data.slice(180, 188),
269
+ },
270
+ creditsObserved: v.getBigUint64(188, true),
271
+ },
272
+ stakeFlags: data[196],
273
+ };
274
+ }
275
+ /** The stake account at `address` decoded, or null when it does not exist. */
276
+ export function readStakeAccount(svm, address) {
277
+ const a = svm.getAccount(address);
278
+ return a.exists ? decodeStakeState(a.data) : null;
279
+ }
280
+ const SOL = 1000000000n;
281
+ /**
282
+ * A cluster's stake bookkeeping over one or more LiteSVMs. Each epoch advance appends the StakeHistory entry of the
283
+ * epoch that ends (the sum of `stakeActivation` over the cluster's delegations at that epoch, plus `base`), as a
284
+ * cluster does at an epoch boundary, then moves the Clock to the next epoch's first slot. Every VM gets the same Clock,
285
+ * EpochSchedule and StakeHistory (taken from the first VM when the cluster is made), so differential tests see
286
+ * identical sysvars; the delegations are read from the first VM.
287
+ *
288
+ * The default `math` is `"float"`, the Stake program's in LiteSVM 1.6.1, so the history it writes and `activation`
289
+ * agree to the lamport with what that program does.
290
+ */
291
+ export class StakeCluster {
292
+ svms;
293
+ entries;
294
+ tracked = new Set();
295
+ opts;
296
+ constructor(svms, opts = {}) {
297
+ this.svms = Array.isArray(svms) ? [...svms] : [svms];
298
+ if (this.svms.length === 0)
299
+ throw new Error("StakeCluster needs at least one LiteSVM");
300
+ this.opts = { math: "float", ...opts };
301
+ const first = this.svms[0];
302
+ this.entries = readStakeHistory(first);
303
+ const clock = first.getClock();
304
+ // The Stake program finds an entry by its distance from the newest one, which must be the previous epoch's: an
305
+ // older one leaves a gap, one for this epoch or later is an epoch that has not ended.
306
+ const newest = this.newestEntry();
307
+ if (newest >= 0n && newest < clock.epoch - 1n)
308
+ throw new Error(`StakeCluster: the StakeHistory ends at epoch ${newest} but the Clock is at epoch ${clock.epoch}; entries up to ${clock.epoch - 1n} are needed`);
309
+ if (newest >= clock.epoch)
310
+ throw new Error(`StakeCluster: the StakeHistory has an entry for epoch ${newest} but the Clock is at epoch ${clock.epoch}; its newest entry must be epoch ${clock.epoch - 1n}'s (an epoch that ended)`);
311
+ const schedule = first.getEpochSchedule();
312
+ for (const svm of this.svms.slice(1)) {
313
+ svm.setEpochSchedule(schedule);
314
+ applyClock(svm, clock);
315
+ }
316
+ writeStakeHistory(this.svms, this.entries);
317
+ }
318
+ /** Count these stake accounts (with `allStakeAccounts: false`, only tracked ones count). */
319
+ track(...addresses) {
320
+ for (const a of addresses)
321
+ this.tracked.add(a);
322
+ return this;
323
+ }
324
+ /** The current epoch (the first VM's Clock). */
325
+ get epoch() {
326
+ return this.svms[0].getClock().epoch;
327
+ }
328
+ /** The StakeHistory written so far, by epoch. */
329
+ get history() {
330
+ return this.entries;
331
+ }
332
+ /** The delegations the cluster counts now: every Stake-state account (or the tracked ones) of the first VM. */
333
+ delegations() {
334
+ const svm = this.svms[0];
335
+ const addresses = new Set(this.tracked);
336
+ if (this.opts.allStakeAccounts !== false)
337
+ for (const a of svm.getProgramAccounts(STAKE_PROGRAM_ADDRESS))
338
+ addresses.add(a.address);
339
+ const out = [];
340
+ for (const a of addresses) {
341
+ const acc = svm.getAccount(a);
342
+ if (!acc.exists || acc.programAddress !== STAKE_PROGRAM_ADDRESS || acc.data.length < 200)
343
+ continue;
344
+ const state = decodeStakeState(acc.data);
345
+ if (state.kind === "Stake")
346
+ out.push(state.stake.delegation);
347
+ }
348
+ return out;
349
+ }
350
+ /** A delegation's (or a stake account's) activation at `epoch` (default: now), by this cluster's history. */
351
+ activation(of, epoch = this.epoch) {
352
+ let d;
353
+ if (typeof of === "string") {
354
+ const state = readStakeAccount(this.svms[0], of);
355
+ if (state?.kind !== "Stake")
356
+ return stakeHistoryEntry();
357
+ d = state.stake.delegation;
358
+ }
359
+ else
360
+ d = of;
361
+ return stakeActivation(d, epoch, this.entries, this.rateEpoch(), this.opts);
362
+ }
363
+ /** The entry the epoch `epoch` ends with, given the delegations now and the history so far. */
364
+ entryAt(epoch) {
365
+ const base = typeof this.opts.base === "function" ? this.opts.base(epoch) : (this.opts.base ?? stakeHistoryEntry(400000000n * SOL));
366
+ const rate = this.rateEpoch();
367
+ return addStakeHistoryEntries(base, ...this.delegations().map((d) => stakeActivation(d, epoch, this.entries, rate, this.opts)));
368
+ }
369
+ /** End the current epoch: append its entry and move every VM to the next epoch. Returns the new epoch. */
370
+ nextEpoch() {
371
+ const epoch = this.epoch + 1n;
372
+ this.warpToEpoch(epoch);
373
+ return epoch;
374
+ }
375
+ /**
376
+ * End epochs one by one (an entry for each, none skipped) up to `epoch`, then move every VM to its first slot. The
377
+ * history must still end at the epoch before the Clock's (or be empty): a Clock moved past it some other way (the
378
+ * plain `warpToEpoch`, `setClock`) would leave epochs without an entry, which the Stake program misreads, so that is
379
+ * refused. A new LiteSVM's Clock is at epoch 0 but at slot 454,464,000, so the first warp from one moves the slot back
380
+ * (to the first slot of `epoch` by the EpochSchedule); the timestamps still move forward.
381
+ */
382
+ warpToEpoch(epoch) {
383
+ const first = this.svms[0];
384
+ const now = first.getClock().epoch;
385
+ const newest = this.newestEntry();
386
+ if (newest >= 0n && newest !== now - 1n)
387
+ throw new Error(`StakeCluster.warpToEpoch: the StakeHistory ends at epoch ${newest} but the Clock is at epoch ${now} (moved outside the cluster?); its newest entry must be epoch ${now - 1n}'s`);
388
+ const clock = clockAtEpoch(first, epoch, this.opts);
389
+ if (!clock)
390
+ return;
391
+ for (let e = first.getClock().epoch; e < epoch; e++) {
392
+ this.entries.set(e, this.entryAt(e));
393
+ for (const old of [...this.entries.keys()])
394
+ if (old <= e - BigInt(STAKE_HISTORY_MAX_ENTRIES))
395
+ this.entries.delete(old);
396
+ }
397
+ writeStakeHistory(this.svms, this.entries);
398
+ for (const svm of this.svms)
399
+ applyClock(svm, clock);
400
+ }
401
+ /** The newest epoch with an entry, or -1 for an empty history. */
402
+ newestEntry() {
403
+ return [...this.entries.keys()].reduce((a, b) => (b > a ? b : a), -1n);
404
+ }
405
+ rateEpoch() {
406
+ return this.opts.newRateActivationEpoch === undefined ? 0n : this.opts.newRateActivationEpoch;
407
+ }
408
+ }
409
+ const enc = getAddressEncoder();
410
+ const keyBytes = (a) => enc.encode(a);
411
+ function instruction(programAddress, data, accounts) {
412
+ return {
413
+ programAddress,
414
+ accounts: accounts.map((a) => ({
415
+ address: a.address,
416
+ role: a.signer ? (a.writable ? AccountRole.WRITABLE_SIGNER : AccountRole.READONLY_SIGNER) : a.writable ? AccountRole.WRITABLE : AccountRole.READONLY,
417
+ ...(a.signer ? { signer: a.signer } : {}),
418
+ })),
419
+ data,
420
+ };
421
+ }
422
+ class Writer {
423
+ parts = [];
424
+ u8(n) {
425
+ this.parts.push(Uint8Array.of(n));
426
+ return this;
427
+ }
428
+ u32(n) {
429
+ const b = new Uint8Array(4);
430
+ new DataView(b.buffer).setUint32(0, n, true);
431
+ this.parts.push(b);
432
+ return this;
433
+ }
434
+ u64(n) {
435
+ const b = new Uint8Array(8);
436
+ new DataView(b.buffer).setBigUint64(0, BigInt.asUintN(64, n), true);
437
+ this.parts.push(b);
438
+ return this;
439
+ }
440
+ key(a) {
441
+ this.parts.push(keyBytes(a));
442
+ return this;
443
+ }
444
+ bytes() {
445
+ const out = new Uint8Array(this.parts.reduce((n, p) => n + p.length, 0));
446
+ let o = 0;
447
+ for (const p of this.parts) {
448
+ out.set(p, o);
449
+ o += p.length;
450
+ }
451
+ return out;
452
+ }
453
+ }
454
+ const createAccountIx = (payer, account, lamports, space, owner) => instruction(SYSTEM_PROGRAM, new Writer().u32(0).u64(lamports).u64(space).key(owner).bytes(), [
455
+ { address: payer.address, signer: payer, writable: true },
456
+ { address: account.address, signer: account, writable: true },
457
+ ]);
458
+ /** Send `ixs` in one transaction paid by `payer`; throws with the logs if it fails. The blockhash expires after. */
459
+ async function sendOrThrow(svm, payer, ixs, what) {
460
+ const tx = await pipe(createTransactionMessage({ version: 0 }), (t) => setTransactionMessageFeePayerSigner(payer, t), (t) => svm.setTransactionMessageLifetimeUsingLatestBlockhash(t), (t) => appendTransactionMessageInstructions(ixs, t), (t) => signTransactionMessageWithSigners(t));
461
+ const res = svm.sendTransaction(tx);
462
+ svm.expireBlockhash();
463
+ if (res instanceof FailedTransactionMetadata)
464
+ throw new Error(`${what} failed: ${String(res.err())}\n${res.meta().logs().join("\n")}`);
465
+ return res;
466
+ }
467
+ /**
468
+ * A vote account made by the Vote program (System CreateAccount of 3762 bytes, then InitializeAccount with
469
+ * VoteInit { node, authorized voter, authorized withdrawer, commission }). `node` signs (a new keypair by default);
470
+ * `voter` and `withdrawer` default to the node. Returns the vote account's address (`address` to choose it).
471
+ */
472
+ export async function createVoteAccount(svm, payer, opts = {}) {
473
+ const node = opts.node ?? (await generateKeyPairSigner());
474
+ const vote = opts.address ?? (await generateKeyPairSigner());
475
+ const data = new Writer()
476
+ .u32(0)
477
+ .key(node.address)
478
+ .key(opts.voter ?? node.address)
479
+ .key(opts.withdrawer ?? node.address)
480
+ .u8(opts.commission ?? 0)
481
+ .bytes();
482
+ await sendOrThrow(svm, payer, [
483
+ createAccountIx(payer, vote, svm.minimumBalanceForRentExemption(VOTE_ACCOUNT_SIZE), VOTE_ACCOUNT_SIZE, VOTE_PROGRAM_ADDRESS),
484
+ instruction(VOTE_PROGRAM_ADDRESS, data, [
485
+ { address: vote.address, writable: true },
486
+ { address: RENT_SYSVAR },
487
+ { address: CLOCK_SYSVAR },
488
+ { address: node.address, signer: node },
489
+ ]),
490
+ ], "createVoteAccount");
491
+ return vote.address;
492
+ }
493
+ /**
494
+ * A stake account made by the Stake program (System CreateAccount of 200 bytes holding `lamports` in all, rent
495
+ * reserve included, then Initialize with the authorities and lockup). Returns its address (`address` to choose it).
496
+ */
497
+ export async function createStakeAccount(svm, payer, opts) {
498
+ const stake = opts.address ?? (await generateKeyPairSigner());
499
+ const data = new Writer()
500
+ .u32(0)
501
+ .key(opts.staker)
502
+ .key(opts.withdrawer)
503
+ .u64(opts.lockup?.unixTimestamp ?? 0n)
504
+ .u64(opts.lockup?.epoch ?? 0n)
505
+ .key(opts.lockup?.custodian ?? SYSTEM_PROGRAM)
506
+ .bytes();
507
+ await sendOrThrow(svm, payer, [
508
+ createAccountIx(payer, stake, opts.lamports, STAKE_ACCOUNT_SIZE, STAKE_PROGRAM_ADDRESS),
509
+ instruction(STAKE_PROGRAM_ADDRESS, data, [{ address: stake.address, writable: true }, { address: RENT_SYSVAR }]),
510
+ ], "createStakeAccount");
511
+ return stake.address;
512
+ }
513
+ /** Delegate a stake account to a vote account (Stake DelegateStake, signed by the staker; `staker` defaults to the payer). */
514
+ export async function delegateStake(svm, payer, opts) {
515
+ const staker = opts.staker ?? payer;
516
+ return sendOrThrow(svm, payer, [
517
+ instruction(STAKE_PROGRAM_ADDRESS, new Writer().u32(2).bytes(), [
518
+ { address: opts.stake, writable: true },
519
+ { address: opts.vote },
520
+ { address: CLOCK_SYSVAR },
521
+ { address: STAKE_HISTORY_SYSVAR },
522
+ { address: STAKE_CONFIG },
523
+ { address: staker.address, signer: staker },
524
+ ]),
525
+ ], "delegateStake");
526
+ }
package/dist/testing.d.ts CHANGED
@@ -22,6 +22,7 @@ import { FailedTransactionMetadata, LiteSVM, TransactionMetadata } from "litesvm
22
22
  import { loadClonedAccounts } from "./tools/clone.js";
23
23
  import { type SvmConnection, svmConnection } from "./tools/svmrpc.js";
24
24
  export { type SvmConnection, svmConnection };
25
+ export * from "./testing-stake.js";
25
26
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
26
27
  export { loadClonedAccounts };
27
28
  declare const BorshCoder: typeof anchor.BorshCoder;
package/dist/testing.js CHANGED
@@ -27,6 +27,7 @@ import { loadClonedAccounts } from "./tools/clone.js";
27
27
  import { svmConnection } from "./tools/svmrpc.js";
28
28
  import { buildWorkspace, findWorkspace } from "./workspace.js";
29
29
  export { svmConnection };
30
+ export * from "./testing-stake.js";
30
31
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
31
32
  export { loadClonedAccounts };
32
33
  // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
@@ -0,0 +1,11 @@
1
+ type Message = {
2
+ jsonrpc: "2.0";
3
+ id?: number | string | null;
4
+ method?: string;
5
+ params?: Record<string, unknown>;
6
+ };
7
+ /** One request's response (undefined for a notification). */
8
+ export declare function handle(msg: Message): object | undefined;
9
+ /** Serve on stdin / stdout until stdin closes. Logs go to stderr: stdout carries only protocol messages. */
10
+ export declare function serve(): Promise<void>;
11
+ export {};