@typesol/cli 0.42.0 → 0.44.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 (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
@@ -7,9 +7,13 @@
7
7
  * so existing clients keep working. Account structs holding a String, Vec or Option get `@layout borsh`, so they keep
8
8
  * Anchor's bytes (existing accounts stay readable); where a layout still differs (a String or Vec nested in a struct, a
9
9
  * data enum, a COption) it says so in a note and a comment.
10
+ *
11
+ * The IDL is checked as `typesol client` checks it (checkIdl): names, addresses and byte lists reach the skeleton only
12
+ * when well-formed, and text from the IDL (docs, relations, the program's name) only inside comments, escaped.
10
13
  */
11
14
  import { createHash } from "node:crypto";
12
15
  import { ACCOUNT_MEMBERS, cNameProblem, fieldIdlName } from "../compiler/analyze.js";
16
+ import { checkIdl, commentText, printable } from "./clientgen.js";
13
17
  const RESERVED = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await".split(" "));
14
18
  const camel = (s) => s.replace(/[_-]+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase()).replace(/^[A-Z]/, (c) => c.toLowerCase());
15
19
  const pascal = (s) => camel(s).replace(/^[a-z]/, (c) => c.toUpperCase());
@@ -38,6 +42,13 @@ const PROGRAMS = {
38
42
  ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL: "AssociatedTokenProgram",
39
43
  };
40
44
  export function generatePort(idl) {
45
+ // An IDL with an empty instructions list still ports its types (a skeleton to add instructions to).
46
+ checkIdl(idl);
47
+ const res = port(idl);
48
+ return { ...res, notes: res.notes.map(printable) };
49
+ }
50
+ const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
51
+ function port(idl) {
41
52
  const notes = [];
42
53
  const imports = new Set();
43
54
  const use = (n) => (imports.add(n), n);
@@ -263,12 +274,15 @@ export function generatePort(idl) {
263
274
  return undefined;
264
275
  return quiet ? "x" : tsType(t, "account", at);
265
276
  };
266
- const esc = (s) => s.replace(/\*\//g, "* /");
267
- const docs = (lines, pad = "", tags = []) => tags.length
268
- ? `${pad}/**\n${lines?.length ? `${pad} * ${esc(lines.join(" "))}\n` : ""}${tags.map((t) => `${pad} * ${t}\n`).join("")}${pad} */\n`
269
- : lines?.length
270
- ? `${pad}/** ${esc(lines.join(" "))} */\n`
271
- : "";
277
+ const esc = (s) => commentText(String(s));
278
+ const docs = (given, pad = "", tags = []) => {
279
+ const lines = Array.isArray(given) ? given.filter((l) => typeof l === "string") : undefined;
280
+ return tags.length
281
+ ? `${pad}/**\n${lines?.length ? `${pad} * ${esc(lines.join(" "))}\n` : ""}${tags.map((t) => `${pad} * ${t}\n`).join("")}${pad} */\n`
282
+ : lines?.length
283
+ ? `${pad}/** ${esc(lines.join(" "))} */\n`
284
+ : "";
285
+ };
272
286
  // What an Anchor IDL says of a zero-copy type (repr, serialization), kept as tags so the port's IDL says it too.
273
287
  const metaTags = (def) => [
274
288
  ...(def.serialization ? [`@serialization ${def.serialization}`] : []),
@@ -276,15 +290,25 @@ export function generatePort(idl) {
276
290
  ];
277
291
  const out = [];
278
292
  // Constants: integer literals and strings; expressions are left to port by hand.
279
- for (const c of idl.constants ?? []) {
280
- const ty = typeof c.type === "string" && INTS.has(c.type) ? c.type : undefined;
281
- const name = /^[A-Za-z_][A-Za-z0-9_]*$/.test(c.name) ? c.name : ident(c.name);
282
- if (ty && /^-?\d[\d_]*$/.test(c.value.trim()))
283
- out.push(`export const ${name}: ${use(ty)} = ${c.value.trim().replace(/_/g, "")}n;`);
284
- else if (c.type === "string" && /^".*"$/.test(c.value.trim()))
285
- out.push(`export const ${name} = ${c.value.trim()};`);
293
+ for (const c of Array.isArray(idl.constants) ? idl.constants : []) {
294
+ const ty = typeof c?.type === "string" && INTS.has(c.type) ? c.type : undefined;
295
+ const value = typeof c?.value === "string" ? c.value.trim() : undefined;
296
+ // A string constant is copied only as the string it parses to, re-quoted: the IDL's text never becomes code.
297
+ let text;
298
+ try {
299
+ text = c?.type === "string" && value?.startsWith('"') ? JSON.parse(value) : undefined;
300
+ }
301
+ catch {
302
+ text = undefined;
303
+ }
304
+ if (typeof c?.name !== "string" || !IDENT.test(c.name))
305
+ notes.push(`constant ${JSON.stringify(c?.name)}: not an identifier; port it by hand`);
306
+ else if (ty && value !== undefined && /^-?\d[\d_]*$/.test(value))
307
+ out.push(`export const ${c.name}: ${use(ty)} = ${value.replace(/_/g, "")}n;`);
308
+ else if (typeof text === "string")
309
+ out.push(`export const ${c.name} = ${JSON.stringify(text)};`);
286
310
  else
287
- notes.push(`constant ${c.name} = ${c.value}: not a literal; port it by hand`);
311
+ notes.push(`constant ${c.name} = ${String(c.value)}: not a literal; port it by hand`);
288
312
  }
289
313
  if (out.length)
290
314
  out.push("");
@@ -348,7 +372,8 @@ export function generatePort(idl) {
348
372
  // Errors: TypeSOL numbers them from 6000 in order; `/** @code N */` keeps an IDL code that skips ahead. NotPorted,
349
373
  // last, marks the instructions still to write, so the codes of the program's own errors do not move.
350
374
  const errors = [...(idl.errors ?? [])].sort((a, b) => a.code - b.code);
351
- const program = typeName(pascal(idl.metadata?.name ?? "program"));
375
+ const rawName = idl.metadata?.name;
376
+ const program = typeName(pascal(typeof rawName === "string" && IDENT.test(rawName) ? rawName : "program"));
352
377
  const errorEnum = `${program}Error`;
353
378
  if (errors.some((e, i) => e.code < 6000 || (i > 0 && e.code === errors[i - 1].code)))
354
379
  notes.push(`errors: codes below 6000 or repeated in the IDL (${errors.map((e) => e.code).join(", ")}) cannot be kept, so clients see other codes`);
@@ -408,8 +433,8 @@ export function generatePort(idl) {
408
433
  : `@${camel(s.path ?? "")}`);
409
434
  comments.push(`${ident(a.name)}: PDA [${seeds.join(", ")}]`);
410
435
  }
411
- if (a.relations?.length)
412
- comments.push(`${ident(a.name)}: has_one ${a.relations.map(camel).join(", ")}`);
436
+ if (Array.isArray(a.relations) && a.relations.length)
437
+ comments.push(`${ident(a.name)}: has_one ${a.relations.map((r) => camel(String(r))).join(", ")}`);
413
438
  }
414
439
  for (const g of ix.args)
415
440
  params.push(`${unique(ident(g.name), "Arg")}: ${tsType(g.type, "arg", `${ix.name}(${g.name})`)}`);
@@ -436,7 +461,7 @@ export function generatePort(idl) {
436
461
  notes.push(`account ${a.name}: its discriminator is not sha256("account:${a.name}"); TypeSOL derives that one, so existing accounts would not load`);
437
462
  }
438
463
  const header = [
439
- `// Ported from the ${idl.metadata?.name ?? "program"} IDL by \`typesol port\`. Fill in the instruction bodies;`,
464
+ `// Ported from the ${typeof rawName === "string" && rawName ? commentText(rawName) : "program"} IDL by \`typesol port\`. Fill in the instruction bodies;`,
440
465
  "// pick Account<T> / Mut<T> / Init<T> for the AccountInfo parameters that hold one of the structs below.",
441
466
  `import { ${[
442
467
  ...[...imports]
@@ -53,6 +53,26 @@ export declare function buildWorkspace(ws: Workspace, names?: string[], opts?: {
53
53
  result: BuildResult;
54
54
  clientPath: string;
55
55
  }[];
56
+ /** What a test needs of a built program. */
57
+ export interface BuiltProgram {
58
+ address: string;
59
+ soPath: string;
60
+ idl: BuildResult["idl"];
61
+ /** False when the existing build was up to date and was loaded instead of rebuilt. */
62
+ rebuilt: boolean;
63
+ }
64
+ /**
65
+ * The program built for a test: the existing build when it is up to date (same sources, runtime header, TypeSOL,
66
+ * TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records),
67
+ * else a fresh one. Concurrent callers (parallel test workers) wait for each other instead of building over each other.
68
+ */
69
+ export declare function buildForTest(ws: Workspace, name: string): BuiltProgram;
70
+ /**
71
+ * Run `fn` holding `<dir>/.typesol-build.lock`, created exclusively: one build of a program at a time across processes.
72
+ * The lock records its holder's host and pid; a lock whose process is gone (on this host) or that is older than
73
+ * LOCK_STALE_MS is taken over, so a crashed or killed build does not block the next one.
74
+ */
75
+ export declare function withBuildLock<T>(dir: string, fn: () => T): T;
56
76
  /** The `solana program deploy` arguments for one built program (deploying again upgrades it). */
57
77
  export declare function deployArgs(soPath: string, keypair: string, opts: {
58
78
  url?: string;
package/dist/workspace.js CHANGED
@@ -12,10 +12,14 @@
12
12
  * The address is recorded in typesol.json on first build, so a lost or swapped keypair is caught before deploying.
13
13
  */
14
14
  import { agentsMd, CLAUDE_MD, cursorRule, MCP_JSON } from "./ai.js";
15
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { createHash } from "node:crypto";
16
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
17
+ import os from "node:os";
16
18
  import path from "node:path";
19
+ import ts from "typescript";
17
20
  import { writeClient } from "./tools/clientgen.js";
18
21
  import { build, COMPILER_VERSION, SBPF_VERSIONS } from "./compiler/index.js";
22
+ import { checkToolchain, RUNTIME_DIR, toolchainInfo } from "./compiler/toolchain.js";
19
23
  import { loadOrCreateKeypair } from "./keys.js";
20
24
  import { TEMPLATES } from "./templates.js";
21
25
  export const CONFIG = "typesol.json";
@@ -104,13 +108,176 @@ export function programAddress(ws, name, opts = {}) {
104
108
  export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {}) {
105
109
  return names.map((name) => {
106
110
  const paths = programPaths(ws, name);
107
- const { address, created, keyless } = programAddress(ws, name, { needKeypair: opts.needKeypair });
108
- const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile });
109
- // The TypeScript client (docs/client.md) is written with the build, from the same IDL.
110
- const clientPath = writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`)).path;
111
- return { paths, address, created, keyless, result, clientPath };
111
+ // Every build of a program writes the same files (<name>.c, .o, .so, …), and the first one creates its keypair:
112
+ // another process building it at the same time (vitest runs test files in parallel workers) would overwrite them.
113
+ return withBuildLock(paths.outDir, () => {
114
+ const { address, created, keyless } = programAddress(ws, name, { needKeypair: opts.needKeypair });
115
+ const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile });
116
+ // The TypeScript client (docs/client.md) is written with the build, from the same IDL.
117
+ const clientPath = writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`)).path;
118
+ return { paths, address, created, keyless, result, clientPath };
119
+ });
112
120
  });
113
121
  }
122
+ /**
123
+ * The program built for a test: the existing build when it is up to date (same sources, runtime header, TypeSOL,
124
+ * TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records),
125
+ * else a fresh one. Concurrent callers (parallel test workers) wait for each other instead of building over each other.
126
+ */
127
+ export function buildForTest(ws, name) {
128
+ const paths = programPaths(ws, name);
129
+ return withBuildLock(paths.outDir, () => {
130
+ const { address } = programAddress(ws, name);
131
+ const current = upToDateBuild(paths, address, ws.sbpf);
132
+ if (current)
133
+ return { ...current, rebuilt: false };
134
+ const result = build(paths.entry, paths.outDir, address, { sbpf: ws.sbpf });
135
+ writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`));
136
+ return { address, soPath: result.soPath, idl: result.idl, rebuilt: true };
137
+ });
138
+ }
139
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
140
+ /** The existing build of a program if building it again would give the same files, else undefined. */
141
+ function upToDateBuild(paths, address, sbpf) {
142
+ // The compiler names a program's files after its entry file (programs/counter.ts → counter.so).
143
+ const base = path.join(paths.outDir, path.basename(paths.entry).replace(/\.ts$/, ""));
144
+ const files = { manifest: `${base}.build.json`, so: `${base}.so`, idl: `${base}.json`, client: `${base}.client.ts` };
145
+ if (!Object.values(files).every((f) => existsSync(f)))
146
+ return undefined;
147
+ let manifest;
148
+ let idl;
149
+ try {
150
+ manifest = JSON.parse(readFileSync(files.manifest, "utf8"));
151
+ idl = JSON.parse(readFileSync(files.idl, "utf8"));
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ if (manifest.compiler !== COMPILER_VERSION || manifest.typescript !== ts.version || manifest.sbpf !== sbpf || manifest.profile)
157
+ return undefined;
158
+ if (idl.address !== address || !manifest.sources || typeof manifest.sources !== "object")
159
+ return undefined;
160
+ if (sha256(readFileSync(files.so)) !== manifest.binary)
161
+ return undefined;
162
+ const root = path.dirname(paths.entry);
163
+ for (const [rel, hash] of Object.entries(manifest.sources)) {
164
+ const file = rel === "<runtime>/typesol_rt.h" ? path.join(RUNTIME_DIR, "typesol_rt.h") : path.resolve(root, rel);
165
+ if (!existsSync(file) || sha256(readFileSync(file)) !== hash)
166
+ return undefined;
167
+ }
168
+ // A new import changes the importing file, so every source of the current program is in the list; the runtime and
169
+ // the entry must be there too (a manifest from another layout).
170
+ if (!manifest.sources["<runtime>/typesol_rt.h"] || !manifest.sources[path.basename(paths.entry)])
171
+ return undefined;
172
+ // A manifest from before 0.44.0 has no host: rebuild once to record the toolchain in full.
173
+ if (!manifest.host || manifest.host.os !== process.platform || manifest.host.arch !== process.arch)
174
+ return undefined;
175
+ // Last, as it runs clang: updated platform-tools may compile the same C differently.
176
+ const toolchain = toolchainInfo();
177
+ if (manifest.clang !== toolchain.clang || manifest.platformTools !== toolchain.platformTools)
178
+ return undefined;
179
+ // A reused build came from this toolchain too: the same warning (or refusal) as building it.
180
+ checkToolchain(toolchain);
181
+ return { address, soPath: files.so, idl };
182
+ }
183
+ /** How long a build lock may be held before a waiter treats it as abandoned (a build takes seconds to a few minutes). */
184
+ const LOCK_STALE_MS = 15 * 60 * 1000;
185
+ const LOCK_POLL_MS = 100;
186
+ /**
187
+ * Run `fn` holding `<dir>/.typesol-build.lock`, created exclusively: one build of a program at a time across processes.
188
+ * The lock records its holder's host and pid; a lock whose process is gone (on this host) or that is older than
189
+ * LOCK_STALE_MS is taken over, so a crashed or killed build does not block the next one.
190
+ */
191
+ export function withBuildLock(dir, fn) {
192
+ mkdirSync(dir, { recursive: true });
193
+ const lock = path.join(dir, ".typesol-build.lock");
194
+ const me = `${os.hostname()} ${process.pid} ${Date.now()}`;
195
+ const deadline = Date.now() + LOCK_STALE_MS + 60_000;
196
+ for (;;) {
197
+ let fd;
198
+ try {
199
+ fd = openSync(lock, "wx");
200
+ }
201
+ catch (e) {
202
+ if (e.code !== "EEXIST")
203
+ throw e;
204
+ }
205
+ if (fd !== undefined) {
206
+ try {
207
+ writeSync(fd, me);
208
+ }
209
+ finally {
210
+ closeSync(fd);
211
+ }
212
+ try {
213
+ return fn();
214
+ }
215
+ finally {
216
+ // Only our own lock: a waiter may have taken it over after LOCK_STALE_MS.
217
+ try {
218
+ if (readFileSync(lock, "utf8") === me)
219
+ unlinkSync(lock);
220
+ }
221
+ catch {
222
+ // Already gone.
223
+ }
224
+ }
225
+ }
226
+ const holder = readLock(lock);
227
+ if (holder !== undefined && isStale(holder, lock)) {
228
+ // Read again just before removing it: another waiter may have replaced the stale lock with its own meanwhile.
229
+ if (readLock(lock) === holder)
230
+ try {
231
+ unlinkSync(lock);
232
+ }
233
+ catch {
234
+ // Removed by another waiter.
235
+ }
236
+ continue;
237
+ }
238
+ if (Date.now() > deadline)
239
+ throw new Error(`timed out waiting for ${lock} (held by ${holder ?? "?"}); delete it if no build is running`);
240
+ sleepSync(LOCK_POLL_MS);
241
+ }
242
+ }
243
+ function readLock(lock) {
244
+ try {
245
+ return readFileSync(lock, "utf8");
246
+ }
247
+ catch {
248
+ return undefined;
249
+ }
250
+ }
251
+ function isStale(holder, lock) {
252
+ const [host, pid] = holder.split(" ");
253
+ let age;
254
+ try {
255
+ age = Date.now() - statSync(lock).mtimeMs;
256
+ }
257
+ catch {
258
+ return false;
259
+ }
260
+ if (age > LOCK_STALE_MS)
261
+ return true;
262
+ // An empty or partly written lock: its writer is between open and write, unless it died there.
263
+ if (!host || !pid || !/^\d+$/.test(pid))
264
+ return age > 10_000;
265
+ if (host !== os.hostname())
266
+ return false;
267
+ try {
268
+ process.kill(Number(pid), 0);
269
+ return false;
270
+ }
271
+ catch (e) {
272
+ // EPERM: the process exists but belongs to another user.
273
+ return e.code === "ESRCH";
274
+ }
275
+ }
276
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
277
+ /** Block this thread (builds are synchronous, so waiting for one is too). */
278
+ function sleepSync(ms) {
279
+ Atomics.wait(sleeper, 0, 0, ms);
280
+ }
114
281
  /** The `solana program deploy` arguments for one built program (deploying again upgrades it). */
115
282
  export function deployArgs(soPath, keypair, opts) {
116
283
  const args = ["program", "deploy", soPath, "--program-id", keypair, "--use-rpc"];
package/docs/ai.md CHANGED
@@ -23,7 +23,8 @@ own project notes below them in AGENTS.md.
23
23
  ([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
24
24
  and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
25
25
  in one file, to paste into a chat or give to a model as context. Both also ship in the npm package
26
- (`node_modules/typesol/llms-full.txt`).
26
+ (`node_modules/typesol/llms-full.txt` in a project `typesol init` created, which installs `@typesol/cli` under the
27
+ name `typesol`; `node_modules/@typesol/cli/llms-full.txt` where it is installed under its own name).
27
28
 
28
29
  ## Errors an agent can fix by itself
29
30
 
@@ -34,13 +35,17 @@ in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on ch
34
35
  ## The MCP server
35
36
 
36
37
  `typesol mcp` serves the [Model Context Protocol](https://modelcontextprotocol.io) on stdio. `typesol init` writes
37
- `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx typesol mcp`. Other clients take the
38
- same command:
38
+ `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx --no-install typesol mcp`: the
39
+ project's own copy, after `npm install`. `--no-install` matters: `typesol` is not the npm package's name, and without
40
+ it npx would fetch whatever package is published as `typesol` when the project's copy is missing. Other clients take
41
+ the same command, run in the project directory:
39
42
 
40
43
  ```json
41
- { "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
44
+ { "mcpServers": { "typesol": { "command": "npx", "args": ["--no-install", "typesol", "mcp"] } } }
42
45
  ```
43
46
 
47
+ Outside a project, start it from the published package by its full name: `npx -y @typesol/cli mcp`.
48
+
44
49
  | Tool | What it does |
45
50
  | --- | --- |
46
51
  | `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
@@ -48,5 +53,5 @@ same command:
48
53
  | `docs` | searches the docs and returns the best-matching sections |
49
54
  | `rules` | the rules above |
50
55
 
51
- Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
56
+ Building and testing stay in the shell (`npm test`, `npx --no-install typesol build`): they need the platform-tools and write
52
57
  files, which an agent should do in the open.
@@ -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 |
@@ -102,7 +103,7 @@ representation in between. We reviewed this on 2026-10-30 and kept it that way f
102
103
  named in the source, see `alias.ts`), a second backend (SBF without clang), and optimizations clang cannot see
103
104
  because they depend on account semantics (dropping a repeated check, packing a `@layout borsh` account only where
104
105
  it changed).
105
- - **What it would cost now:** rewriting most of the compiler's 14,000 lines, and losing the property every release
106
+ - **What it would cost now:** rewriting most of the compiler's 19,000 lines, and losing the property every release
106
107
  relies on: programs that do not use a change compile to the same binaries. Audit scope and differential results
107
108
  would start over.
108
109
  - **What we have instead:** the layers above, each owning one concern; `Ref` / `Value` as the typed place and value
@@ -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:
package/docs/audit.md CHANGED
@@ -7,26 +7,29 @@ with TypeSOL are out of scope; their authors audit them.
7
7
 
8
8
  ## Scope
9
9
 
10
- In order of priority. Line counts at 0.40.0 (November 2026).
10
+ In order of priority. Line counts at 0.43.0 (November 2026).
11
11
 
12
12
  | Priority | Component | Files | Lines | Why |
13
13
  | --- | --- | --- | ---: | --- |
14
- | 1 | C runtime | `runtime/typesol_rt.h` | 2,510 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
- | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 870 | Which checks each account parameter gets, and their order |
16
- | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 2,802 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
17
- | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 4,084 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
14
+ | 1 | C runtime | `runtime/typesol_rt.h` | 2,995 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
+ | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 879 | Which checks each account parameter gets, and their order |
16
+ | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 3,742 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
17
+ | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 5,633 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
18
+ | 1 | Raw views and the red-black tree | `src/compiler/emit/views.ts`, `rbtree.ts` | 655 | Accounts read without a discriminator at run-time offsets (`loadRaw`, `loadRawAt`, `rawArrayAt`, `BigVec`), their bounds, and the red-black tree's node indexes (`rbTreeAt`) |
18
19
  | 1 | Metaplex CPIs | `src/compiler/emit/metaplex.ts` | 1,454 | Token Metadata, Core and Bubblegum instruction layouts and their account lists |
19
- | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 1,820 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
20
- | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 2,930 | What the language accepts; constraints and account types as parsed from the source |
21
- | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,316 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
20
+ | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 2,088 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
21
+ | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 3,486 | What the language accepts; constraints and account types as parsed from the source |
22
+ | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,460 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
22
23
  | 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, deploy and verification commands |
23
24
 
24
- The language surface is `lib/typesol.d.ts` (2,163 lines): every type and built-in a program can use, with its
25
+ The language surface is `lib/typesol.d.ts` (2,581 lines): every type and built-in a program can use, with its
25
26
  documented behavior. [docs/language.md](language.md) is the reference; [docs/architecture.md](architecture.md) maps
26
27
  the code, [docs/runtime.md](runtime.md) the runtime's conventions.
27
28
 
28
29
  Out of scope: the Solana runtime, platform-tools (clang, lld), the TypeScript compiler, and programs written with
29
- TypeSOL.
30
+ TypeSOL. The platform-tools are part of what a binary trusts all the same: the tests cover the toolchain the release
31
+ declares (`TESTED_TOOLCHAIN` in `src/compiler/toolchain.ts`: Agave 3.1.10, platform-tools v1.52), builds with another
32
+ one warn, and the review of 0.43.0 traced one defect to how that backend passes struct arguments.
30
33
 
31
34
  ## What to check
32
35
 
@@ -48,14 +51,57 @@ accepts. Areas where a bug would be most damaging, and where earlier internal re
48
51
 
49
52
  ## Earlier reviews
50
53
 
51
- Internal reviews, by the maintainers, in October 2026. Their findings and fixes are in the CHANGELOG. The releases
52
- after 0.25.0 (0.26.0 to 0.40.0) have had no review of this kind yet; they add, among others, `u256`, big-endian seeds
54
+ Internal reviews, by the maintainers: none of them is an independent audit. Their findings and fixes are in the
55
+ CHANGELOG.
56
+
57
+ ### 0.43.0 (2026-11-11)
58
+
59
+ An internal review of 0.43.0 as published. It probed the compiler's semantics with targeted programs (helpers,
60
+ references, closures, seeds, `close()`, Borsh decoding), read the runtime header and the C generated for those
61
+ programs, and exercised the tooling (the CLI commands and `typesol/testing`). It did not cover the emitters of the
62
+ Metaplex and token CPI wrappers, the oracles, builds for SBPF v1 and v2, or Windows.
63
+
64
+ Defects found, fixed in 0.44.0 (its CHANGELOG section, with a test
65
+ for each):
66
+
67
+ - **Helper arguments were not copies.** A Pubkey, Option, string or u256 argument reaches a helper as a pointer to the
68
+ caller's object (that is how the SBF backend passes it), so a helper that was not inlined and wrote that object read
69
+ its own write through the parameter: an authorization check on the old value (`rotate(v, v.admin, caller)` with
70
+ `v.admin = v.pending` inside) passed on the new one. Whether it happened depended on clang's inlining.
71
+ - **Seed lists were read at the CPI instead of where they are written.** A list bound to a name, given to a helper,
72
+ or written beside an argument with side effects read its seeds when the CPI ran, so after `st.count += 1n` the
73
+ program signed for another PDA than the one the source names.
74
+ - **The reference rule was skipped for account-group fields and loaded accounts.** A reference into an account used
75
+ after a helper that may move the account's data is refused; it was not when the account reached the helper as an
76
+ account-group field or had been loaded with `loadAccountMut`, and such a program wrote through the stale reference.
77
+ - **Borsh length checks wrapped.** The decoder subtracted before comparing, so for an `Option` of a struct holding an
78
+ Option (or a Vec of such structs) a short buffer wrapped the subtraction and the read went past the end of the
79
+ input: bounded by the struct's size, and read only.
80
+ - **Evaluation order with closures.** A local read before a closure or list callback that changes it kept the new
81
+ value instead of the one it had when read; a string viewing text inside an `Inout` place was not copied for the
82
+ helper taking the place.
83
+ - **`close()` gaps.** Closing an account into itself compiled, `Dup<…>` was accepted on an account the body closes,
84
+ and an account could be used after `close()` in the same instruction (its writes were dropped).
85
+ - **Tooling: IDL text reached generated code unvalidated.** `typesol cpi` and `typesol port` wrote names and other text
86
+ from the IDL they were given into the TypeScript they generate without the checks `typesol client` makes.
87
+
88
+ Programs built with 0.43.0 or earlier should be rebuilt with 0.44.0 or later and redeployed. The first defect is
89
+ the one that can break an authorization check; [security-model.md](security-model.md#review-of-0430-2026-11-11)
90
+ says how to tell whether a program was exposed to it.
91
+
92
+ ### Before 0.43.0
93
+
94
+ Internal reviews in October 2026. The releases from 0.26.0 to 0.42.0 were not reviewed one by one: the 0.43.0 review
95
+ read the code that includes them, but probed only the areas above. They add, among others, `u256`, big-endian seeds
53
96
  and accounts loaded in the body (0.37.0), stored bumps in nested fields and error members without messages (0.38.0),
54
97
  `@code`, `@repr` / `@serialization`, `@bytes` / `@idlName`, `f64`, Options inside Options in arguments and events,
55
98
  loop-scoped `loadAccountMut` with `Dup<T>`, account resizing and raw writes, `systemProgram.createPda` (0.39.0), and
56
99
  the native-program surface: `loadRaw` / `loadRawMut` (accounts without a discriminator), instruction data readers,
57
- error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0). An external review should include them;
58
- the native-program surface first, since it skips the account checks Anchor-style parameters get.
100
+ error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0), the agent tooling (`typesol mcp`, 0.41.0),
101
+ Borsh accounts without a discriminator, `BigVec<T>`, typed CPIs on remaining accounts and the Stake program's CPIs
102
+ (0.42.0), views at run-time offsets (`loadRawAt`, `rawArrayAt`), the built-in red-black tree (`rbTreeAt`), `Inout<T>`
103
+ helper parameters and `closeRaw` (0.43.0). An external review should include them; the native-program surface first,
104
+ since it skips the account checks Anchor-style parameters get, and the areas the 0.43.0 review did not cover.
59
105
 
60
106
  - **0.25.0** (runtime and emitted checks): two Medium issues fixed, a remaining account loaded mutably twice through
61
107
  the same slot, and a Vec element written after its right side resized the Vec; plus a token program ambiguity,
@@ -67,8 +113,8 @@ the native-program surface first, since it skips the account checks Anchor-style
67
113
 
68
114
  ## Evidence
69
115
 
70
- - **Tests**: by subject under `test/` (`docs/architecture.md`); the count of each run is in CI's log (727 on main on
71
- 2026-11-01). `test/security/` holds the attacks.
116
+ - **Tests**: by subject under `test/` (`docs/architecture.md`); the count of each run is in CI's log.
117
+ `test/security/` holds the attacks.
72
118
  - **Differential tests**: the same transactions to TypeSOL and to Anchor twins (`test/anchor-twins`), comparing
73
119
  outcomes, account contents and balances after every step.
74
120
  - **Model-based fuzzing** (`test/verification/`): arithmetic against BigInt at every width, `u256` against BigInt,
@@ -93,7 +139,7 @@ git clone https://github.com/typesol-lang/typesol && cd typesol
93
139
  pnpm install && pnpm build
94
140
  pnpm fetch:programs # Metaplex binaries for the token-metadata, Core and Bubblegum tests
95
141
  pnpm build:twins # the Anchor twins (Rust + Anchor 1.0.2)
96
- pnpm test # everything; CI runs it on Ubuntu (Node 22, 24) per change, macOS daily
142
+ pnpm test # everything; CI runs it on Ubuntu (Node 22, 24) per change, macOS on demand (macos.yml)
97
143
  pnpm fuzz # the randomized checks, wide
98
144
  ```
99
145
 
@@ -212,7 +212,7 @@ with their Solscan links in the [performance report](https://typesol.com/report/
212
212
 
213
213
  The steps this port followed, in order:
214
214
 
215
- 1. Generate the skeleton from the Anchor IDL: `npx typesol port target/idl/escrow.json --out programs/escrow.ts`. It
215
+ 1. Generate the skeleton from the Anchor IDL: `npx @typesol/cli port target/idl/escrow.json --out programs/escrow.ts`. It
216
216
  keeps instruction names, discriminators, account order and error codes.
217
217
  2. Turn each `#[account(...)]` into the parameter's type, using the table above and
218
218
  [Accounts and constraints](migrate-from-anchor.md#accounts-and-constraints). Keep the account order: it is the