@typesol/cli 0.38.0 → 0.40.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 (61) hide show
  1. package/CHANGELOG.md +373 -2
  2. package/README.md +43 -26
  3. package/SECURITY.md +1 -1
  4. package/dist/cli.js +37 -3
  5. package/dist/compiler/analyze.d.ts +6 -11
  6. package/dist/compiler/analyze.js +331 -34
  7. package/dist/compiler/emit/alias.js +3 -2
  8. package/dist/compiler/emit/base.d.ts +7 -1
  9. package/dist/compiler/emit/base.js +2 -0
  10. package/dist/compiler/emit/borsh.js +63 -2
  11. package/dist/compiler/emit/calls.d.ts +14 -1
  12. package/dist/compiler/emit/calls.js +311 -21
  13. package/dist/compiler/emit/cpi-core.js +17 -5
  14. package/dist/compiler/emit/cpi.js +81 -27
  15. package/dist/compiler/emit/create.d.ts +7 -0
  16. package/dist/compiler/emit/create.js +27 -0
  17. package/dist/compiler/emit/expressions.d.ts +6 -0
  18. package/dist/compiler/emit/expressions.js +102 -6
  19. package/dist/compiler/emit/function.d.ts +7 -0
  20. package/dist/compiler/emit/function.js +164 -29
  21. package/dist/compiler/emit/program.js +27 -2
  22. package/dist/compiler/emit/shared.d.ts +15 -5
  23. package/dist/compiler/emit/shared.js +5 -0
  24. package/dist/compiler/emit/statements.d.ts +28 -1
  25. package/dist/compiler/emit/statements.js +270 -13
  26. package/dist/compiler/emit/storage.d.ts +10 -1
  27. package/dist/compiler/emit/storage.js +50 -11
  28. package/dist/compiler/hints.d.ts +5 -0
  29. package/dist/compiler/hints.js +88 -0
  30. package/dist/compiler/idl.d.ts +1 -1
  31. package/dist/compiler/idl.js +42 -11
  32. package/dist/compiler/index.d.ts +3 -0
  33. package/dist/compiler/index.js +6 -1
  34. package/dist/compiler/model.d.ts +47 -10
  35. package/dist/compiler/model.js +14 -4
  36. package/dist/testing.js +8 -0
  37. package/dist/tools/clientgen.js +10 -1
  38. package/dist/tools/portgen.d.ts +6 -0
  39. package/dist/tools/portgen.js +68 -17
  40. package/docs/architecture.md +5 -4
  41. package/docs/audit.md +31 -19
  42. package/docs/case-study-escrow.md +5 -5
  43. package/docs/case-study-jito-mev.md +9 -5
  44. package/docs/case-study-marginfi.md +797 -0
  45. package/docs/case-study-multisig.md +3 -3
  46. package/docs/case-study-raydium-amm.md +80 -0
  47. package/docs/case-study-raydium-clmm.md +44 -33
  48. package/docs/case-study-raydium-cp-swap.md +3 -3
  49. package/docs/cli.md +5 -5
  50. package/docs/client.md +1 -1
  51. package/docs/errors.md +13 -5
  52. package/docs/language.md +65 -32
  53. package/docs/migrate-from-anchor.md +4 -1
  54. package/docs/runtime.md +1 -1
  55. package/docs/security-model.md +2 -1
  56. package/docs/testing.md +34 -1
  57. package/docs/troubleshooting.md +6 -0
  58. package/lib/typesol.d.ts +118 -10
  59. package/package.json +9 -7
  60. package/runtime/typesol_rt.h +158 -17
  61. package/ts-plugin/index.js +24 -1
