@typesol/cli 0.42.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 (44) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/README.md +10 -7
  3. package/dist/compiler/analyze.js +443 -12
  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 +25 -0
  9. package/dist/compiler/emit/base.js +58 -7
  10. package/dist/compiler/emit/calls.d.ts +67 -0
  11. package/dist/compiler/emit/calls.js +521 -46
  12. package/dist/compiler/emit/cpi-core.d.ts +20 -3
  13. package/dist/compiler/emit/cpi-core.js +226 -5
  14. package/dist/compiler/emit/cpi.js +8 -2
  15. package/dist/compiler/emit/expressions.js +38 -7
  16. package/dist/compiler/emit/program.js +30 -1
  17. package/dist/compiler/emit/rbtree.d.ts +7 -0
  18. package/dist/compiler/emit/rbtree.js +142 -0
  19. package/dist/compiler/emit/shared.d.ts +8 -0
  20. package/dist/compiler/emit/shared.js +9 -1
  21. package/dist/compiler/emit/statements.d.ts +27 -1
  22. package/dist/compiler/emit/statements.js +288 -19
  23. package/dist/compiler/emit/storage.d.ts +23 -2
  24. package/dist/compiler/emit/storage.js +100 -56
  25. package/dist/compiler/emit/token.js +2 -2
  26. package/dist/compiler/emit/views.d.ts +60 -0
  27. package/dist/compiler/emit/views.js +523 -0
  28. package/dist/compiler/idl.js +2 -1
  29. package/dist/compiler/model.d.ts +65 -4
  30. package/dist/compiler/model.js +14 -0
  31. package/dist/compiler/toolchain.d.ts +15 -0
  32. package/dist/compiler/toolchain.js +146 -11
  33. package/docs/architecture.md +9 -2
  34. package/docs/case-study-phoenix.md +226 -0
  35. package/docs/language.md +139 -8
  36. package/docs/migrate-from-anchor.md +1 -0
  37. package/docs/runtime.md +1 -1
  38. package/docs/stability.md +21 -2
  39. package/docs/troubleshooting.md +5 -2
  40. package/lib/typesol.d.ts +221 -4
  41. package/llms-full.txt +169 -14
  42. package/llms.txt +1 -1
  43. package/package.json +2 -2
  44. package/runtime/typesol_rt.h +407 -0
