@typesol/cli 0.41.0 → 0.43.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 (62) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -7
  3. package/dist/compiler/analyze.js +484 -13
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +65 -7
  9. package/dist/compiler/emit/base.js +91 -7
  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 +169 -2
  13. package/dist/compiler/emit/calls.js +1170 -81
  14. package/dist/compiler/emit/cpi-core.d.ts +28 -5
  15. package/dist/compiler/emit/cpi-core.js +238 -12
  16. package/dist/compiler/emit/cpi.js +16 -16
  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 +89 -9
  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 +37 -3
  24. package/dist/compiler/emit/rbtree.d.ts +7 -0
  25. package/dist/compiler/emit/rbtree.js +142 -0
  26. package/dist/compiler/emit/shared.d.ts +43 -1
  27. package/dist/compiler/emit/shared.js +18 -2
  28. package/dist/compiler/emit/statements.d.ts +58 -1
  29. package/dist/compiler/emit/statements.js +549 -22
  30. package/dist/compiler/emit/storage.d.ts +48 -1
  31. package/dist/compiler/emit/storage.js +220 -63
  32. package/dist/compiler/emit/token.d.ts +11 -8
  33. package/dist/compiler/emit/token.js +233 -104
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/hints.js +6 -0
  37. package/dist/compiler/idl.js +2 -1
  38. package/dist/compiler/model.d.ts +84 -4
  39. package/dist/compiler/model.js +19 -0
  40. package/dist/compiler/toolchain.d.ts +15 -0
  41. package/dist/compiler/toolchain.js +146 -11
  42. package/dist/testing-stake.d.ts +216 -0
  43. package/dist/testing-stake.js +526 -0
  44. package/dist/testing.d.ts +1 -0
  45. package/dist/testing.js +1 -0
  46. package/docs/architecture.md +9 -2
  47. package/docs/case-study-phoenix.md +226 -0
  48. package/docs/case-study-spl-stake-pool.md +122 -0
  49. package/docs/errors.md +1 -1
  50. package/docs/language.md +244 -20
  51. package/docs/migrate-from-anchor.md +1 -0
  52. package/docs/runtime.md +1 -1
  53. package/docs/security-model.md +4 -0
  54. package/docs/stability.md +33 -1
  55. package/docs/test-your-program.md +47 -0
  56. package/docs/testing.md +19 -0
  57. package/docs/troubleshooting.md +5 -2
  58. package/lib/typesol.d.ts +462 -44
  59. package/llms-full.txt +338 -26
  60. package/llms.txt +1 -1
  61. package/package.json +2 -2
  62. package/runtime/typesol_rt.h +476 -0