@@ -45,13 +45,13 @@ export declare function buildIdl(model: ProgramModel, address: string, version?:
45
45
  docs?: string[];
46
46
  name: string;
47
47
  } | {
48
- name: string;
49
48
  type: {
50
49
  kind: string;
51
50
  variants: {
52
51
  name: string;
53
52
  }[];
54
53
  };
54
+ name: string;
55
55
  } | {
56
56
  name: string;
57
57
  docs: string[];
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { argIdlName, snakeCase } from "./analyze.js";
2
+ import { argIdlName, fieldIdlName, snakeCase } from "./analyze.js";
3
3
  import { decodeAddress } from "../keys.js";
4
4
  import { fixedVecName, isWritable, optionKey, typeName, } from "./model.js";
5
5
  const SYSTEM_PROGRAM = "11111111111111111111111111111111";
@@ -53,10 +53,17 @@ function borshIdlType(t) {
53
53
  return { defined: { name: t.name } };
54
54
  return idlType(t);
55
55
  }
56
+ /** An IDL type's serialization and repr, as an Anchor IDL lists them (before `type`). */
57
+ function idlMetaFields(m) {
58
+ return {
59
+ ...(m?.serialization ? { serialization: m.serialization } : {}),
60
+ ...(m?.repr ? { repr: { kind: m.repr.kind, ...(m.repr.packed ? { packed: true } : {}), ...(m.repr.align ? { align: m.repr.align } : {}) } } : {}),
61
+ };
62
+ }
56
63
  function idlType(t, borshOption = false) {
57
64
  switch (t.kind) {
58
65
  case "int":
59
- return t.name;
66
+ return t.f64 ? "f64" : t.name;
60
67
  case "bool":
61
68
  return "bool";
62
69
  case "pubkey":
@@ -77,12 +84,21 @@ function idlType(t, borshOption = false) {
77
84
  case "dataEnumArg":
78
85
  // Borsh enum in arguments and events; fixed tag + payload in account data.
79
86
  return borshOption || t.kind === "dataEnumArg" ? { defined: { name: t.name } } : { defined: { name: fixedEnumName(t.name) } };
80
- case "vec":
81
- return t.cap === undefined ? { vec: idlType(t.elem) } : { defined: { name: fixedVecName(t) } };
82
- case "vecArg":
83
- return { vec: idlType(t.elem) };
87
+ case "vec": {
88
+ if (t.cap !== undefined)
89
+ return { defined: { name: fixedVecName(t) } };
90
+ const vec = t.elem.kind === "int" && t.elem.name === "u8" ? "bytes" : { vec: idlType(t.elem) };
91
+ return t.optional ? { option: vec } : vec;
92
+ }
93
+ case "vecArg": {
94
+ // Anchor writes Vec<u8> as bytes; a FixedVec argument is a Borsh Vec on the wire too.
95
+ const vec = t.elem.kind === "int" && t.elem.name === "u8" ? "bytes" : { vec: idlType(t.elem) };
96
+ return t.optional ? { option: vec } : vec;
97
+ }
84
98
  case "arrayArg":
85
99
  return idlType(t.array);
100
+ case "optionArg":
101
+ return { option: idlType(t.option.inner) };
86
102
  case "structRef":
87
103
  return { defined: { name: t.struct } };
88
104
  default:
@@ -211,28 +227,43 @@ export function buildIdl(model, address, version = "0.1.0") {
211
227
  })),
212
228
  ...(ix.returns ? { returns: idlType(ix.returns) } : {}),
213
229
  })),
214
- accounts: structs.filter((s) => model.accountStructs.has(s.name)).map((s) => ({ name: s.name, discriminator: s.accountDiscriminator })),
230
+ accounts: structs
231
+ .filter((s) => model.accountStructs.has(s.name) && !model.foreignAccounts?.has(s.name))
232
+ .map((s) => ({ name: s.name, discriminator: s.accountDiscriminator })),
215
233
  events: structs.filter((s) => model.events.has(s.name)).map((s) => ({ name: s.name, discriminator: s.eventDiscriminator })),
216
234
  errors: model.errors.map((e) => ({ code: e.code, name: e.name, ...(e.msg ? { msg: e.msg } : {}) })),
