@typesol/cli 0.37.0 → 0.39.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 (52) hide show
  1. package/CHANGELOG.md +352 -1
  2. package/README.md +31 -14
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +7 -6
  5. package/dist/compiler/analyze.js +350 -38
  6. package/dist/compiler/emit/alias.js +3 -2
  7. package/dist/compiler/emit/base.d.ts +5 -0
  8. package/dist/compiler/emit/base.js +2 -0
  9. package/dist/compiler/emit/borsh.js +63 -2
  10. package/dist/compiler/emit/calls.d.ts +9 -1
  11. package/dist/compiler/emit/calls.js +147 -18
  12. package/dist/compiler/emit/cpi-core.js +21 -6
  13. package/dist/compiler/emit/cpi.js +81 -27
  14. package/dist/compiler/emit/create.d.ts +7 -0
  15. package/dist/compiler/emit/create.js +27 -0
  16. package/dist/compiler/emit/expressions.js +7 -4
  17. package/dist/compiler/emit/function.d.ts +7 -0
  18. package/dist/compiler/emit/function.js +168 -30
  19. package/dist/compiler/emit/program.js +15 -2
  20. package/dist/compiler/emit/shared.d.ts +5 -5
  21. package/dist/compiler/emit/shared.js +5 -0
  22. package/dist/compiler/emit/statements.d.ts +8 -0
  23. package/dist/compiler/emit/statements.js +93 -6
  24. package/dist/compiler/emit/storage.d.ts +10 -1
  25. package/dist/compiler/emit/storage.js +50 -11
  26. package/dist/compiler/idl.d.ts +2 -2
  27. package/dist/compiler/idl.js +48 -13
  28. package/dist/compiler/model.d.ts +47 -10
  29. package/dist/compiler/model.js +14 -4
  30. package/dist/testing.js +8 -0
  31. package/dist/tools/clientgen.js +10 -1
  32. package/dist/tools/portgen.d.ts +6 -0
  33. package/dist/tools/portgen.js +68 -17
  34. package/docs/architecture.md +5 -4
  35. package/docs/audit.md +31 -19
  36. package/docs/case-study-escrow.md +5 -5
  37. package/docs/case-study-jito-mev.md +171 -0
  38. package/docs/case-study-marginfi.md +797 -0
  39. package/docs/case-study-multisig.md +3 -3
  40. package/docs/case-study-raydium-clmm.md +151 -101
  41. package/docs/case-study-raydium-cp-swap.md +3 -3
  42. package/docs/cli.md +5 -5
  43. package/docs/client.md +1 -1
  44. package/docs/errors.md +15 -4
  45. package/docs/language.md +39 -26
  46. package/docs/migrate-from-anchor.md +4 -1
  47. package/docs/runtime.md +1 -1
  48. package/docs/security-model.md +2 -1
  49. package/docs/testing.md +33 -1
  50. package/lib/typesol.d.ts +48 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
@@ -266,7 +266,8 @@ export class StatementEmitter extends CpiEmitter {
266
266
  void place;
267
267
  const ci = this.tmp("of_i");
268
268
  const label = this.tmp("ts_continue_");
269
- this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true }, (element) => {
269
+ const release = this.iterationClaims(stmt.statement);
270
+ this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true, atNext: release }, (element) => {
270
271
  // The element's declaration: the source's own name (so aliasing checks find its uses) bound to the element.
271
272
  const decl = f.createVariableDeclaration(d.name, undefined, undefined, element);
272
273
  ts.setTextRange(decl, d);
@@ -391,6 +392,7 @@ export class StatementEmitter extends CpiEmitter {
391
392
  body(element, idx);
392
393
  if (next && (names.alwaysNext || counters.length))
393
394
  this.line(`${next}:;`);
395
+ names.atNext?.();
394
396
  this.line(`${ci}++;`);
395
397
  });
396
398
  this.line(`}`);
@@ -509,12 +511,14 @@ export class StatementEmitter extends CpiEmitter {
509
511
  const c = this.expect(this.expr(cond, BOOL), BOOL, cond);
510
512
  this.line(`if (!${c.c}) break;`);
511
513
  }