@@ -64,9 +64,13 @@ export type ValueType = ScalarType | {
64
64
  | {
65
65
  kind: "signerSeeds";
66
66
  }
67
- /** An extra account from remainingAccounts(): `SolAccountInfo *`. */
67
+ /**
68
+ * An extra account from remainingAccounts(): `SolAccountInfo *`. `program`: what `programAt<P>(acct)` /
69
+ * `sysvarAt<S>(acct)` checked it is (its typed methods then apply).
70
+ */
68
71
  | {
69
72
  kind: "account";
73
+ program?: ParamKind;
70
74
  }
71
75
  /** The remainingAccounts() list itself. */
72
76
  | {
@@ -76,11 +80,38 @@ export type ValueType = ScalarType | {
76
80
  | {
77
81
  kind: "txIx";
78
82
  }
79
- /** A struct loaded from a remaining account with loadAccount / loadAccountMut. */
83
+ /** The EpochRewards sysvar as epochRewards() read it: a `TsEpochRewards` copy. */
84
+ | {
85
+ kind: "epochRewards";
86
+ }
87
+ /**
88
+ * A struct loaded from a remaining account with loadAccount / loadAccountMut. `nullable`: a RedBlackTree's
89
+ * `get(k)` / `remove(k)` of a struct value, NULL when the key is absent (narrowed with `x !== null` before use).
90
+ */
80
91
  | {
81
92
  kind: "structRef";
82
93
  struct: string;
83
94
  writable: boolean;
95
+ nullable?: boolean;
96
+ }
97
+ /** `rawArrayAt<T>(acct, offset, capacity)`: `capacity` elements in place at a run-time offset (`T *` + count). */
98
+ | {
99
+ kind: "rawArray";
100
+ elem: FieldType;
101
+ writable: boolean;
102
+ }
103
+ /** `rbTreeAt<K, V>(acct, offset, capacity, compare?)`: lib-sokoban's RedBlackTree in place (a `TsRbt`). */
104
+ | {
105
+ kind: "rbTree";
106
+ inst: string;
107
+ writable: boolean;
108
+ }
109
+ /** A node of a RedBlackTree (min / max / nodeAt / for … of): a `TsRbtEntry`; `nullable` for min / max. */
110
+ | {
111
+ kind: "rbEntry";
112
+ inst: string;
113
+ writable: boolean;
114
+ nullable?: boolean;
84
115
  }
85
116
  /** A data-enum place (local value, argument, or alias into account data): `TS_DE_<name> *`. */
86
117
  | {
@@ -125,6 +156,9 @@ export type FieldType = ScalarType | {
125
156
  * `Vec<T>` (stored after the fixed-size fields, grows the account) or, with `cap`, `FixedVec<T, N>`: a u32 length and
126
157
  * room for N elements. With `heap`, a `Vec<T>` in a `@layout borsh` struct: Anchor's Vec, held on the heap while the
127
158
  * instruction runs (`TSH_*`: length, capacity, elements) and bounded only by the account when it is written back.
159
+ * With `big`, a `BigVec<T>` (the last field of a struct read with loadRaw): stored like a trailing Vec, its room set by
160
+ * the account's size, never resized. With `raw` (and `big`), a `rawArrayAt` view: a run-time count of elements in
161
+ * place, no stored length.
128
162
  */
129
163
  | {
130
164
  kind: "vec";
@@ -132,6 +166,8 @@ export type FieldType = ScalarType | {
132
166
  cap?: number;
133
167
  heap?: true;
134
168
  optional?: true;
169
+ big?: true;
170
+ raw?: true;
135
171
  };
136
172
  export interface StructField {
137
173
  name: string;
@@ -167,9 +203,17 @@ export interface StructDef {
167
203
  elem: FieldType;
168
204
  elemSize: number;
169
205
  }[];
206
+ /** A `BigVec<T>` last field (also `vec` and `vecs`, so every refusal of variable-size structs applies to it). */
207
+ bigVec?: {
208
+ name: string;
209
+ elem: FieldType;
210
+ elemSize: number;
211
+ };
170
212
  accountDiscriminator: number[];
171
213
  eventDiscriminator: number[];
172
214
  node: ts.InterfaceDeclaration;
215
+ /** Not exported (`interface Pair { … }`): its file's own, for helpers and locals, and left out of the IDL. */
216
+ local?: true;
173
217
  /**
174
218
  * How account data stores it: "fixed" (every field at a fixed offset, the default) or "borsh" (`@layout borsh`:
175
219
  * Anchor's bytes, where strings, Vecs and Options take only what they hold).
@@ -421,6 +465,13 @@ export interface HelperParam {
421
465
  /** `{ kind: "account" }` for account parameters (then `account` says which kind). */
422
466
  type: ValueType;
423
467
  account?: ParamKind;
468
+ /**
469
+ * `Inout<T>`: the caller's place itself, which the helper may change (a pointer, never a copy). `type` is then a
470
+ * writable structRef, an arrayArg, or (for a FixedVec) a vecArg standing in for the place; code reads `inout` first.
471
+ */
472
+ inout?: FieldType & {
473
+ kind: "struct" | "array" | "vec";
474
+ };
424
475
  node: ts.ParameterDeclaration;
425
476
  }
426
477
  /** A function written as `function f(…)`, `const f = (…) => …` or `const f = function (…) {…}`. */
@@ -455,14 +506,19 @@ export interface Helper {
455
506
  fnArgIndexes?: number[];
456
507
  /** The declaring file's `typesol` imports (local name -> export name). */
457
508
  imports: Map<string, string>;
509
+ /** `/** @noinline *\/`: a C function of its own that clang never inlines, so its locals get a stack frame of their own. */
510
+ noinline?: boolean;
458
511
  }
459
512
  /** A top-level compile-time constant. `type` is set when annotated (`const FEE: u16 = 30n`). */
460
513
  export interface ConstDef {
461
514
  name: string;
462
- /** `{ pubkey }` for `const ADMIN = pubkey("…")`: the decoded 32 bytes. */
515
+ /**
516
+ * `{ pubkey }` for `const ADMIN = pubkey("…")`: the decoded 32 bytes; `null` only for ERROR_LOG_PREFIX /
517
+ * PROGRAM_ERROR_LOG_PREFIX (failures that log nothing).
518
+ */
463
519
  value: bigint | boolean | string | {
464
520
  pubkey: number[];
465
- };
521
+ } | null;
466
522
  type?: ScalarType;
467
523
  }
468
524
  /** A data-carrying enum: `export type Action = { kind: "Deposit"; amount: u64 } | { kind: "Pause" }`. */
@@ -555,6 +611,30 @@ export interface ProgramModel {
555
611
  localVecs: Map<string, FieldType & {
556
612
  kind: "vec";
557
613
  }>;
614
+ /** Structs read or written with loadBorsh / storeBorsh, filled in while emitting: their ts_bdec_ / ts_benc_ codecs. */
615
+ borshNative: Set<string>;
616
+ /** RedBlackTree instances (key, value, comparator), filled in while emitting: their per-tree C functions. */
617
+ rbTrees: Map<string, RbTreeInst>;
618
+ /**
619
+ * The program makes views of native accounts (loadRaw, loadRawAt, rawArrayAt, rbTreeAt and their Mut forms): their
620
+ * owner checks share one cache (ts_owned), forgotten at every CPI and owner write. Set before any body is emitted.
621
+ */
622
+ ownerCache?: boolean;
623
+ }
624
+ /**
625
+ * One `rbTreeAt<K, V>(…, compare?)` instantiation: lib-sokoban 0.3's RedBlackTree<K, V, N> over K and V (N is the
626
+ * run-time capacity). `c` is the prefix of its C functions (`ts_rbt<n>_find` …); `compare` the helper ordering keys
627
+ * (`compare(searched, nodeKey)`: negative, 0 or positive), or none for the default order.
628
+ */
629
+ export interface RbTreeInst {
630
+ key: string;
631
+ c: string;
632
+ keyType: FieldType;
633
+ valueType: FieldType;
634
+ keySize: number;
635
+ valueSize: number;
636
+ stride: number;
637
+ compare?: Helper;
558
638
  }
559
639
  export declare function isWritable(k: ParamKind): boolean;
560
640
  export declare function typeName(t: ValueType | FieldType): string;
@@ -61,6 +61,10 @@ export function typeName(t) {
61
61
  case "vec":
62
62
  if (t.optional)
63
63
  return `Option<Vec<${typeName(t.elem)}>>`;
64
+ if (t.raw)
65
+ return `RawArray<${typeName(t.elem)}>`;
66
+ if (t.big)
67
+ return `BigVec<${typeName(t.elem)}>`;
64
68
  return t.cap === undefined ? `Vec<${typeName(t.elem)}>` : `FixedVec<${typeName(t.elem)}, ${t.cap}>`;
65
69
  case "vecArg":
66
70
  return t.optional ? `Option<Vec<${typeName(t.elem)}>>` : `Vec<${typeName(t.elem)}>`;
@@ -76,8 +80,16 @@ export function typeName(t) {
76
80
  return "RemainingAccounts";
77
81
  case "txIx":
78
82
  return "TransactionInstruction";
83
+ case "epochRewards":
84
+ return "EpochRewards";
79
85
  case "structRef":
80
86
  return t.struct;
87
+ case "rawArray":
88
+ return `RawArray<${typeName(t.elem)}>`;
89
+ case "rbTree":
90
+ return "RedBlackTree";
91
+ case "rbEntry":
92
+ return "RbEntry";
81
93
  }
82
94
  }
83
95
  export function sameType(a, b) {
@@ -104,6 +116,8 @@ export function sameType(a, b) {
104
116
  return (a.cap === b.cap &&
105
117
  !a.heap === !b.heap &&
106
118
  !a.optional === !b.optional &&
119
+ !a.big === !b.big &&
120
+ !a.raw === !b.raw &&
107
121
  sameType(a.elem, b.elem));
108
122
  case "vecArg":
109
123
  return !a.optional === !b.optional && sameType(a.elem, b.elem);
@@ -113,6 +127,11 @@ export function sameType(a, b) {
113
127
  return sameType(a.option, b.option);
114
128
  case "structRef":
115
129
  return a.struct === b.struct;
130
+ case "rawArray":
131
+ return sameType(a.elem, b.elem);
132
+ case "rbTree":
133
+ case "rbEntry":
134
+ return a.inst === b.inst;
116
135
  case "dataEnum":
117
136
  case "dataEnumArg":
118
137
  case "enumRef":
@@ -19,3 +19,18 @@ export declare const STACK_FRAME = 4096;
19
19
  export declare function buildSharedObject(cFile: string, outSo: string, sbpf?: Sbpf, tc?: Toolchain): void;
20
20
  /** The clang version string, for build manifests. */
21
21
  export declare function toolchainVersion(tc?: Toolchain): string;
22
+ /** One variable slot of a function's stack frame as clang laid it out: its size and the C variables sharing it. */
23
+ export interface FrameSlot {
24
+ size: number;
25
+ vars: {
26
+ name: string;
27
+ line: number;
28
+ }[];
29
+ }
30
+ /** clang's `-Rpass-analysis=stack-frame-layout` remarks: each function's variable slots. */
31
+ export declare function frameLayouts(remarks: string): Map<string, FrameSlot[]>;
32
+ /**
33
+ * clang's frame-size errors in the program's terms: which instruction or helper, how much, the locals that take the
34
+ * room (from `layouts`, clang's frame layout of the generated C `c`) and what to do.
35
+ */
36
+ export declare function stackError(message: string, layouts?: Map<string, FrameSlot[]>, c?: string): Error;
@@ -1,5 +1,5 @@
1
- import { execFileSync } from "node:child_process";
2
- import { existsSync, readdirSync, rmSync } from "node:fs";
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -79,7 +79,18 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
79
79
  run(tc.clang, [...cflags, ...incs, "-o", obj, "-c", cFile]);
80
80
  }
81
81
  catch (e) {
82
- throw stackError(e.message) ?? e;
82
+ const message = e.message;
83
+ if (!STACK_OVER.test(message))
84
+ throw e;
85
+ // Compiled again with debug info for clang's frame layout: which locals take the room.
86
+ const layoutFlags = cflags.filter((f) => f !== "-Werror" && !f.startsWith("-Wframe-larger-than"));
87
+ const res = spawnSync(tc.clang, [...layoutFlags, ...incs, "-g", "-w", "-Rpass-analysis=stack-frame-layout", "-o", obj, "-c", cFile], {
88
+ encoding: "utf8",
89
+ // A large program's remarks (one per function, every slot listed) run past the default 1 MiB.
90
+ maxBuffer: 256 * 1024 * 1024,
91
+ });
92
+ rmSync(obj, { force: true });
93
+ throw stackError(message, frameLayouts(res.stderr ?? ""), readFileSync(cFile, "utf8"));
83
94
  }
84
95
  run(tc.lld, [
85
96
  "-z",
@@ -109,11 +120,39 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
109
120
  export function toolchainVersion(tc = findToolchain()) {
110
121
  return execFileSync(tc.clang, ["--version"], { encoding: "utf8" }).split("\n")[0].trim();
111
122
  }
112
- /** clang's frame-size errors, in the program's terms: which instruction or helper, how much, what to do. */
113
- function stackError(message) {
114
- const over = [...message.matchAll(/stack frame size \((\d+)\) exceeds limit \((\d+)\) in '(\w+)'/g)];
115
- if (!over.length)
116
- return undefined;
123
+ const STACK_OVER = /stack frame size \((\d+)\) exceeds limit \((\d+)\) in '(\w+)'/;
124
+ /** clang's `-Rpass-analysis=stack-frame-layout` remarks: each function's variable slots. */
125
+ export function frameLayouts(remarks) {
126
+ const out = new Map();
127
+ for (const block of remarks.split(/^Function: /m).slice(1)) {
128
+ const lines = block.split("\n");
129
+ const fn = lines[0].trim().split(/\s/)[0];
130
+ const slots = [];
131
+ let slot;
132
+ for (const l of lines.slice(1)) {
133
+ const off = /^Offset: \[SP-?\d+\], Type: (\w+), Align: \d+, Size: (\d+)/.exec(l);
134
+ if (off) {
135
+ slot = off[1] === "Variable" ? { size: Number(off[2]), vars: [] } : undefined;
136
+ if (slot)
137
+ slots.push(slot);
138
+ continue;
139
+ }
140
+ const v = /^ {4}(\w+) @ .*:(\d+)(\s|$)/.exec(l);
141
+ if (v && slot)
142
+ slot.vars.push({ name: v[1], line: Number(v[2]) });
143
+ else
144
+ slot = undefined;
145
+ }
146
+ out.set(fn, slots);
147
+ }
148
+ return out;
149
+ }
150
+ /**
151
+ * clang's frame-size errors in the program's terms: which instruction or helper, how much, the locals that take the
152
+ * room (from `layouts`, clang's frame layout of the generated C `c`) and what to do.
153
+ */
154
+ export function stackError(message, layouts = new Map(), c = "") {
155
+ const over = [...message.matchAll(new RegExp(STACK_OVER.source, "g"))];
117
156
  // clang inlines helpers into their callers, so an instruction's frame includes theirs.
118
157
  const what = (fn) => fn.startsWith("ix_") ? `instruction ${fn.slice(3)} (with the helpers inlined into it)` : fn.startsWith("fn_") ? `helper ${fn.slice(3)}()` : fn;
119
158
  // Anything else clang reported in the same run stays in the message.
@@ -121,13 +160,109 @@ function stackError(message) {
121
160
  .split("\n")
122
161
  .filter((l) => / error: /.test(l) && !/-Wframe-larger-than/.test(l))
123
162
  .join("\n");
124
- return new Error(over.map((m) => `${what(m[3])} needs ${m[1]} bytes of stack; SBPF v0 gives each function ${m[2]}`).join("\n") +
125
- "\nKeep large structs and arrays in account data: bind them with const (a reference) instead of a typed local copy, or split the work into helpers." +
163
+ const cLines = c.split("\n");
164
+ // The C function a line of the generated C belongs to.
165
+ const fnAt = (line) => {
166
+ for (let i = line - 1; i >= 0; i--) {
167
+ const m = /^(?:__attribute__\(\(noinline\)\) )?static uint64_t ((?:fn|ix)_\w+)\(.*\) \{$/.exec(cLines[i] ?? "");
168
+ if (m)
169
+ return m[1];
170
+ }
171
+ return undefined;
172
+ };
173
+ // The source location nearest a line: the generated C carries one in its runtime messages ("(file.ts:12)").
174
+ const near = (line) => {
175
+ for (let d = 0; d < 40; d++)
176
+ for (const i of [line - 1 + d, line - 1 - d]) {
177
+ const m = /\(([\w.-]+\.ts):(\d+)\)/.exec(cLines[i] ?? "");
178
+ if (m)
179
+ return `${m[1]}:${m[2]}`;
180
+ }
181
+ return undefined;
182
+ };
183
+ // The C functions' bodies, and the struct and list locals of the helpers `fn` calls that clang may inline into it.
184
+ const bodies = new Map();
185
+ let current;
186
+ for (const l of cLines) {
187
+ const m = /^(__attribute__\(\(noinline\)\) )?static uint64_t ((?:fn|ix)_\w+)\(.*\) \{$/.exec(l);
188
+ if (m)
189
+ bodies.set(m[2], (current = []));
190
+ else if (l === "}")
191
+ current = undefined;
192
+ else
193
+ current?.push(l);
194
+ }
195
+ const noinline = new Set(cLines.flatMap((l) => /^__attribute__\(\(noinline\)\) static uint64_t ((?:fn|ix)_\w+)\(/.exec(l)?.[1] ?? []));
196
+ const inlinedLocals = (fn) => {
197
+ const out = [];
198
+ const seen = new Set();
199
+ const visit = (f) => {
200
+ for (const l of bodies.get(f) ?? [])
201
+ for (const call of l.matchAll(/\b(fn_\w+)\(/g)) {
202
+ const callee = call[1];
203
+ if (seen.has(callee) || noinline.has(callee))
204
+ continue;
205
+ seen.add(callee);
206
+ for (const d of bodies.get(callee) ?? []) {
207
+ const local = /^\s+TS[SFE]_\w+ l_(\w+?)_\d+(__v)?;$/.exec(d);
208
+ if (local)
209
+ out.push(`\`${local[1]}\` (${callee.slice(3)}())`);
210
+ }
211
+ visit(callee);
212
+ }
213
+ };
214
+ visit(fn);
215
+ return out;
216
+ };
217
+ const describe = (name) => {
218
+ const local = /^l_(\w+?)_\d+(__v|__h)?$/.exec(name);
219
+ if (local)
220
+ return `\`${local[1]}\``;
221
+ if (/^p_\w+$/.test(name))
222
+ return `parameter \`${name.slice(2)}\``;
223
+ const temps = [
224
+ [/^fv\d+$/, "a list literal's temporary"],
225
+ [/^st\d+$/, "a struct literal's temporary"],
226
+ [/^de\d+$/, "a data enum literal's temporary"],
227
+ [/^evv\d+$/, "an event's FixedVec"],
228
+ [/^bv\d+$/, "a pushBorsh value"],
229
+ [/^t\d+$/, "a helper's result"],
230
+ [/^s\d+$/, "a log line's text"],
231
+ ];
232
+ return temps.find(([re]) => re.test(name))?.[1] ?? `a temporary (${name})`;
233
+ };
234
+ const locals = (fn) => {
235
+ const slots = (layouts.get(fn) ?? []).filter((s) => s.size >= 64).sort((a, b) => b.size - a.size);
236
+ if (!slots.length)
237
+ return "";
238
+ const shown = slots.slice(0, 5).map((s) => {
239
+ const names = s.vars.map((v) => {
240
+ const owner = fnAt(v.line);
241
+ const at = near(v.line);
242
+ const where = [owner && owner !== fn ? `in ${what(owner).replace(" (with the helpers inlined into it)", "")}` : "", at ? `near ${at}` : ""]
243
+ .filter(Boolean)
244
+ .join(", ");
245
+ return `${describe(v.name)}${where ? ` (${where})` : ""}`;
246
+ });
247
+ // Variables whose lifetimes do not overlap share a slot. clang names no variable of an inlined helper.
248
+ return `${s.size} bytes: ${names.length ? [...new Set(names)].join(" / ") : "unnamed"}`;
249
+ });
250
+ const unnamed = slots.slice(0, 5).some((s) => !s.vars.length);
251
+ const inlined = unnamed ? inlinedLocals(fn) : [];
252
+ return (`\n biggest locals: ${shown.join("; ")}` +
253
+ (unnamed
254
+ ? inlined.length
255
+ ? `\n (unnamed: locals of the helpers inlined into it, among ${inlined.join(", ")}, or copies clang made)`
256
+ : "\n (unnamed: copies clang made)"
257
+ : ""));
258
+ };
259
+ return new Error(over.map((m) => `${what(m[3])} needs ${m[1]} bytes of stack; SBPF v0 gives each function ${m[2]}${locals(m[3])}`).join("\n") +
260
+ "\nKeep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals of its own into a /** @noinline */ helper, which gets its own 4 KiB frame." +
126
261
  (rest ? `\n${rest}` : ""));
127
262
  }
128
263
  function run(cmd, args) {
129
264
  try {
130
- execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
265
+ execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
131
266
  }
132
267
  catch (e) {
133
268
  const err = e;
@@ -0,0 +1,216 @@
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 { type Address, type KeyPairSigner } from "@solana/kit";
9
+ import { type LiteSVM, type TransactionMetadata } from "litesvm";
10
+ export declare const STAKE_PROGRAM_ADDRESS: Address;
11
+ export declare const VOTE_PROGRAM_ADDRESS: Address;
12
+ /** Size of a stake account (StakeStateV2). */
13
+ export declare const STAKE_ACCOUNT_SIZE = 200n;
14
+ /** Size of a vote account. */
15
+ export declare const VOTE_ACCOUNT_SIZE = 3762n;
16
+ /** StakeHistory keeps this many epochs, newest first. */
17
+ export declare const STAKE_HISTORY_MAX_ENTRIES = 512;
18
+ /** The EpochSchedule sysvar's fields (LiteSVM's `EpochSchedule` has them). */
19
+ export interface EpochScheduleLike {
20
+ slotsPerEpoch: bigint;
21
+ leaderScheduleSlotOffset: bigint;
22
+ warmup: boolean;
23
+ firstNormalEpoch: bigint;
24
+ firstNormalSlot: bigint;
25
+ }
26
+ /** The epoch of `slot` and the slot's index in it (EpochSchedule::get_epoch_and_slot_index). */
27
+ export declare function epochAndSlotIndex(schedule: EpochScheduleLike, slot: bigint): {
28
+ epoch: bigint;
29
+ slotIndex: bigint;
30
+ };
31
+ /** The first slot of `epoch` (EpochSchedule::get_first_slot_in_epoch). */
32
+ export declare function firstSlotInEpoch(schedule: EpochScheduleLike, epoch: bigint): bigint;
33
+ /** The epoch whose leader schedule is known at `slot` (EpochSchedule::get_leader_schedule_epoch). */
34
+ export declare function leaderScheduleEpoch(schedule: EpochScheduleLike, slot: bigint): bigint;
35
+ export interface WarpOptions {
36
+ /** Seconds the Clock's unixTimestamp advances per slot (default 0.4, millisecond precision). */
37
+ secondsPerSlot?: number;
38
+ }
39
+ /**
40
+ * Move the cluster to the first slot of `epoch`: the Clock's slot, epoch, leader schedule epoch and timestamps
41
+ * (unixTimestamp advances by `secondsPerSlot` per slot and the epoch starts then), by the VM's EpochSchedule, warmup
42
+ * epochs included. The blockhash expires, so a transaction sent again is a new one. The StakeHistory is left as it is:
43
+ * use a `StakeCluster` to have it filled in.
44
+ */
45
+ export declare function warpToEpoch(svm: LiteSVM, epoch: bigint, opts?: WarpOptions): void;
46
+ /** `warpToEpoch` to the next epoch; returns it. */
47
+ export declare function nextEpoch(svm: LiteSVM, opts?: WarpOptions): bigint;
48
+ /** A StakeHistory entry, and what `stakeActivation` returns for one delegation: lamports. */
49
+ export interface StakeHistoryEntryValue {
50
+ effective: bigint;
51
+ activating: bigint;
52
+ deactivating: bigint;
53
+ }
54
+ export type StakeActivationStatus = StakeHistoryEntryValue;
55
+ /** A StakeHistory entry. */
56
+ export declare function stakeHistoryEntry(effective?: bigint, activating?: bigint, deactivating?: bigint): StakeHistoryEntryValue;
57
+ /** Sum of entries, saturating at u64::MAX per field (StakeHistoryEntry's `+`). */
58
+ export declare function addStakeHistoryEntries(...entries: StakeHistoryEntryValue[]): StakeHistoryEntryValue;
59
+ /** Stake history by epoch: a Map, LiteSVM's `StakeHistory`, or anything with `get(epoch)`. */
60
+ export interface StakeHistoryLookup {
61
+ get(epoch: bigint): StakeHistoryEntryValue | null | undefined;
62
+ }
63
+ /** The parts of a Delegation that activation depends on. */
64
+ export interface DelegationLike {
65
+ stake: bigint;
66
+ activationEpoch: bigint;
67
+ deactivationEpoch: bigint;
68
+ }
69
+ export interface StakeActivationOptions {
70
+ /**
71
+ * `"integer"` (default): solana-stake-interface 4.3.0's `stake_activating_and_deactivating_v2`, the basis-point
72
+ * integer math of SIMD-0391 (Stake program v5.1). `"float"`: the f64 math it replaces (the deprecated
73
+ * `stake_activating_and_deactivating`), which the Stake program in LiteSVM 1.6.1 runs. They differ by a few lamports
74
+ * once amounts pass 2^53 lamports (about 9M SOL), e.g. with a mainnet-sized cluster.
75
+ */
76
+ math?: "integer" | "float";
77
+ }
78
+ /**
79
+ * The effective, activating and deactivating stake of a delegation at `targetEpoch`, given the cluster's stake history:
80
+ * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0), BigInt math with
81
+ * its u128 saturation. `newRateActivationEpoch` is the epoch from which warmup and cooldown are 9% per epoch rather
82
+ * than 25%: 0 (the default) as the Stake program has it on every cluster; `null` for 25% throughout (Rust's None).
83
+ */
84
+ export declare function stakeActivation(delegation: DelegationLike, targetEpoch: bigint, history: StakeHistoryLookup, newRateActivationEpoch?: bigint | null, opts?: StakeActivationOptions): StakeActivationStatus;
85
+ /** The StakeHistory sysvar of `svm`, by epoch (read from the sysvar account: newest first, as stored). */
86
+ export declare function readStakeHistory(svm: LiteSVM): Map<bigint, StakeHistoryEntryValue>;
87
+ /** Replace the StakeHistory sysvar of each VM with these entries (the newest 512 are kept). */
88
+ export declare function writeStakeHistory(svms: LiteSVM | readonly LiteSVM[], history: ReadonlyMap<bigint, StakeHistoryEntryValue>): void;
89
+ export interface StakeAuthorized {
90
+ staker: Address;
91
+ withdrawer: Address;
92
+ }
93
+ export interface StakeLockup {
94
+ unixTimestamp: bigint;
95
+ epoch: bigint;
96
+ custodian: Address;
97
+ }
98
+ export interface StakeMeta {
99
+ /**
100
+ * As stored. The Stake program in LiteSVM 1.6.1 holds back the Rent sysvar's minimum for 200 bytes instead
101
+ * (`svm.minimumBalanceForRentExemption(200n)`), which is smaller than what its Initialize writes here.
102
+ */
103
+ rentExemptReserve: bigint;
104
+ authorized: StakeAuthorized;
105
+ lockup: StakeLockup;
106
+ }
107
+ export interface Delegation extends DelegationLike {
108
+ voterPubkey: Address;
109
+ /** The legacy `warmup_cooldown_rate: f64` field, now reserved: its 8 bytes as stored. */
110
+ warmupCooldownRate: Uint8Array;
111
+ }
112
+ export interface Stake {
113
+ delegation: Delegation;
114
+ creditsObserved: bigint;
115
+ }
116
+ /** A stake account's data (StakeStateV2). */
117
+ export type StakeStateV2 = {
118
+ kind: "Uninitialized";
119
+ } | {
120
+ kind: "Initialized";
121
+ meta: StakeMeta;
122
+ } | {
123
+ kind: "Stake";
124
+ meta: StakeMeta;
125
+ stake: Stake;
126
+ stakeFlags: number;
127
+ } | {
128
+ kind: "RewardsPool";
129
+ };
130
+ /** Decode StakeStateV2 bytes. */
131
+ export declare function decodeStakeState(data: Uint8Array): StakeStateV2;
132
+ /** The stake account at `address` decoded, or null when it does not exist. */
133
+ export declare function readStakeAccount(svm: LiteSVM, address: Address): StakeStateV2 | null;
134
+ export interface StakeClusterOptions extends WarpOptions, StakeActivationOptions {
135
+ /**
136
+ * The rest of the cluster, added to every epoch's entry: a fixed entry or one per epoch. Default 400M SOL effective,
137
+ * nothing activating or deactivating, which lets a delegation of under 36M SOL warm up in one epoch, as on mainnet.
138
+ * Make `activating` / `deactivating` more than 9% of `effective` to see warmup and cooldown take several epochs.
139
+ */
140
+ base?: StakeHistoryEntryValue | ((epoch: bigint) => StakeHistoryEntryValue);
141
+ /** Count every stake account of the first VM (default true); false counts only the ones passed to `track`. */
142
+ allStakeAccounts?: boolean;
143
+ /** The epoch the 9% rate starts (default 0, as the Stake program has it); null for 25%. */
144
+ newRateActivationEpoch?: bigint | null;
145
+ }
146
+ /**
147
+ * A cluster's stake bookkeeping over one or more LiteSVMs. Each epoch advance appends the StakeHistory entry of the
148
+ * epoch that ends (the sum of `stakeActivation` over the cluster's delegations at that epoch, plus `base`), as a
149
+ * cluster does at an epoch boundary, then moves the Clock to the next epoch's first slot. Every VM gets the same Clock,
150
+ * EpochSchedule and StakeHistory (taken from the first VM when the cluster is made), so differential tests see
151
+ * identical sysvars; the delegations are read from the first VM.
152
+ *
153
+ * The default `math` is `"float"`, the Stake program's in LiteSVM 1.6.1, so the history it writes and `activation`
154
+ * agree to the lamport with what that program does.
155
+ */
156
+ export declare class StakeCluster {
157
+ readonly svms: readonly LiteSVM[];
158
+ private readonly entries;
159
+ private readonly tracked;
160
+ private readonly opts;
161
+ constructor(svms: LiteSVM | readonly LiteSVM[], opts?: StakeClusterOptions);
162
+ /** Count these stake accounts (with `allStakeAccounts: false`, only tracked ones count). */
163
+ track(...addresses: Address[]): this;
164
+ /** The current epoch (the first VM's Clock). */
165
+ get epoch(): bigint;
166
+ /** The StakeHistory written so far, by epoch. */
167
+ get history(): ReadonlyMap<bigint, StakeHistoryEntryValue>;
168
+ /** The delegations the cluster counts now: every Stake-state account (or the tracked ones) of the first VM. */
169
+ delegations(): Delegation[];
170
+ /** A delegation's (or a stake account's) activation at `epoch` (default: now), by this cluster's history. */
171
+ activation(of: Address | DelegationLike, epoch?: bigint): StakeActivationStatus;
172
+ /** The entry the epoch `epoch` ends with, given the delegations now and the history so far. */
173
+ entryAt(epoch: bigint): StakeHistoryEntryValue;
174
+ /** End the current epoch: append its entry and move every VM to the next epoch. Returns the new epoch. */
175
+ nextEpoch(): bigint;
176
+ /**
177
+ * End epochs one by one (an entry for each, none skipped) up to `epoch`, then move every VM to its first slot. The
178
+ * history must still end at the epoch before the Clock's (or be empty): a Clock moved past it some other way (the
179
+ * plain `warpToEpoch`, `setClock`) would leave epochs without an entry, which the Stake program misreads, so that is
180
+ * 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
181
+ * (to the first slot of `epoch` by the EpochSchedule); the timestamps still move forward.
182
+ */
183
+ warpToEpoch(epoch: bigint): void;
184
+ /** The newest epoch with an entry, or -1 for an empty history. */
185
+ private newestEntry;
186
+ private rateEpoch;
187
+ }
188
+ /**
189
+ * A vote account made by the Vote program (System CreateAccount of 3762 bytes, then InitializeAccount with
190
+ * VoteInit { node, authorized voter, authorized withdrawer, commission }). `node` signs (a new keypair by default);
191
+ * `voter` and `withdrawer` default to the node. Returns the vote account's address (`address` to choose it).
192
+ */
193
+ export declare function createVoteAccount(svm: LiteSVM, payer: KeyPairSigner, opts?: {
194
+ node?: KeyPairSigner;
195
+ voter?: Address;
196
+ withdrawer?: Address;
197
+ commission?: number;
198
+ address?: KeyPairSigner;
199
+ }): Promise<Address>;
200
+ /**
201
+ * A stake account made by the Stake program (System CreateAccount of 200 bytes holding `lamports` in all, rent
202
+ * reserve included, then Initialize with the authorities and lockup). Returns its address (`address` to choose it).
203
+ */
204
+ export declare function createStakeAccount(svm: LiteSVM, payer: KeyPairSigner, opts: {
205
+ staker: Address;
206
+ withdrawer: Address;
207
+ lamports: bigint;
208
+ lockup?: Partial<StakeLockup>;
209
+ address?: KeyPairSigner;
210
+ }): Promise<Address>;
211
+ /** Delegate a stake account to a vote account (Stake DelegateStake, signed by the staker; `staker` defaults to the payer). */
212
+ export declare function delegateStake(svm: LiteSVM, payer: KeyPairSigner, opts: {
213
+ stake: Address;
214
+ vote: Address;
215
+ staker?: KeyPairSigner;
216
+ }): Promise<TransactionMetadata>;