@@ -61,6 +61,8 @@ 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)}>`;
64
66
  if (t.big)
65
67
  return `BigVec<${typeName(t.elem)}>`;
66
68
  return t.cap === undefined ? `Vec<${typeName(t.elem)}>` : `FixedVec<${typeName(t.elem)}, ${t.cap}>`;
@@ -82,6 +84,12 @@ export function typeName(t) {
82
84
  return "EpochRewards";
83
85
  case "structRef":
84
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";
85
93
  }
86
94
  }
87
95
  export function sameType(a, b) {
@@ -109,6 +117,7 @@ export function sameType(a, b) {
109
117
  !a.heap === !b.heap &&
110
118
  !a.optional === !b.optional &&
111
119
  !a.big === !b.big &&
120
+ !a.raw === !b.raw &&
112
121
  sameType(a.elem, b.elem));
113
122
  case "vecArg":
114
123
  return !a.optional === !b.optional && sameType(a.elem, b.elem);
@@ -118,6 +127,11 @@ export function sameType(a, b) {
118
127
  return sameType(a.option, b.option);
119
128
  case "structRef":
120
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;
121
135
  case "dataEnum":
122
136
  case "dataEnumArg":
123
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;
@@ -32,7 +32,7 @@ program.so + program.build.json (manifest: versions, sha256 of sources and binar
32
32
  | `ts-plugin/` | The editor plugin (`typesol/ts-plugin`) |
33
33
  | `examples/` | Example programs; the `typesol init` templates are copies of three of them |
34
34
  | `test/` | The compiler's test suite (`pnpm test:core`), by subject: `language/`, `security/`, `examples/`, `integrations/` (token, Metaplex, oracle and other CPIs), `client/`, `cli/`, `verification/` (differential and fuzz tests). Shared: `harness.ts` and the `*-helpers.ts`, `fixtures/` (programs the tests compile), `golden/` (pinned generated C and clients), `programs/` (third-party program binaries, see its SOURCES.md), `anchor-twins/` (below) |
35
- | `showcase/` | Ports, apart from the compiler's own tests (`pnpm test:showcase`, its own CI job): `mainnet/` (SPL Stake Pool, Raydium AMM v4, CP-Swap and CLMM, Jito's MEV programs, Marginfi, coral-xyz/multisig, each checked against the binary on mainnet), `program-examples/` (TypeSOL rewrites of solana-developers/program-examples), `test/` (their differential tests, fuzzers, helpers and fixtures; `porting/` for the program-examples) |
35
+ | `showcase/` | Ports, apart from the compiler's own tests (`pnpm test:showcase`, its own CI job): `mainnet/` (Phoenix v1, SPL Stake Pool, Raydium AMM v4, CP-Swap and CLMM, Jito's MEV programs, Marginfi, coral-xyz/multisig, each checked against the binary on mainnet), `program-examples/` (TypeSOL rewrites of solana-developers/program-examples), `test/` (their differential tests, fuzzers, helpers and fixtures; `porting/` for the program-examples) |
36
36
  | `test/anchor-twins/` | Anchor twins of the counter, vault and escrow examples, for the differential tests (`pnpm build:twins`) and the zero-copy client test; the benchmarks themselves are in [typesol-lang/benchmarks](https://github.com/typesol-lang/benchmarks) |
37
37
  | `scripts/` | `smoke.ts`, `localnet.sh` and `localnet-fixtures.ts` (a local validator run), `fetch-programs.sh` (third-party binaries), `readme-bench.ts` (the README numbers), `codegen-snapshot.ts` (the generated C and IDL of every program, to diff a refactor), `release-manifest.ts` (a release's binary, IDL and toolchain hashes) |
38
38
  | `docs/` | User and contributor documentation (also published on typesol.com) |
@@ -82,6 +82,7 @@ call evaluates expressions), the method is declared `abstract` at the end of `ba
82
82
  | `storage.ts` | `StorageEmitter` | references into account data and locals, reads and writes, indexing, aliasing, argument validation |
83
83
  | `expressions.ts` | `ExpressionEmitter` | literals, operators and checked arithmetic, property reads, conditionals, text, casts |
84
84
  | `calls.ts` | `CallEmitter` | `call()` (the built-in dispatch), Vec methods, helpers, remaining accounts, foreign reads, return data |
85
+ | `views.ts` | `ViewEmitter` | views at run-time offsets (`loadRawAt`, `rawArrayAt`) and the RedBlackTree's binding, methods and node references (its per-tree C is `rbtree.ts`, its structural code `ts_rbt_*` in the runtime) |
85
86
  | `cpi-core.ts` | `CpiCoreEmitter` | seeds and PDAs, signer seeds, remaining-account ranges, byte buffers and Borsh serialization |
86
87
  | `create.ts` | `CreateEmitter` | `create` / `createIfNeeded` of program accounts, mints (with Token-2022 extensions), token accounts and ATAs; System transfers |
87
88
  | `token.ts` | `TokenEmitter` | SPL Token / Token-2022 instructions and the ATA program |
@@ -137,8 +138,13 @@ These invariants are easy to break. Each one has tests.
137
138
  message.
138
139
  - **No SDK byte loops.** Generated code and the runtime compare, copy and zero memory with `ts_key_eq`, `ts_mem_eq`,
139
140
  `ts_memcpy` and `ts_memzero` (8 bytes per instruction), not `sol_memcmp`, `sol_memcpy`, `sol_memset` or