217
235
  types: [
218
236
  ...usedStructs.map((s) => ({
219
237
  name: s.name,
220
238
  ...docsOf(s.node),
239
+ ...idlMetaFields(s.idlMeta),
221
240
  type: {
222
241
  kind: "struct",
223
- fields: s.fields.map((f) => ({
224
- name: snakeCase(f.name),
242
+ // An event lists its fields as it sends them (declared order); account data as it stores them.
243
+ fields: (s.declared && !model.accountStructs.has(s.name) ? s.declared.map((n) => s.fields.find((f) => f.name === n)) : s.fields).map((f) => ({
244
+ name: f.idlName ?? fieldIdlName(f.name),
225
245
  ...docsOf(s.node.members.find((m) => m.name && ts.isIdentifier(m.name) && m.name.text === f.name)),
226
- type: s.layout === "borsh" ? borshIdlType(f.type) : idlType(f.type, model.events.has(s.name) && !model.accountStructs.has(s.name)),
246
+ type: f.idlBytes
247
+ ? f.type.kind === "array"
248
+ ? { array: [{ array: ["u8", f.idlBytes] }, f.type.len] }
249
+ : { array: ["u8", f.idlBytes] }
250
+ : s.layout === "borsh" || s.wire === "borsh"
251
+ ? borshIdlType(f.type)
252
+ : idlType(f.type, model.events.has(s.name) && !model.accountStructs.has(s.name)),
227
253
  })),
228
254
  },
229
255
  })),
230
- ...[...model.enums.values()].map((e) => ({ name: e.name, type: { kind: "enum", variants: e.variants.map((v) => ({ name: v })) } })),
256
+ ...[...model.enums.values()].map((e) => ({
257
+ name: e.name,
258
+ ...idlMetaFields(e.idlMeta),
259
+ type: { kind: "enum", variants: e.variants.map((v) => ({ name: v })) },
260
+ })),
231
261
  // A variable enum (it holds strings) only exists in Borsh: no fixed account-data form to describe.
232
262
  ...[...model.dataEnums.values()].flatMap((e) => [
233
263
  {
234
264
  name: e.name,
235
265
  ...docsOf(e.node),
266
+ ...idlMetaFields(e.idlMeta),
236
267
  type: {
237
268
  kind: "enum",
238
269
  variants: e.variants.map((v) => v.fields.length
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { type EmitOptions } from "./emit/index.js";
2
3
  import { buildIdl } from "./idl.js";
3
4
  import { type Sbpf } from "./toolchain.js";
@@ -5,6 +6,8 @@ import type { ProgramModel } from "./model.js";
5
6
  export { CompileError, formatDiagnostic, type Diagnostic } from "./diagnostics.js";
6
7
  export type { ProgramModel } from "./model.js";
7
8
  export { SBPF_VERSIONS, type Sbpf } from "./toolchain.js";
9
+ /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
10
+ export declare function typescriptHint(d: ts.Diagnostic): string | undefined;
8
11
  export interface Generated {
9
12
  model: ProgramModel;
10
13
  c: string;
@@ -3,13 +3,18 @@ import { createRequire } from "node:module";
3
3
  import ts from "typescript";
4
4
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import path from "node:path";
6
- import { analyze } from "./analyze.js";
6
+ import { analyze, LIB_PATH } from "./analyze.js";
7
+ import { hintForTypeScript } from "./hints.js";
7
8
  import { emitProgram } from "./emit/index.js";
8
9
  import { buildIdl } from "./idl.js";
9
10
  import { buildSharedObject, toolchainVersion } from "./toolchain.js";
10
11
  import { RUNTIME_DIR } from "./toolchain.js";
11
12
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
12
13
  export { SBPF_VERSIONS } from "./toolchain.js";
14
+ /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
15
+ export function typescriptHint(d) {
16
+ return hintForTypeScript(d, ts.flattenDiagnosticMessageText(d.messageText, "\n"), LIB_PATH);
17
+ }
13
18
  /** Typecheck, enforce the TypeSOL subset, and generate C. Throws CompileError with every diagnostic. */
14
19
  export function generate(entry, opts = {}) {
15
20
  const analysis = analyze(entry, opts.files);
@@ -14,6 +14,7 @@ export declare function unsignedC(name: IntName): string;
14
14
  export type ScalarType = {
15
15
  kind: "int";
16
16
  name: IntName;
17
+ f64?: boolean;
17
18
  } | {
18
19
  kind: "bool";
19
20
  }
@@ -43,6 +44,7 @@ export type ValueType = ScalarType | {
43
44
  kind: "vecArg";
44
45
  elem: FieldType;
45
46
  cap?: number;
47
+ optional?: boolean;
46
48
  }
47
49
  /** `FixedArray<T, N>` instruction argument (Borsh [T; N]), parsed into a read-only copy. */
48
50
  | {
@@ -51,6 +53,13 @@ export type ValueType = ScalarType | {
51
53
  kind: "array";
52
54
  };
53
55
  }
56
+ /** `Option<S>` instruction argument of a fixed-size struct (Borsh tag + S), parsed into a read-only `TS_Opt_s_S`. */
57
+ | {
58
+ kind: "optionArg";
59
+ option: FieldType & {
60
+ kind: "option";
61
+ };
62
+ }
54
63
  /** A Solana `SignerSeeds` helper parameter: the seeds of one PDA signature, built with signer([...]). */
55
64
  | {
56
65
  kind: "signerSeeds";
@@ -105,10 +114,7 @@ export type FieldType = ScalarType | {
105
114
  /** `Option<T>` in account data: fixed { u8 is_some; T value } (value zeroed when None). T may be a struct here. */
106
115
  | {
107
116
  kind: "option";
108
- inner: ScalarType | {
109
- kind: "struct";
110
- name: string;
111
- };
117
+ inner: OptionInner;
112
118
  }
113
119
  /** A data-carrying enum (discriminated union): fixed { u8 tag; payload sized for the largest variant }. */
114
120
  | {
@@ -125,10 +131,15 @@ export type FieldType = ScalarType | {
125
131
  elem: FieldType;
126
132
  cap?: number;
127
133
  heap?: true;
134
+ optional?: true;
128
135
  };
129
136
  export interface StructField {
130
137
  name: string;
131
138
  type: FieldType;
139
+ /** `/** @bytes *\/` on an integer field: the IDL describes it as [u8; N] (its little-endian bytes, as stored). */
140
+ idlBytes?: number;
141
+ /** `/** @idlName _pad0 *\/`: the field's name in the IDL, where the source cannot use it (Rust's `_pad0`). */
142
+ idlName?: string;
132
143
  /** The declaration, while the struct is being analyzed (for messages). */
133
144
  node?: ts.Node;
134
145
  }
@@ -164,6 +175,12 @@ export interface StructDef {
164
175
  * Anchor's bytes, where strings, Vecs and Options take only what they hold).
165
176
  */
166
177
  layout: "fixed" | "borsh";
178
+ /** The field names as declared, when the fixed layout stores them in another order (growable Vecs last). */
179
+ declared?: string[];
180
+ /** "borsh": a struct with Options that only travels in instruction data and events: Borsh there, fixed in C. */
181
+ wire?: "borsh";
182
+ /** `/** @repr … *\/` and `/** @serialization … *\/`: what the IDL says of an Anchor zero-copy type (see IdlMeta). */
183
+ idlMeta?: IdlMeta;
167
184
  /**
168
185
  * A @layout borsh struct with a `string` field or a data enum carrying strings: they are views of the bytes it was
169
186
  * read from, so it is an argument, return value or event, never account data.
@@ -451,6 +468,7 @@ export interface ConstDef {
451
468
  /** A data-carrying enum: `export type Action = { kind: "Deposit"; amount: u64 } | { kind: "Pause" }`. */
452
469
  export interface DataEnumDef {
453
470
  name: string;
471
+ idlMeta?: IdlMeta;
454
472
  variants: {
455
473
  name: string;
456
474
  fields: StructField[];
@@ -469,6 +487,20 @@ export interface DataEnumDef {
469
487
  export interface EnumDef {
470
488
  name: string;
471
489
  variants: string[];
490
+ idlMeta?: IdlMeta;
491
+ }
492
+ /**
493
+ * The repr and serialization an Anchor IDL records for a type (`/** @repr c *\/`, `@repr c packed`, `@repr c align 8`,
494
+ * `@repr rust`; `/** @serialization bytemuck *\/`), kept in the port's IDL. A repr(C) struct that is not packed must
495
+ * have its fields where C puts them, since TypeSOL stores fields back to back.
496
+ */
497
+ export interface IdlMeta {
498
+ repr?: {
499
+ kind: "c" | "rust";
500
+ packed?: boolean;
501
+ align?: number;
502
+ };
503
+ serialization?: string;
472
504
  }
473
505
  export interface ErrorDef {
474
506
  code: number;
@@ -504,14 +536,13 @@ export interface ProgramModel {
504
536
  /** Top-level `const NAME = literal` compile-time constants. */
505
537
  constants: Map<string, ConstDef>;
506
538
  /** Types used inside Option<...>, for C typedefs and IDL types (scalars, or structs in account data). */
507
- options: Map<string, ScalarType | {
508
- kind: "struct";
509
- name: string;
510
- }>;
539
+ options: Map<string, OptionInner>;
511
540
  /** Structs passed to emit(), filled in while emitting. */
512
541
  events: Set<string>;
513
542
  /** Structs used as Account/Mut/Init. */
514
543
  accountStructs: Set<string>;
544
+ /** Account structs only taken as another program's (`Owner<Account<T>, "…">`): not in the IDL's accounts. */
545
+ foreignAccounts?: Set<string>;
515
546
  /** Structs passed as instruction arguments (directly, in arrays or in Vecs): their IDL layout is the fixed one. */
516
547
  argStructs: Set<string>;
517
548
  /** FixedString capacities in use, for C typedefs and IDL types. */
@@ -531,10 +562,16 @@ export declare function sameType(a: ValueType | FieldType, b: ValueType | FieldT
531
562
  export declare function scalarSize(t: ScalarType): number;
532
563
  export declare function isScalar(t: ValueType | FieldType): t is ScalarType;
533
564
  /** Stable C identifier suffix for a scalar, used in TS_Opt_<suffix>. */
534
- export declare function optionKey(t: ScalarType | {
565
+ /** What an Option holds: a scalar, a struct, or a fixed array of those (Anchor's Option<[u16; 3]>). */
566
+ export type OptionInner = ScalarType | {
535
567
  kind: "struct";
536
568
  name: string;
537
- }): string;
569
+ } | {
570
+ kind: "array";
571
+ elem: FieldType;
572
+ len: number;
573
+ };
574
+ export declare function optionKey(t: OptionInner): string;
538
575
  export declare function scalarKey(t: ScalarType): string;
539
576
  /** The C type of a heap Vec<T> (in a `@layout borsh` struct): `TSH_<T>`. */
540
577
  export declare function heapVecName(t: FieldType & {
@@ -59,11 +59,15 @@ export function typeName(t) {
59
59
  case "enumRef":
60
60
  return t.name;
61
61
  case "vec":
62
+ if (t.optional)
63
+ return `Option<Vec<${typeName(t.elem)}>>`;
62
64
  return t.cap === undefined ? `Vec<${typeName(t.elem)}>` : `FixedVec<${typeName(t.elem)}, ${t.cap}>`;
63
65
  case "vecArg":
64
- return `Vec<${typeName(t.elem)}>`;
66
+ return t.optional ? `Option<Vec<${typeName(t.elem)}>>` : `Vec<${typeName(t.elem)}>`;
65
67
  case "arrayArg":
66
68
  return typeName(t.array);
69
+ case "optionArg":
70
+ return typeName(t.option);
67
71
  case "signerSeeds":
68
72
  return "SignerSeeds";
69
73
  case "account":
@@ -97,11 +101,16 @@ export function sameType(a, b) {
97
101
  case "option":
98
102
  return sameType(a.inner, b.inner);
99
103
  case "vec":
100
- return a.cap === b.cap && !a.heap === !b.heap && sameType(a.elem, b.elem);
104
+ return (a.cap === b.cap &&
105
+ !a.heap === !b.heap &&
106
+ !a.optional === !b.optional &&
107
+ sameType(a.elem, b.elem));
101
108
  case "vecArg":
102
- return sameType(a.elem, b.elem);
109
+ return !a.optional === !b.optional && sameType(a.elem, b.elem);
103
110
  case "arrayArg":
104
111
  return sameType(a.array, b.array);
112
+ case "optionArg":
113
+ return sameType(a.option, b.option);
105
114
  case "structRef":
106
115
  return a.struct === b.struct;
107
116
  case "dataEnum":
@@ -118,8 +127,9 @@ export function scalarSize(t) {
118
127
  export function isScalar(t) {
119
128
  return t.kind === "int" || t.kind === "bool" || t.kind === "pubkey" || t.kind === "enum";
120
129
  }
121
- /** Stable C identifier suffix for a scalar, used in TS_Opt_<suffix>. */
122
130
  export function optionKey(t) {
131
+ if (t.kind === "array")
132
+ return `a${t.len}_${optionKey(t.elem)}`;
123
133
  return t.kind === "struct" ? `s_${t.name}` : scalarKey(t);
124
134
  }
125
135
  export function scalarKey(t) {
package/dist/testing.js CHANGED
@@ -266,6 +266,14 @@ export function programHarness(svm, programId, idl) {
266
266
  const at = s.path.includes(".") ? undefined : addressOf(s.path);
267
267
  return at && new Uint8Array(enc.encode(at));
268
268
  }
269
+ // `opt.unwrap_or(7)`: an Option argument, or 7 when it is None (Anchor's text for such a seed).
270
+ const fallback = /^(.*)\.unwrap_or\((-?\d+)\)$/.exec(s.path);
271
+ if (fallback) {
272
+ const arg = def.args.find((x) => x.name === fallback[1]);
273
+ const inner = arg && typeof arg.type === "object" && "option" in arg.type ? arg.type.option : undefined;
274
+ const value = arg && (argsIn[arg.name] ?? argsIn[camel(arg.name)]);
275
+ return inner === undefined ? undefined : argSeed(value === undefined || value === null ? BigInt(fallback[2]) : value, inner);
276
+ }
269
277
  const arg = def.args.find((x) => x.name === s.path);
270
278
  const value = arg && (argsIn[arg.name] ?? argsIn[camel(arg.name)]);
271
279
  return arg && (argSeed(value, arg.type) ?? enumSeed(value, arg.type));
@@ -81,7 +81,8 @@ export const TYPESOL_ERRORS = {
81
81
  const INTS = { u8: 8, u16: 16, u32: 32, u64: 64, u128: 128, i8: 8, i16: 16, i32: 32, i64: 64, i128: 128 };
82
82
  const FLOATS = { f32: 32, f64: 64 };
83
83
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
84
- const PATH = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/;
84
+ /** A seed path: `arg`, `arg.field…`, or `opt.unwrap_or(N)` (Anchor's text for an Option argument with a default). */
85
+ const PATH = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*(\.unwrap_or\(-?\d+\))?$/;
85
86
  const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
86
87
  const JS_RESERVED = new Set(("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in " +
87
88
  "instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package " +
@@ -1112,6 +1113,14 @@ function generate(idl, opts) {
1112
1113
  if (s.kind === "const")
1113
1114
  return bytes(s.value);
1114
1115
  if (s.kind === "arg") {
1116
+ // `opt.unwrap_or(7)`: an Option argument, or 7 when it is None.
1117
+ const fallback = /^(.*)\.unwrap_or\((-?\d+)\)$/.exec(s.path);
1118
+ if (fallback) {
1119
+ const t = argType.get(fallback[1]);
1120
+ if (t === undefined || typeof t !== "object" || t.option === undefined || !(typeof t.option === "string" && t.option in INTS))
1121
+ return { why: `the seed ${s.path} is not an Option integer argument with a default` };
1122
+ return `${codec(t.option)}.encode(${refs.arg(camel(fallback[1]))} ?? ${fallback[2]})`;
1123
+ }
1115
1124
  // `params.id`: a field (of a field…) of a struct argument.
1116
1125
  const [head, ...rest] = s.path.split(".");
1117
1126
  let t = argType.get(head);
@@ -25,6 +25,12 @@ interface IdlTypeDef {
25
25
  }[];
26
26
  };
27
27
  generics?: unknown[];
28
+ serialization?: string;
29
+ repr?: {
30
+ kind: string;
31
+ packed?: boolean;
32
+ align?: number;
33
+ };
28
34
  }
29
35
  interface IdlAccountItem {
30
36
  name: string;
@@ -9,7 +9,7 @@
9
9
  * data enum, a COption) it says so in a note and a comment.
10
10
  */
11
11
  import { createHash } from "node:crypto";
12
- import { cNameProblem } from "../compiler/analyze.js";
12
+ import { ACCOUNT_MEMBERS, cNameProblem, fieldIdlName } from "../compiler/analyze.js";
13
13
  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
14
  const camel = (s) => s.replace(/[_-]+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase()).replace(/^[A-Z]/, (c) => c.toLowerCase());
15
15
  const pascal = (s) => camel(s).replace(/^[a-z]/, (c) => c.toUpperCase());
@@ -130,6 +130,9 @@ export function generatePort(idl) {
130
130
  }
131
131
  if (t === "bytes")
132
132
  return tsType({ vec: "u8" }, where, at, last);
133
+ // An f64 is held as its bits (no float arithmetic): f64FromBits / f64Bits.
134
+ if (t === "f64")
135
+ return use("f64");
133
136
  notes.push(`${at}: IDL type "${t}" has no TypeSOL equivalent; left as u64`);
134
137
  return `${use("u64")} /* TODO: ${t} */`;
135
138
  }
@@ -145,7 +148,8 @@ export function generatePort(idl) {
145
148
  notes.push(`${at}: a COption (4-byte tag in Anchor); TypeSOL's Option has a 1-byte tag, so this layout differs.`);
146
149
  if (t.option || t.coption) {
147
150
  const inner = tsType((t.option ?? t.coption), where === "variant" ? "variant" : where, at);
148
- if (fixed(where))
151
+ // A struct argument holding Options is Borsh on the wire (as Anchor sends it); account data and variants are fixed.
152
+ if (fixed(where) && where !== "struct")
149
153
  notes.push(`${at}: an Option in ${describe(where)} is fixed-size in TypeSOL (1 + size of T), Borsh (1, or 1 + size) in Anchor: the layout differs.`);
150
154
  return `${use("Option")}<${inner}>`;
151
155
  }
@@ -182,13 +186,26 @@ export function generatePort(idl) {
182
186
  return `${use("u64")} /* TODO */`;
183
187
  };
184
188
  /** A String, Vec or Option at a struct's top level: Borsh-sized in Anchor. */
189
+ const nestedOption = (t, seen = new Set()) => {
190
+ if (typeof t === "string")
191
+ return false;
192
+ if (t.option || t.coption)
193
+ return true;
194
+ if (t.array)
195
+ return nestedOption(t.array[0], seen);
196
+ const name = t.defined ? (typeof t.defined === "string" ? t.defined : t.defined.name) : undefined;
197
+ if (!name || seen.has(name))
198
+ return false;
199
+ const def = (idl.types ?? []).find((d) => d.name === name);
200
+ return !!def && def.type.kind === "struct" && (def.type.fields ?? []).some((f) => nestedOption(f.type, new Set([...seen, name])));
201
+ };
185
202
  const borshOnly = (t) => t === "string" || t === "bytes" || (typeof t === "object" && (!!t.vec || !!t.option));
186
203
  /** A field's type in a `@layout borsh` struct, or undefined when that layout cannot hold it. Notes the capacities. */
187
204
  const borshField = (t, at) => {
188
205
  const quiet = at === "";
189
206
  const fixedOk = (u) => {
190
207
  if (typeof u === "string")
191
- return INTS.has(u) || u === "bool" || u === "pubkey" || u === "publicKey";
208
+ return INTS.has(u) || u === "bool" || u === "pubkey" || u === "publicKey" || u === "f64";
192
209
  if (u.array)
193
210
  return Number.isInteger(Number(u.array[1])) && fixedOk(u.array[0]);
194
211
  if (u.defined) {
@@ -226,17 +243,37 @@ export function generatePort(idl) {
226
243
  notes.push(`${at}: set the Vec's capacity to Anchor's #[max_len] (Borsh bytes are kept: @layout borsh)`);
227
244
  return `${use("FixedVec")}<${elem}, 8> /* TODO: #[max_len] */`;
228
245
  }
246
+ // A struct with Options inside (Marginfi's event header): Borsh at every depth, its own fields fixed or Options.
247
+ const nestedOk = (u) => {
248
+ if (typeof u !== "object" || !u.defined)
249
+ return false;
250
+ const d = defs.get(definedName(u.defined));
251
+ if (!d || d.type.kind !== "struct")
252
+ return false;
253
+ return (d.type.fields ?? []).every((f) => fixedOk(f.type) || nestedOk(f.type) || (typeof f.type === "object" && !!f.type.option && (fixedOk(f.type.option) || nestedOk(f.type.option))));
254
+ };
229
255
  if (typeof t === "object" && t.option) {
230
- if (!fixedOk(t.option))
256
+ if (!fixedOk(t.option) && !nestedOk(t.option))
231
257
  return undefined;
232
- return quiet ? "x" : `${use("Option")}<${tsType(t.option, "account", at)}>`;
258
+ return quiet ? "x" : `${use("Option")}<${tsType(t.option, "event", at)}>`;
233
259
  }
260
+ if (nestedOk(t))
261
+ return quiet ? "x" : tsType(t, "event", at);
234
262
  if (!fixedOk(t))
235
263
  return undefined;
236
264
  return quiet ? "x" : tsType(t, "account", at);
237
265
  };
238
266
  const esc = (s) => s.replace(/\*\//g, "* /");
239
- const docs = (lines, pad = "") => (lines?.length ? `${pad}/** ${esc(lines.join(" "))} */\n` : "");
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
+ : "";
272
+ // What an Anchor IDL says of a zero-copy type (repr, serialization), kept as tags so the port's IDL says it too.
273
+ const metaTags = (def) => [
274
+ ...(def.serialization ? [`@serialization ${def.serialization}`] : []),
275
+ ...(def.repr ? [`@repr ${def.repr.kind}${def.repr.packed ? " packed" : ""}${def.repr.align ? ` align ${def.repr.align}` : ""}`] : []),
276
+ ];
240
277
  const out = [];
241
278
  // Constants: integer literals and strings; expressions are left to port by hand.
242
279
  for (const c of idl.constants ?? []) {
@@ -266,26 +303,34 @@ export function generatePort(idl) {
266
303
  // An account struct, or one passed / returned whole, with a String, Vec or Option of its own: `@layout borsh`
267
304
  // keeps Anchor's bytes.
268
305
  const borshable = accountNames.has(def.name) || (whole.has(def.name) && !nested.has(def.name) && !eventNames.has(def.name));
269
- const borsh = borshable && !isTuple(fields) && fields.some((f) => borshOnly(f.type)) && fields.every((f) => borshField(f.type, "") !== undefined);
306
+ const borsh = (borshable && !isTuple(fields) && fields.some((f) => borshOnly(f.type)) && fields.every((f) => borshField(f.type, "") !== undefined)) ||
307
+ // An event holding a struct with Options (Marginfi's header { signer: Option<Pubkey> }): Borsh at every depth.
308
+ (eventNames.has(def.name) && !isTuple(fields) && fields.some((f) => nestedOption(f.type)));
270
309
  const tag = accountNames.has(def.name) ? " (account)" : eventNames.has(def.name) ? ` (event: emit<${typeName(def.name)}>({ … }))` : "";
271
310
  const doc = def.docs?.length ? esc(def.docs.join(" ")) : `${def.name}${tag}`;
272
- out.push(borsh ? `/**\n * ${doc}\n * @layout borsh\n */` : `/** ${doc} */`);
311
+ const typeTags = [...(borsh ? ["@layout borsh"] : []), ...metaTags(def)];
312
+ out.push(typeTags.length ? `/**\n * ${doc}\n${typeTags.map((t) => ` * ${t}\n`).join("")} */` : `/** ${doc} */`);
273
313
  out.push(`export interface ${typeName(def.name)} {`);
274
314
  const seen = new Set();
275
315
  fields.forEach((f, i) => {
276
316
  let n = ident(f.name, true);
317
+ // An account member's name (key, lamports) is held as key_, which the IDL still calls key.
318
+ if (ACCOUNT_MEMBERS.has(n))
319
+ n = `${n}_`;
277
320
  while (seen.has(n))
278
321
  n = `${n}2`;
279
322
  seen.add(n);
280
323
  const ty = borsh ? borshField(f.type, `${def.name}.${f.name}`) : tsType(f.type, where, `${def.name}.${f.name}`, i === fields.length - 1);
281
- out.push(`${docs(f.docs, " ")} ${n}: ${ty};`);
324
+ // The IDL's own name where TypeSOL's would differ (_pad0, integration_acc_1).
325
+ const tags = fieldIdlName(n) === f.name ? [] : [`@idlName ${f.name}`];
326
+ out.push(`${docs(f.docs, " ", tags)} ${n}: ${ty};`);
282
327
  });
283
328
  out.push("}", "");
284
329
  }
285
330
  else {
286
331
  const variants = def.type.variants ?? [];
287
332
  if (variants.every((v) => !v.fields?.length)) {
288
- out.push(`${docs(def.docs)}export enum ${typeName(def.name)} {`, ...variants.map((v) => ` ${ident(v.name, true).replace(/^[a-z]/, (c) => c.toUpperCase())},`), "}", "");
333
+ out.push(`${docs(def.docs, "", metaTags(def))}export enum ${typeName(def.name)} {`, ...variants.map((v) => ` ${ident(v.name, true).replace(/^[a-z]/, (c) => c.toUpperCase())},`), "}", "");
289
334
  }
290
335
  else {
291
336
  // Strings in variants are fine in arguments and events (Borsh); account data needs fixed-size variants.
@@ -296,17 +341,17 @@ export function generatePort(idl) {
296
341
  : `f${i}: ${tsType(f, vw, `${def.name}.${v.name}`)}`);
297
342
  return `{ kind: "${pascal(v.name)}"${fs.map((x) => `; ${x}`).join("")} }`;
298
343
  });
299
- out.push(`${docs(def.docs)}export type ${typeName(def.name)} =\n | ${parts.join("\n | ")};`, "");
344
+ out.push(`${docs(def.docs, "", metaTags(def))}export type ${typeName(def.name)} =\n | ${parts.join("\n | ")};`, "");
300
345
  }
301
346
  }
302
347
  }
303
- // Errors: TypeSOL numbers them 6000 + their index. NotPorted, last, marks the instructions still to write, so the
304
- // codes of the program's own errors do not move.
305
- const errors = idl.errors ?? [];
348
+ // Errors: TypeSOL numbers them from 6000 in order; `/** @code N */` keeps an IDL code that skips ahead. NotPorted,
349
+ // last, marks the instructions still to write, so the codes of the program's own errors do not move.
350
+ const errors = [...(idl.errors ?? [])].sort((a, b) => a.code - b.code);
306
351
  const program = typeName(pascal(idl.metadata?.name ?? "program"));
307
352
  const errorEnum = `${program}Error`;
308
- if (!errors.every((e, i) => e.code === 6000 + i))
309
- notes.push(`errors: TypeSOL numbers an error enum from 6000 in order; the IDL's codes (${errors.map((e) => e.code).join(", ")}) differ, so clients see other codes`);
353
+ if (errors.some((e, i) => e.code < 6000 || (i > 0 && e.code === errors[i - 1].code)))
354
+ 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`);
310
355
  const memberNames = new Set();
311
356
  const member = (name) => {
312
357
  // RequireFailedN is TypeSOL's own name for require("message") errors; it is reserved in source.
@@ -316,7 +361,13 @@ export function generatePort(idl) {
316
361
  memberNames.add(n);
317
362
  return n;
318
363
  };
319
- const errorLines = errors.map((e) => ` ${member(e.name)} = ${JSON.stringify(e.msg ?? e.name)},`);
364
+ let nextCode = 6000;
365
+ const errorLines = errors.flatMap((e) => {
366
+ const skip = e.code > nextCode ? [` /** @code ${e.code} */`] : [];
367
+ nextCode = Math.max(nextCode, e.code) + 1;
368
+ // An error without a message has none in TypeSOL's IDL either.
369
+ return [...skip, ` ${member(e.name)} = ${JSON.stringify(e.msg ?? "")},`];
370
+ });
320
371
  const notPorted = member("NotPorted");
321
372
  out.push(`export enum ${errorEnum} {`, ...errorLines, ` ${notPorted} = "This instruction is not ported yet",`, "}", "");
322
373
  // Accounts of an instruction, nested groups flattened.
@@ -31,9 +31,10 @@ program.so + program.build.json (manifest: versions, sha256 of sources and binar
31
31
  | `lib/` | `typesol.d.ts`, the language surface programs typecheck against |
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
- | `test/` | The test suite, by subject: `language/`, `security/`, `examples/`, `integrations/` (token, Metaplex, oracle and other CPIs), `client/`, `cli/`, `porting/`, `verification/` (differential and fuzz tests). Shared: `harness.ts` and the `*-helpers.ts`, `fixtures/` (programs the tests compile), `ports/` (TypeSOL rewrites of solana-developers/program-examples), `golden/` (pinned generated C and clients), `programs/` (third-party program binaries, see its SOURCES.md), `anchor-twins/` (below) |
35
- | `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/benchmarks](https://github.com/typesol/benchmarks) |
36
- | `scripts/` | `smoke.ts` and `localnet.sh` (a local validator run), `fetch-programs.sh` (third-party binaries), `readme-bench.ts` (the README numbers) |
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/` (Raydium 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
+ | `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
+ | `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) |
37
38
  | `docs/` | User and contributor documentation (also published on typesol.com) |
38
39
  | `assets/` | The CLI's logo and the README images (`readme/`, generated) |
39
40
 
@@ -101,7 +102,7 @@ representation in between. We reviewed this on 2026-10-30 and kept it that way f
101
102
  named in the source, see `alias.ts`), a second backend (SBF without clang), and optimizations clang cannot see
102
103
  because they depend on account semantics (dropping a repeated check, packing a `@layout borsh` account only where
103
104
  it changed).
104
- - **What it would cost now:** rewriting most of the compiler's 12,000 lines, and losing the property every release
105
+ - **What it would cost now:** rewriting most of the compiler's 14,000 lines, and losing the property every release
105
106
  relies on: programs that do not use a change compile to the same binaries. Audit scope and differential results
106
107
  would start over.
107
108
  - **What we have instead:** the layers above, each owning one concern; `Ref` / `Value` as the typed place and value