514
+ const release = this.iterationClaims(body);
512
515
  this.loops.push(label);
513
516
  this.line(`{`);
514
517
  this.block(() => this.body(body));
515
518
  this.line(`}`);
516
519
  this.loops.pop();
517
520
  this.line(`${label}:;`);
521
+ release();
518
522
  if (step)
519
523
  this.expressionStatement(step, false);
520
524
  });
@@ -840,17 +844,93 @@ export class StatementEmitter extends CpiEmitter {
840
844
  const label = this.tmp("ts_continue_");
841
845
  this.line(`while (1) {`);
842
846
  this.block(() => {
847
+ const release = this.iterationClaims(stmt.statement);
843
848
  this.loops.push(label);
844
849
  this.line(`{`);
845
850
  this.block(() => this.body(stmt.statement));
846
851
  this.line(`}`);
847
852
  this.loops.pop();
848
853
  this.line(`${label}:;`);
854
+ release();
849
855
  const c = this.expect(this.expr(stmt.expression, BOOL), BOOL, stmt.expression);
850
856
  this.line(`if (!${c.c}) break;`);
851
857
  });
852
858
  this.line(`}`);
853
859
  }
860
+ /**
861
+ * The loadAccountMut calls of a loop body whose views end with the iteration: `const v = loadAccountMut<T>(…)` in the
862
+ * body (not in a loop nested in it, which handles its own), with `v` never assigned or copied to a name, returned, put in
863
+ * an object, or used in a function written in the body (other than a const closure of the body that stays in it). Their claims are recorded (declared here) and dropped at each iteration's end, so a
864
+ * later iteration may load the same account again: the earlier view is out of scope by then. Returns the release.
865
+ */
866
+ iterationClaims(body) {
867
+ const sites = [];
868
+ const isLoop = (n) => ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isForInStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n);
869
+ const isFunction = (n) => ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n);
870
+ // A function written in the body may use the view when it is a const of the body that does not escape either (a
871
+ // closure TypeSOL expands where it is called, within the iteration).
872
+ const localFunction = (n, seen) => {
873
+ const d = n.parent;
874
+ if (!d || !ts.isVariableDeclaration(d) || d.initializer !== n || !ts.isIdentifier(d.name))
875
+ return false;
876
+ const list = d.parent;
877
+ if (!ts.isVariableDeclarationList(list) || !(list.flags & ts.NodeFlags.Const))
878
+ return false;
879
+ return !seen.has(d.name.text) && !escapes(d.name.text, new Set([...seen, d.name.text]));
880
+ };
881
+ const escapes = (name, seen = new Set([name])) => {
882
+ let found = false;
883
+ const scan = (n, inFunction) => {
884
+ if (found)
885
+ return;
886
+ if (ts.isIdentifier(n) && n.text === name) {
887
+ const p = n.parent;
888
+ if (inFunction)
889
+ found = true;
890
+ else if (p && ts.isBinaryExpression(p) && p.right === n && p.operatorToken.kind === ts.SyntaxKind.EqualsToken)
891
+ found = true;
892
+ else if (p && ts.isReturnStatement(p))
893
+ found = true;
894
+ else if (p && ts.isVariableDeclaration(p) && p.initializer === n)
895
+ found = true;
896
+ else if (p && (ts.isShorthandPropertyAssignment(p) || (ts.isPropertyAssignment(p) && p.initializer === n)))
897
+ found = true;
898
+ }
899
+ ts.forEachChild(n, (c) => scan(c, inFunction || (isFunction(n) && !localFunction(n, seen))));
900
+ };
901
+ scan(body, false);
902
+ return found;
903
+ };
904
+ const visit = (n) => {
905
+ if (n !== body && (isLoop(n) || isFunction(n)))
906
+ return;
907
+ if (ts.isVariableDeclarationList(n) && n.flags & ts.NodeFlags.Const)
908
+ for (const d of n.declarations) {
909
+ let init = d.initializer;
910
+ while (init && ts.isParenthesizedExpression(init))
911
+ init = init.expression;
912
+ if (ts.isIdentifier(d.name) &&
913
+ init &&
914
+ ts.isCallExpression(init) &&
915
+ ts.isIdentifier(init.expression) &&
916
+ init.expression.text === "loadAccountMut" &&
917
+ !escapes(d.name.text))
918
+ sites.push(init);
919
+ }
920
+ ts.forEachChild(n, visit);
921
+ };
922
+ visit(body);
923
+ const slots = sites.map((call) => {
924
+ const slot = this.tmp("claim");
925
+ this.line(`uint64_t ${slot} = (uint64_t)-1;`);
926
+ this.claimSlots.set(call, slot);
927
+ return slot;
928
+ });
929
+ return () => {
930
+ for (const slot of slots)
931
+ this.line(`ts_release_mut(params, &${slot});`);
932
+ };
933
+ }
854
934
  body(stmt) {
855
935
  if (ts.isBlock(stmt))
856
936
  stmt.statements.forEach((s) => this.reporter.guard(() => this.statement(s)));
@@ -1007,9 +1087,11 @@ export class StatementEmitter extends CpiEmitter {
1007
1087
  if (structType.size === undefined || structType.vec)
1008
1088
  this.fail(d.type, `${structType.name} has variable-size fields and cannot be a local`);
1009
1089
  this.line(`TSS_${structType.name} ${c}__v;`);
1010
- this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init);
1090
+ this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
1011
1091
  this.line(`TSS_${structType.name} *${c} = &${c}__v;`);
1012
- this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
1092
+ this.scopes
1093
+ .at(-1)
1094
+ .set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
1013
1095
  continue;
1014
1096
  }