140
- `SolPubkey_same`. `ts_bytes_cmp` stays byte-wise because it orders, not just compares. Checked u64 arithmetic uses
141
+ `SolPubkey_same`. Large regions go to the memory syscalls (max(10, n / 250) CU): `ts_memzero_bulk` and
142
+ `ts_memcpy_const` from 128 bytes, `ts_memcpy_bulk` (a run-time length) from 32, `sol_memmove_` for BigVec's moves.
143
+ `ts_bytes_cmp` stays byte-wise because it orders, not just compares. Checked u64 arithmetic uses
141
144
  `ts_add/sub/mul_overflow_u64`, which clang lowers to fewer instructions than the builtins on SBF.
145
+ - **A FixedVec's free slots are zero.** Bytes past a FixedVec's length are never read element by element, but its
146
+ whole layout is copied (into account data, an event, another list), so a list made from a literal zeroes them
147
+ (once, `ts_memzero_bulk`) and the stack's earlier contents never reach an account or a log.
142
148
  - **Heap use is bounded.** The heap is a bump allocator (32 KiB by default) and is never freed. Anything that runs in
143
149
  a loop must not allocate on every pass; hoist a reusable buffer instead (see `snapshotPlace()`).
144
150
 
@@ -188,6 +194,7 @@ the change. The sha256 values in the `*.build.json` manifests must not change.
188
194
  | `test/language/diagnostics.test.ts` | Every rejected construct, plus the golden C. |
189
195
  | `test/security/hardening.test.ts`, `test/security/regressions.test.ts` | Attacks and edge cases that once failed. Keep each as a negative test. |
190
196
  | `test/verification/fuzz-*.test.ts`, `test/verification/differential.test.ts` | Randomized checks against BigInt, a TypeScript state model, and the Anchor twins in `test/anchor-twins`. See [testing.md](testing.md). |
197
+ | `test/verification/rbtree-trace.test.ts` | The RedBlackTree replaying traces lib-sokoban 0.3 itself recorded (`test/verification/rbtree/`, rebuilt by its `regenerate.sh` with a small Rust oracle the tests do not need), bytes compared after every operation. |
191
198
  | `scripts/smoke.ts` | End to end against a real `solana-test-validator` (`scripts/localnet.sh`). |
192
199
 
193
200
  Some tests need optional inputs and are skipped without them:
@@ -0,0 +1,226 @@
1
+ # Case study: Phoenix v1
2
+
3
+ This page ports [Phoenix v1](https://github.com/Ellipsis-Labs/phoenix-v1), Ellipsis Labs' on-chain limit order book:
4
+ a central limit order book that matches and settles in the same instruction, price first and first in, first out
5
+ within a price, with no crank. Its repository now calls it Phoenix Legacy. The port is checked against the binary
6
+ that runs on mainnet as `PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY` (deployed in slot 231433470, 2023-11-21), not a
7
+ rebuild.
8
+
9
+ **Which source.** Commit c16694d rebuilt with `solana-verify build --library-name phoenix` (Solana 1.14.9) gives the
10
+ deployed executable's hash (`6877a5b732b3494b828a324ec846d526d962223959534dbaf4209e0da3b2d6a9`); OtterSec's
11
+ verification registry lists the program as verified from that commit. The repository was under BUSL 1.1 at c16694d;
12
+ on 2026-05-11 Ellipsis Labs relicensed it under the MIT License (5a34f7f) with the program's sources unchanged since
13
+ c16694d, so the port follows c16694d under MIT ([`test/programs/SOURCES.md`](../test/programs/SOURCES.md)).
14
+
15
+ Phoenix is a native program built with solana-program 1.14: a u8 tag, the instruction's Borsh arguments after it,
16
+ accounts by position. A market is one account: a 576-byte header, then a `FIFOMarket` whose bids, asks and traders are
17
+ three lib-sokoban `RedBlackTree`s laid out in the account's bytes (sized by the header: twelve size sets, up to 4,096
18
+ orders a side and 8,321 seats), read and written in place. Phoenix does not log its market events: it sends them to
19
+ itself in Log instructions, self-CPIs signed by a log-authority PDA, so clients read them from the inner instructions.
20
+ The order instructions return the ids of the orders that rested as return data, and the program's failures are often
21
+ Rust panics in solana-program 1.14's format, at the original's source locations.
22
+
23
+ | File | Holds |
24
+ | --- | --- |
25
+ | [`phoenix.ts`](../showcase/mainnet/phoenix/phoenix.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`): the four accounts every instruction starts with, the event recorder, dispatch to the 28 tags |
26
+ | [`state.ts`](../showcase/mainnet/phoenix/state.ts), [`errors.ts`](../showcase/mainnet/phoenix/errors.ts) | MarketHeader, the FIFOMarket prefix, the tree keys and values, Seat, PhoenixMarketEvent, the instruction arguments, PhoenixError from code 0 |
27
+ | [`checkers.ts`](../showcase/mainnet/phoenix/checkers.ts), [`util.ts`](../showcase/mainnet/phoenix/util.ts) | the account checks in the original's order, the market loader with its twelve sizes; PDAs, the quantity operators with their panics, the token CPIs |
28
+ | [`recorder.ts`](../showcase/mainnet/phoenix/recorder.ts) | the event recorder: batches of events sent in Log self-CPIs whenever the next event would not fit |
29
+ | [`matching.ts`](../showcase/mainnet/phoenix/matching.ts), [`book.ts`](../showcase/mainnet/phoenix/book.ts) | the FIFOMarket: place_order_inner, match_order, check_for_cross, eviction; reduce_order_inner and the cancels built on it |
30
+ | `orders.ts`, `cancel.ts`, `initialize.ts`, `governance.ts`, `seats.ts`, `funds.ts`, `fees.ts` | the instructions by subject |
31
+
32
+ ## What is ported
33
+
34
+ All 28 tags: Swap and SwapWithFreeFunds (0, 1), PlaceLimitOrder and its free-funds form (2, 3), ReduceOrder (4, 5),
35
+ CancelAllOrders (6, 7), CancelUpTo (8, 9), CancelMultipleOrdersById (10, 11), WithdrawFunds (12), DepositFunds (13),
36
+ RequestSeat (14), Log (15), PlaceMultiplePostOnlyOrders (16, 17), and the authority's InitializeMarket,
37
+ ClaimAuthority, NameSuccessor, ChangeMarketStatus, ChangeSeatStatus, RequestSeatAuthorized, EvictSeat,
38
+ ForceCancelOrders, CollectFees and ChangeFeeRecipient (100 to 109). Every order type (PostOnly, Limit, ImmediateOrCancel
39
+ and fill-or-kill, with base or quote budgets, minimum fills, match limits, the three self-trade behaviours, time in
40
+ force, fail-silent orders), free funds, taker fees, eviction from a full book, the order packet decoder with its
41
+ zero-padding retries, the market's statuses down to Tombstone, and the events byte for byte.
42
+
43
+ ## What it needed
44
+
45
+ TypeSOL gained these features for it (docs/language.md, "Porting a native program"); programs that use none of them
46
+ compile to the same C as before:
47
+
48
+ - **lib-sokoban's RedBlackTree** over account bytes, `rbTreeAt` / `rbTreeMutAt`: `get`, `insert`, `remove`, `min`,
49
+ `max`, `addrOf`, `nodeAt`, walks both ways, with a comparator of the program (Phoenix orders bids by inverted sequence
50
+ numbers). It runs sokoban's code statement for statement, so the bytes are the crate's: replayed against the real
51
+ crate with identical bytes after every operation, on the 21,650 recorded operations of the committed test (seeds
52
+ 1–3, capacities 1 to 4096, strides 32, 64 and 144) and, with the previous trace generator, on a one-off run of
53
+ 1,020,000 (capacities 1 to 512); sokoban's panics come out with its messages and source lines.
54
+ - **`removeAt(index)`**: the node `addrOf`, `min` or `max` found, removed with `remove(key)`'s writes and no second
55
+ search (the trace replay runs again with every `remove(key)` as `removeAt(addrOf(key))`). The port uses it where
56
+ Phoenix finds an order and then removes it: 62 to 103 compute units less per cancelled order (more in deeper books),
57
+ about 100 per order a match fills whole, 190 to 360 per eviction.
58
+ - **Cheaper tree walks** (one bounds check per node, the stack by pointer) and an **owner-check cache** for native
59
+ views (the market viewed again passes with a pointer compare): Phoenix's helpers each view the market again, often in
60
+ loops that write it.
61
+ - **Data enums by `pushBorsh`, straight-line**: `data.pushBorsh<PhoenixMarketEvent>({ kind: "Fill", … })` writes only
62
+ that variant, one room check and a store per field. Every event is appended to the batch this way: 47 compute units
63
+ less per Reduce event than the six `pushLE` calls it replaced, each of which checked the room of the batch (an
64
+ `Inout` parameter) on its own, and 55 to 70 less per Fill, Place, FillSummary, Evict or ExpiredOrder than serializing
65
+ the whole enum.
66
+ - **Struct arguments in place**: an owned struct (a local, a parameter passed on) goes to a helper that takes accounts by
67
+ pointer, so the book helpers take their MarketShape as a plain struct, not `Inout<T>`.
68
+ - **`Inout<T>`** helper parameters (Rust's `&mut`: the recorder and its 1,280-byte batch passed down the matching
69
+ engine), **`/** @noinline */`** and **`/** @heap */`** (room beyond one 4 KiB stack frame), local lists of 2 KiB
70
+ (asked for by a 2,052-byte list of collected order ids; the port keeps the 512 ids as u16 node indices).
71
+ - **Native-program foundations**: `loadRawAt` / `loadRawMutAt` (a struct at a run-time offset), `NATIVE_ACCOUNT_WRITES`
72
+ (views of one account written in place, judged by the runtime), byte builders (`pushLE`, `pushKey`, `pushBorsh`,
73
+ `setLE`, `truncate`) and `invokeInstruction` for the Log self-CPI, `setReturnData` and `logComputeUnits`, `closeRaw`
74
+ for Tombstone, `findProgramAddressWithBump`, errors from code 0 that log nothing (`ERROR_LOG_PREFIX = null`), and
75
+ panics as solana-program 1.14 writes them (`PANIC_STYLE = "solana-1.14"`, `panicsAt` for Rust's overflow messages at
76
+ the original's locations).
77
+ - **Source-level conveniences** the port reads better with: constant expressions (`EVENT_ROOM =
78
+ MAX_INNER_INSTRUCTION_SIZE - LOG_IX_ACCOUNT_META_SIZE`, the node sizes, `BIDS_OFFSET`), file-local structs for
79
+ helper-only types (left out of the IDL), comma-separated `for` updates, and read-only views read where they are made
80
+ (`loadRaw<MarketHeader>(m).status`).
81
+
82
+ ## How it is checked
83
+
84
+ The mainnet binary and the port run in two LiteSVMs under the same program id and the same Clock
85
+ ([`phoenix-helpers.ts`](../showcase/test/phoenix-helpers.ts)). Every account is made the same way in both, and every
86
+ transaction must give:
87
+
88
+ - the same outcome;
89
+ - the same log lines, every one: the original's messages and numbers, panics with their locations, the batch lines of
90
+ the recorder (Phoenix's own "Program consumption" lines by count and position; only the runtime's "consumed N of M
91
+ compute units" lines are left out);
92
+ - the same inner instructions in order, each one's program, accounts and data bytes: the Log self-CPIs, so every event
93
+ batch is compared byte for byte, and the token transfers;
94
+ - the same return data;
95
+ - the same lamports, owner and bytes in every account the transaction names (the books and the traders tree byte for
96
+ byte, rotations and colours included).
97
+
98
+ There are 3,575 such transactions in five files, on markets of 512 orders and 128 seats and of 4,096 and 8,321 (each
99
+ file fails unless it compares exactly its own count):
100
+
101
+ - **The non-matching instructions** (`phoenix.test.ts`; 824): the entry's checks for all 28 tags, InitializeMarket with
102
+ each of the twelve sizes and every refusal, the authority's instructions, seats, deposits and withdrawals, fees.
103
+ - **Orders and matching** (`phoenix-orders.test.ts`; 1,117): every order type on both sides, crossings of many levels,
104
+ self trades, match limits, minimum fills, budgets, fees (100% included), free funds, multiple-order grouping and its
105
+ failure behaviours, a full book (eviction and rejection), time in force, the sequence number's limit, matches whose
106
+ events take several Log batches (300 fills), the packet decoder on cut and invalid packets.
107
+ - **Reductions and cancels** (`phoenix-cancel.test.ts`; 390): the orders are placed by the original and its bytes
108
+ copied into the port's VM, so both start from the trees Phoenix itself wrote; partial, whole and oversized reductions,
109
+ foreign and unknown orders, every cancel form with its limits, ForceCancelOrders and EvictSeat, 90 to 512 cancels in
110
+ one instruction, the out-of-memory abort at the 513th, books of up to 8,000 orders, the overflow and division panics.
111
+ - **The original's own tests** (`phoenix-upstream.test.ts`; 1,082): each of the 50 test functions at c16694d (the
112
+ integration tests, the matching engine's unit tests, the packet decoder's) is mapped to a case
113
+ ([the mapping](../showcase/test/phoenix-upstream.md)): 11 were covered already, 37 are added there and run whole,
114
+ 2 are not applicable (compile-time type checks of the quantity macros). Each refusal the upstream test expects is
115
+ pinned to the original's error and message, and the upstream test's own assertions (balances, the book, free lots,
116
+ the sequence number, fees) are made on chain.
117
+ - **The limits** (`phoenix-limits.test.ts`; 162): markets with a tick size or a base lot of 0 (the divisions' panics),
118
+ a negative clock, multiple-order packets longer than a transaction carries, and both sides of each of the heap's
119
+ boundaries, through a forwarding caller program where a CPI is needed (see Differences).
120
+
121
+ States no instruction reaches in a test's time (fees accrued, a sequence number near its maximum, a damaged lot size)
122
+ are written into both VMs' bytes, and each test checks the outcome too, so that every error path is really reached.
123
+ Every compared transaction's compute units are kept, and each file fails unless the port uses fewer on every
124
+ transaction that succeeds: 2,390 of the 3,575.
125
+
126
+ **A random walk over the order book** (`phoenix-fuzz.test.ts`, not in those counts) runs a 512/128 and a 4096/8321
127
+ market, each book started nearly full of orders far from the action: seated makers and unseated takers deposit and
128
+ withdraw, place every kind of order with tokens or free funds, reduce and cancel (with others', unknown, wrong-side and
129
+ bit-flipped ids), the authority changes seats, forces cancels, evicts, collects fees and changes the market's status,
130
+ the clock moves on so orders expire, and some packets are corrupted. Every step goes through the same comparison, and
131
+ an oracle checks after each that the registered traders' locked and free lots plus the uncollected fees are exactly
132
+ what the vaults hold. A walk's choices and every keypair come from its seed, so a seed reproduces it. By default the
133
+ test walks seeds 1, 2 and 3 on both markets, 300 steps each (1,801 transactions), and requires minimum counts of real
134
+ effects decoded from the event batches (fills, partial fills, orders rested, self trades, expiries, evictions, fees)
135
+ and a minimum share of successes for every kind of instruction. `FUZZ_SEED` walks another seed and
136
+ `PHOENIX_FUZZ_STEPS` changes the length; a walk of 1,000 steps or more must also have every main kind of instruction
137
+ succeed and each book fill up and evict. Before the walk drew its keys from the seed, a one-off run of five seeds (1
138
+ and 1794299110079 at 1,000 steps, 2, 3 and 4 at 3,000; 21,593 transactions) found no difference.
139
+
140
+ ## Cost
141
+
142
+ Compute units per transaction, mainnet original against the port, from those tests (the token CPIs are the same work
143
+ in both; the account checks that derive PDAs vary with the bumps the keys need, each further bump about 1,500 units
144
+ in the original and 341 in the port, and a few rows by a few dozen units from run to run: a range is what two runs of
145
+ the five files gave, and `InitializeMarket`'s covers its twelve sizes):
146
+
147
+ | Instruction | Original | TypeSOL | |
148
+ | --- | ---: | ---: | ---: |
149
+ | `InitializeMarket` | 79,146–97,353 | 10,940–15,035 | 14–15% |
150
+ | `RequestSeat` | 14,900 | 4,599 | 31% |
151
+ | `DepositFunds` | 20,441 | 6,176 | 30% |
152
+ | `WithdrawFunds` | 17,760 | 6,201 | 35% |
153
+ | `CollectFees` | 13,814 | 4,977 | 36% |
154
+ | `PlaceLimitOrder`, PostOnly | 20,577–25,077 | 6,452–7,475 | 30–31% |
155
+ | `PlaceLimitOrder`, Limit, resting | 21,971–23,471 | 7,066–7,407 | 32% |
156
+ | `Swap`, 2 fills | 22,809–22,886 | 8,178–8,196 | 36% |
157
+ | `Swap`, 30 fills | 61,313–61,390 | 26,344–26,362 | 43% |
158
+ | `PlaceLimitOrder`, Limit through 20 fills, then resting | 108,397–114,399 | 52,894–54,260 | 47–49% |
159
+ | `PlaceMultiplePostOnlyOrders`, 5 orders in 4 levels | 34,605–40,614 | 13,324–14,698 | 36–39% |
160
+ | `ReduceOrder` | 15,235 | 5,170 | 34% |
161
+ | `CancelMultipleOrdersById`, 1 order | 15,984 | 5,708 | 36% |
162
+ | `CancelMultipleOrdersByIdWithFreeFunds`, 50 orders | 67,793–67,871 | 38,527–38,547 | 57% |
163
+ | `CancelUpTo`, 3 orders | 18,349–18,367 | 7,312 | 40% |
164
+ | `CancelAllOrdersWithFreeFunds`, 90 orders | 115,366 | 69,762 | 60% |
165
+ | `EvictSeat` | 22,966–33,466 | 7,306–9,693 | 29–32% |
166
+
167
+ At the extremes: a match of 300 fills in three Log batches 443,217–443,295 against 217,847–217,867 (49%);
168
+ `CancelAllOrders` of 512 orders in a 4,096 book 760,087 against 434,446 (57%), and of 200 among 8,000 orders 1,184,623
169
+ against 471,050 (40%); `CancelUpTo` searching 1,500 orders 1,002,398–1,002,399 against 456,958–456,960 (46%); the
170
+ 513th collected id runs both out of memory after 90,220 and 30,363.
171
+
172
+ The binary is 256,360 bytes against the original's 1,344,472.
173
+
174
+ ## Differences
175
+
176
+ What the port does not reproduce, and how a transaction would reach it:
177
+
178
+ - **Compute.** The port spends 13–61% of the original's units (up to 86% in `phoenix-limits.test.ts`, whose
179
+ transactions carry hundreds of account entries or go through a forwarding program), so a transaction that runs the
180
+ original out of its compute budget can complete in the port; the tests give both enough.
181
+ - **Memory, counted.** Phoenix allocates on solana-program 1.14.9's bump heap: 32 KiB from the top down, never freed,
182
+ and an allocation past it aborts with "Error: memory allocation failed, out of memory". The port keeps its own lists
183
+ fixed and counts Phoenix's heap instead ([`heap.ts`](../showcase/mainnet/phoenix/heap.ts)), charge by charge as the
184
+ Rust allocates: the entrypoint's 48 bytes per account entry and 72 per distinct account, the discriminant lines, the
185
+ event recorder, the status checks' messages (built even when they pass), each batch line, each SPL Token transfer's
186
+ instruction, the cancels' boxed tree iterators with their stacks and the ids they collect, CancelMultipleOrdersById's
187
+ decoded list and kept ids, the multiple-order packet's decoded lists, its sorts (the merge sort's buffer and stack of
188
+ runs) and the "Insufficient funds" lines of the orders it skips, the placed order ids and their Borsh bytes. So a
189
+ transaction that fills the heap (with up to 255 account entries, which Phoenix ignores past the ones it reads, or with
190
+ a CPI's larger instruction data) aborts in the port at the same allocation, after the same log lines and batches.
191
+ [`phoenix-limits.test.ts`](../showcase/test/phoenix-limits.test.ts) finds the original's boundary and compares both
192
+ sides of it (one account entry fewer succeeds, the next aborts) for CancelAllOrders and its free-funds form (257 to
193
+ 512 orders, bids and asks, 4 to 20 accounts of their own, top-level and through a CPI), CancelUpTo with a count and
194
+ with a search limit, ForceCancelOrders, CancelMultipleOrdersById through a CPI (230 and 340 entries; 341 always runs
195
+ out), and PlaceMultiplePostOnlyOrders through a CPI (decoded lists past their first 85 orders, scrambled sides, 130
196
+ resting orders, token deposits, skipped orders).
197
+ - **More than a transaction carries.** A CPI passes up to 10,240 bytes of instruction data, so a multiple-order packet
198
+ is decoded whatever its length, as Phoenix decodes it: past 170 orders a side always runs out of memory at its sort,
199
+ and past 340 while decoding; from 64 resting orders set_return_data refuses the ids (1,028 bytes and up), after every
200
+ order is placed and every batch sent, in both.
201
+ - **Memory, not counted.** What Phoenix formats only when it fails is not charged: assert_with_msg's line with its
202
+ location, the formatted failure lines (an IOC's minimum fill, "Market is not active, …"), the String of a Borsh
203
+ decoding error, the panic handler's line. Phoenix builds each on the heap before it reports the failure, so when the
204
+ heap no longer has room for it Phoenix aborts with the out-of-memory line (ProgramFailedToComplete) where the port
205
+ logs the failure and returns its error. A transaction gets there only by failing after it has nearly filled the
206
+ heap. For instance a forwarded multiple-order packet of 300 bids whose asks are cut short fails with BorshIoError in
207
+ both with few account entries and runs out of memory in both (its decoded Vec's last growth) with many; in between,
208
+ at one account count, Phoenix runs out of memory building the error's message (about 100 bytes) while the port
209
+ returns BorshIoError. A formatted failure line after a long match would need the same kind of near-full heap.
210
+ Neither are InitializeMarket's, CollectFees' and the seat and governance
211
+ instructions' own lines and vectors charged (only their batches): with at most 128 distinct accounts, the most a
212
+ transaction locks, they stay far below the heap. A Limit order's crossing check (a boxed iterator) and a match's
213
+ batches are counted, but no test reaches the limit with them: it takes a match of about a thousand fills and more
214
+ distinct accounts than a transaction holds without lookup tables.
215
+ - **Damaged trees.** A tree walk keeps its stack of 64 nodes on the program's stack, more than any red-black tree a u32
216
+ index can address holds on one path; only damaged registers go deeper, and the port panics where sokoban's heap stack
217
+ would grow. The panics of a node index out of range (`nodeAt` on damaged registers) take their locations from
218
+ sokoban's source, not from the binary.
219
+ - **Paths v1 never takes.** An order of zero lots on a book (only bytes written by hand put one there) is removed as
220
+ the original removes it: a cancel meeting one is tested, the matching engine's two such paths ("Empty order found in
221
+ check_for_cross", a tombstone met while matching) are ported but not reached by a test. The unclean-division warning
222
+ of a bid's unlock, which no market InitializeMarket accepts can produce, is tested on written bytes.
223
+
224
+ The tests run on LiteSVM without account-data direct mapping; both programs write the market in place, so both would
225
+ fault at the same write. The runtime truncates a transaction's log at 10,000 bytes at a point that depends on the
226
+ compute-unit lines, which differ by design, so the harness lifts that limit to compare the whole log.