1015
1097
  // Data enums: `const a: Action = { kind: "X", ... }` builds a local; `const a = acct.action` aliases storage.
@@ -1046,12 +1128,15 @@ export class StatementEmitter extends CpiEmitter {
1046
1128
  if (mutable)
1047
1129
  this.fail(d, "bind struct references with const");
1048
1130
  this.line(`TSS_${target.struct} *${c} = ${target.ptr};`);
1131
+ // A struct a helper returned lives in a local this function owns, not in account data.
1132
+ const owned = ts.isCallExpression(init) && !!this.helperOf(init);
1049
1133
  this.scopes.at(-1).set(name, {
1050
1134
  c,
1051
1135
  type: { kind: "structRef", struct: target.struct, writable: target.writable },
1052
1136
  mutable: false,
1053
- paths: this.pathsOf(init),
1137
+ paths: owned ? [`@${c}`] : this.pathsOf(init),
1054
1138
  decl: d,
1139
+ ...(owned ? { owned } : {}),
1055
1140
  });
1056
1141
  continue;
1057
1142
  }
@@ -1069,7 +1154,7 @@ export class StatementEmitter extends CpiEmitter {
1069
1154
  if (type.kind === "remaining") {
1070
1155
  if (mutable)
1071
1156
  this.fail(d, "bind remainingAccounts() with const");
1072
- this.scopes.at(-1).set(name, { c: "", type, mutable: false });
1157
+ this.scopes.at(-1).set(name, { c: v.c, type, mutable: false });
1073
1158
  continue;
1074
1159
  }
1075
1160
  if ((type.kind === "account" || type.kind === "structRef") && mutable)
@@ -1078,7 +1163,9 @@ export class StatementEmitter extends CpiEmitter {
1078
1163
  this.line(`SolPubkey ${c} = *(${v.c});`);
1079
1164
  else
1080
1165
  this.line(`${valueC(type)}${type.kind === "account" ? "" : " "}${c} = ${this.ownedString(v).c};`);
1081
- this.scopes.at(-1).set(name, { c, type, mutable });
1166
+ // A struct a helper returned lives in a local this function owns, not in account data.
1167
+ const owned = type.kind === "structRef" && ts.isCallExpression(init) && !!this.helperOf(init);
1168
+ this.scopes.at(-1).set(name, { c, type, mutable, ...(owned ? { paths: [`@${c}`], owned } : {}) });
1082
1169
  }
1083
1170
  }
1084
1171
  /**
@@ -33,6 +33,11 @@ export declare abstract class StorageEmitter extends AliasEmitter {
33
33
  };
34
34
  /** Resolve an expression to a storage location, if it names one. */
35
35
  protected ref(node: ts.Expression): Ref | undefined;
36
+ /**
37
+ * The value of an Option<FixedArray> / Option<Struct> place TypeScript has narrowed to Some: the place inside it.
38
+ * An empty option aborts (5108), the backstop of the narrowing.
39
+ */
40
+ protected someValue(r: Ref): Ref;
36
41
  /** An SPL COption<Pubkey> (u32 tag + 32 bytes) at `at`, as an Option<Pubkey> value. */
37
42
  protected coptionKey(at: string): Value;
38
43
  /** Why a place cannot be written, naming what to change. */
@@ -55,7 +60,11 @@ export declare abstract class StorageEmitter extends AliasEmitter {
55
60
  */
56
61
  /** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
57
62
  private wholeAccount;
58
- protected writeAggregate(target: Ref, valueNode: ts.Expression): void;
63
+ /**
64
+ * Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
65
+ * expression can read yet, so a literal is built in it directly rather than in a temporary first.
66
+ */
67
+ protected writeAggregate(target: Ref, valueNode: ts.Expression, fresh?: boolean): void;
59
68
  /** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
60
69
  protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
61
70
  /** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
@@ -174,6 +174,9 @@ export class StorageEmitter extends AliasEmitter {
174
174
  return { lv: l.c, type: l.type, writable: !l.readonly };
175
175
  if (l && l.type.kind === "vec")
176
176
  return this.withFixedVec({ lv: l.c, type: l.type, writable: true });
177
+ // An Option<struct> instruction argument: read like an Option<struct> field.
178
+ if (l && l.type.kind === "optionArg")
179
+ return { lv: l.c, type: l.type.option, writable: false };
177
180
  // A struct loaded from a remaining account.
178
181
  if (l && l.type.kind === "structRef")
179
182
  return { lv: `(*${l.c})`, type: { kind: "struct", name: l.type.struct }, writable: l.type.writable };
@@ -309,7 +312,9 @@ export class StorageEmitter extends AliasEmitter {
309
312
  const idx = this.index(node.arguments[0], `(uint64_t)${l.c}.len`);
310
313
  return { lv: `((${fieldC(l.type.elem)} *)${l.c}.ptr)[${idx}]`, type: l.type.elem, writable: false };
311
314
  }
312
- const base = this.ref(node.expression.expression);
315
+ let base = this.ref(node.expression.expression);
316
+ if (base && base.type.kind === "option" && base.type.inner.kind === "array")
317
+ base = this.someValue(base);
313
318
  if (base && (base.type.kind === "array" || base.type.kind === "vec")) {
314
319
  if (node.arguments.length !== 1)
315
320
  this.fail(node, "get(index) takes one argument");
@@ -320,6 +325,15 @@ export class StorageEmitter extends AliasEmitter {
320
325
  }
321
326
  return undefined;
322
327
  }
328
+ /**
329
+ * The value of an Option<FixedArray> / Option<Struct> place TypeScript has narrowed to Some: the place inside it.
330
+ * An empty option aborts (5108), the backstop of the narrowing.
331
+ */
332
+ someValue(r) {
333
+ const t = r.type;
334
+ this.line(`if (!${r.lv}.some) TS_FAIL(TS_ERR_UNWRAP, "TypeSOL: option is empty");`);
335
+ return this.withFixedVec({ ...r, lv: `${r.lv}.v`, type: t.inner, path: undefined, vec: undefined });
336
+ }
323
337
  /** An SPL COption<Pubkey> (u32 tag + 32 bytes) at `at`, as an Option<Pubkey> value. */
324
338
  coptionKey(at) {
325
339
  const opt = { kind: "option", inner: PUBKEY };
@@ -453,9 +467,25 @@ export class StorageEmitter extends AliasEmitter {
453
467
  this.assertUsable(a, node);
454
468
  return { lv: `(*d_${a.name})`, type: { kind: "struct", name: a.kind.struct.name }, writable: false };
455
469
  }
456
- writeAggregate(target, valueNode) {
470
+ /**
471
+ * Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
472
+ * expression can read yet, so a literal is built in it directly rather than in a temporary first.
473
+ */
474
+ writeAggregate(target, valueNode, fresh = false) {
457
475
  if (ts.isParenthesizedExpression(valueNode))
458
- return this.writeAggregate(target, valueNode.expression);
476
+ return this.writeAggregate(target, valueNode.expression, fresh);
477
+ // `fixedArray<T, N>(fill)` as a field's value: filled in place.
478
+ if (target.type.kind === "array" && ts.isCallExpression(valueNode) && this.exportName(valueNode.expression) === "fixedArray") {
479
+ const [elemNode, lenNode] = valueNode.typeArguments ?? [];
480
+ const elem = elemNode && resolveScalarType(elemNode, this.scope);
481
+ const len = lenNode && ts.isLiteralTypeNode(lenNode) && ts.isNumericLiteral(lenNode.literal) ? Number(lenNode.literal.text) : NaN;
482
+ if (!elem || !sameType(elem, target.type.elem) || len !== target.type.len || valueNode.arguments.length !== 1)
483
+ this.fail(valueNode, `expected fixedArray<${typeName(target.type.elem)}, ${target.type.len}>(fill)`);
484
+ const fill = this.expect(this.expr(valueNode.arguments[0], elem), elem, valueNode.arguments[0]);
485
+ const i = this.tmp("i");
486
+ this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) ${this.writeStorage({ lv: `${target.lv}[${i}]`, type: elem, writable: true }, fill.c)};`);
487
+ return;
488
+ }
459
489
  if (target.type.kind === "option" && target.type.inner.kind === "struct") {
460
490
  if (valueNode.kind === ts.SyntaxKind.NullKeyword) {
461
491
  this.line(`${target.lv}.some = 0;`);
@@ -568,23 +598,26 @@ export class StorageEmitter extends AliasEmitter {
568
598
  for (const k of given.keys())
569
599
  if (!s.fields.some((f) => f.name === k))
570
600
  this.fail(valueNode, `${s.name} has no field "${k}"`);
571
- // Build in a temporary so `p = { x: p.y, y: p.x }` reads the old values.
572
- const tmp = this.tmp("st");
573
- this.line(`TSS_${s.name} ${tmp};`);
601
+ // Build in a temporary so `p = { x: p.y, y: p.x }` reads the old values (a fresh target has none to read).
602
+ const tmp = fresh ? undefined : this.tmp("st");
603
+ if (tmp)
604
+ this.line(`TSS_${s.name} ${tmp};`);
605
+ const into = tmp ?? target.lv;
574
606
  for (const f of s.fields)
575
607
  if (!given.has(f.name))
576
608
  this.fail(valueNode, `missing field "${f.name}" of ${s.name}`);
577
609
  // Fields are evaluated in source order, as in JS, straight into the temporary.
578
610
  for (const [name, e] of given) {
579
611
  const f = s.fields.find((x) => x.name === name);
580
- const sub = { lv: `${tmp}.${f.name}`, type: f.type, writable: true };
612
+ const sub = { lv: `${into}.${f.name}`, type: f.type, writable: true };
581
613
  const vt = this.storageValueType(f.type);
582
614
  if (vt)
583
615
  this.line(this.writeStorage(sub, this.expect(this.expr(e, vt), vt, e).c) + ";");
584
616
  else
585
- this.writeAggregate(sub, e);
617
+ this.writeAggregate(sub, e, true);
586
618
  }
587
- this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
619
+ if (tmp)
620
+ this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
588
621
  return;
589
622
  }
590
623
  if (ts.isConditionalExpression(valueNode)) {
@@ -632,7 +665,13 @@ export class StorageEmitter extends AliasEmitter {
632
665
  }
633
666
  if (heap)
634
667
  this.fail(valueNode, `expected a ${typeName(target.type)}: a Vec argument or another list of the same elements`);
635
- const src = this.ref(valueNode) ?? this.wholeAccount(valueNode);
668
+ let src = this.ref(valueNode) ?? this.wholeAccount(valueNode);
669
+ // A narrowed Option<FixedArray> / Option<Struct> place (`x.tiers !== null` before it): its value.
670
+ if (src &&
671
+ src.type.kind === "option" &&
672
+ (src.type.inner.kind === "array" || src.type.inner.kind === "struct") &&
673
+ sameType(src.type.inner, target.type))
674
+ src = this.someValue(src);
636
675
  if (!src || !sameType(src.type, target.type))
637
676
  this.fail(valueNode, `expected a ${typeName(target.type)}: an object literal, another ${typeName(target.type)}${target.type.kind === "vec" && target.type.cap !== undefined ? " or a Vec of the same elements" : ""}`);
638
677
  // Same-typed places are either distinct or identical (`a.p = a.p`); ts_copy skips the latter.
@@ -719,7 +758,7 @@ export class StorageEmitter extends AliasEmitter {
719
758
  case "enum":
720
759
  return scalarSize(t);
721
760
  case "option":
722
- return 1 + (t.inner.kind === "struct" ? this.fieldBytes(t.inner) : scalarSize(t.inner));
761
+ return 1 + (t.inner.kind === "struct" || t.inner.kind === "array" ? this.fieldBytes(t.inner) : scalarSize(t.inner));
723
762
  case "dataEnum":
724
763
  return 1 + this.model.dataEnums.get(t.name).payload;
725
764
  case "fstring":
@@ -29,9 +29,9 @@ export declare function buildIdl(model: ProgramModel, address: string, version?:
29
29
  discriminator: number[];
30
30
  }[];
31
31
  errors: {
32
+ msg?: string | undefined;
32
33
  code: number;
33
34
  name: string;
34
- msg: string;
35
35
  }[];
36
36
  types: ({
37
37
  type: {
@@ -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 { 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:
@@ -204,31 +220,50 @@ export function buildIdl(model, address, version = "0.1.0") {
204
220
  ...docsOf(ix.node),
205
221
  discriminator: ix.discriminator,
206
222
  accounts: nestGroups(ix, (a) => accountEntry(ix, a.name, a.kind, address)),
207
- args: ix.args.map((a) => ({ name: snakeCase(a.name), ...paramDocs(a.node), type: idlType(a.type, true) })),
223
+ args: ix.args.map((a) => ({
224
+ name: argIdlName(a.name, ix.accounts.map((o) => o.name)),
225
+ ...paramDocs(a.node),
226
+ type: idlType(a.type, true),
227
+ })),
208
228
  ...(ix.returns ? { returns: idlType(ix.returns) } : {}),
209
229
  })),
210
- 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 })),
211
233
  events: structs.filter((s) => model.events.has(s.name)).map((s) => ({ name: s.name, discriminator: s.eventDiscriminator })),
212
- errors: model.errors.map((e) => ({ code: e.code, name: e.name, msg: e.msg })),
234
+ errors: model.errors.map((e) => ({ code: e.code, name: e.name, ...(e.msg ? { msg: e.msg } : {}) })),
213
235
  types: [
214
236
  ...usedStructs.map((s) => ({
215
237
  name: s.name,
216
238
  ...docsOf(s.node),
239
+ ...idlMetaFields(s.idlMeta),
217
240
  type: {
218
241
  kind: "struct",
219
- fields: s.fields.map((f) => ({
220
- 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),
221
245
  ...docsOf(s.node.members.find((m) => m.name && ts.isIdentifier(m.name) && m.name.text === f.name)),
222
- 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)),
223
253
  })),
224
254
  },
225
255
  })),
226
- ...[...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
+ })),
227
261
  // A variable enum (it holds strings) only exists in Borsh: no fixed account-data form to describe.
228
262
  ...[...model.dataEnums.values()].flatMap((e) => [
229
263
  {
230
264
  name: e.name,
231
265
  ...docsOf(e.node),
266
+ ...idlMetaFields(e.idlMeta),
232
267
  type: {
233
268
  kind: "enum",
234
269
  variants: e.variants.map((v) => v.fields.length
@@ -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));