@typesol/cli 0.38.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 +327 -2
  2. package/README.md +29 -15
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +6 -11
  5. package/dist/compiler/analyze.js +323 -31
  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 +17 -5
  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 +164 -29
  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 +1 -1
  27. package/dist/compiler/idl.js +42 -11
  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 +9 -5
  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 +44 -33
  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 +13 -5
  45. package/docs/language.md +38 -25
  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 +46 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
@@ -10,12 +10,12 @@ export const LIB_PATH = fileURLToPath(new URL("../../lib/typesol.d.ts", import.m
10
10
  /** Names a struct field may not use because account parameters already expose them. */
11
11
  const RESERVED_FIELDS = new Set(["create", "equals", "get", "set", "length"]);
12
12
  /** Members every account parameter has (`acct.key`, `acct.isSigner`, …): a struct held in an account cannot use them. */
13
- const ACCOUNT_MEMBERS = new Set(["key", "lamports", "dataLen", "isSigner", "isWritable", "pdaBump"]);
13
+ export const ACCOUNT_MEMBERS = new Set(["key", "lamports", "dataLen", "isSigner", "isWritable", "pdaBump"]);
14
14
  /** A struct used as account data: none of its fields may shadow an account member. */
15
15
  export function checkAccountMembers(s, at, reporter) {
16
16
  const clash = s.fields.find((f) => ACCOUNT_MEMBERS.has(f.name));
17
17
  if (clash)
18
- reporter.fail(at, `${s.name}.${clash.name}: "${clash.name}" is an account member (acct.${clash.name}); rename the field to hold ${s.name} in an account`);
18
+ reporter.fail(at, `${s.name}.${clash.name}: "${clash.name}" is an account member (acct.${clash.name}); rename the field to hold ${s.name} in an account (${clash.name}_ keeps the name "${snakeCase(clash.name)}" in the IDL)`);
19
19
  }
20
20
  /**
21
21
  * Struct fields and enum variants become C member names as written. C keywords and the object-like
@@ -61,6 +61,7 @@ function checkSnakeDuplicates(names, what, reporter) {
61
61
  /** Exports of the `typesol` module that are types (everything else is a function). */
62
62
  const TYPE_EXPORTS = new Set([
63
63
  ...INT_NAMES,
64
+ "f64",
64
65
  "Pubkey",
65
66
  "AccountMeta",
66
67
  "Signer",
@@ -146,6 +147,42 @@ export function snakeCase(name) {
146
147
  * argument of one name (`authority`); TypeScript cannot, so the argument is written with a trailing underscore
147
148
  * (`authority_`) and recorded without it.
148
149
  */
150
+ /** `/** @repr c *\/` (packed, align N) / `@repr rust` and `/** @serialization bytemuck *\/` on a type: see IdlMeta. */
151
+ function idlMetaOf(decl, reporter) {
152
+ const text = (name) => {
153
+ const tag = ts.getJSDocTags(decl).find((t) => t.tagName.text === name);
154
+ return tag ? { tag, words: (typeof tag.comment === "string" ? tag.comment : "").trim().split(/\s+/).filter(Boolean) } : undefined;
155
+ };
156
+ const repr = text("repr");
157
+ const serialization = text("serialization");
158
+ if (!repr && !serialization)
159
+ return undefined;
160
+ const meta = {};
161
+ if (repr) {
162
+ const [kind, ...rest] = repr.words;
163
+ if (kind !== "c" && kind !== "rust")
164
+ reporter.fail(repr.tag, "@repr is c or rust, then optionally packed and align N: @repr c align 8");
165
+ meta.repr = { kind };
166
+ for (let i = 0; i < rest.length; i++) {
167
+ if (rest[i] === "packed")
168
+ meta.repr.packed = true;
169
+ else if (rest[i] === "align" && /^\d+$/.test(rest[i + 1] ?? ""))
170
+ meta.repr.align = Number(rest[++i]);
171
+ else
172
+ reporter.fail(repr.tag, `@repr: unknown "${rest[i]}" (packed, align N)`);
173
+ }
174
+ }
175
+ if (serialization) {
176
+ if (serialization.words.length !== 1)
177
+ reporter.fail(serialization.tag, "@serialization takes one word: bytemuck, bytemuckunsafe, …");
178
+ meta.serialization = serialization.words[0];
179
+ }
180
+ return meta;
181
+ }
182
+ /** A struct field's IDL name: snake_case, and an account member's name plus "_" (`key_`) without the "_". */
183
+ export function fieldIdlName(name) {
184
+ return name.endsWith("_") && ACCOUNT_MEMBERS.has(name.slice(0, -1)) ? snakeCase(name.slice(0, -1)) : snakeCase(name);
185
+ }
149
186
  export function argIdlName(name, accountNames) {
150
187
  const base = snakeCase(name);
151
188
  if (base.length > 1 && base.endsWith("_") && !base.endsWith("__") && accountNames.some((a) => snakeCase(a) === base.slice(0, -1)))
@@ -155,18 +192,19 @@ export function argIdlName(name, accountNames) {
155
192
  /**
156
193
  * An account struct's discriminator: Anchor's sha256("account:<Name>")[..8], or the one a `/** @discriminator … *\/` tag
157
194
  * gives (a sha256 preimage such as `account:Counter`, or 0x and 8 bytes), e.g. for an old version of a struct kept under
158
- * a new name for Migrate<From, To>.
195
+ * a new name for Migrate<From, To>; 0x and 1 to 7 bytes for another program's account (`Owner<Account<T>, "…">`).
159
196
  */
160
197
  function accountDiscriminator(decl, name, reporter) {
161
198
  const tag = ts.getJSDocTags(decl).find((t) => t.tagName.text === "discriminator");
162
199
  if (!tag)
163
200
  return discriminator(`account:${name}`);
164
201
  const text = (typeof tag.comment === "string" ? tag.comment : (ts.getTextOfJSDocComment(tag.comment) ?? "")).trim();
165
- if (/^0x([0-9a-fA-F]{2}){8}$/.test(text))
202
+ // 8 bytes; another program's account may have a shorter one (Solend's reserve: its version byte).
203
+ if (/^0x([0-9a-fA-F]{2}){1,8}$/.test(text))
166
204
  return [...Buffer.from(text.slice(2), "hex")];
167
205
  if (text && !text.startsWith("0x"))
168
206
  return discriminator(text);
169
- reporter.fail(decl, "@discriminator on an account struct needs a sha256 preimage (account:<Name>) or 0x and 8 bytes");
207
+ reporter.fail(decl, "@discriminator on an account struct needs a sha256 preimage (account:<Name>) or 0x and 8 bytes (1 to 8 for another program's account)");
170
208
  }
171
209
  export function discriminator(preimage) {
172
210
  return [...createHash("sha256").update(preimage).digest().subarray(0, 8)];
@@ -376,7 +414,17 @@ export function analyze(entry, files) {
376
414
  for (const m of stmt.members) {
377
415
  if (!m.initializer || !ts.isStringLiteral(m.initializer))
378
416
  reporter.fail(m, 'error enum members need a string message: Name = "message"');
379
- const def = { code: 6000 + errors.length, name: m.name.getText(file), msg: m.initializer.text };
417
+ // Codes run on from the last one; `/** @code 6200 */` sets a member's (Anchor's `Variant = 200`), and the
418
+ // members after it continue from there.
419
+ let code = errors.length ? errors[errors.length - 1].code + 1 : 6000;
420
+ const tag = ts.getJSDocTags(m).find((t) => t.tagName.text === "code");
421
+ if (tag) {
422
+ const text = typeof tag.comment === "string" ? tag.comment.trim() : "";
423
+ if (!/^\d+$/.test(text) || Number(text) < code || Number(text) > 4_294_967_295)
424
+ reporter.fail(m, `@code must be a number from ${code} up (codes only go up, and start at 6000)`);
425
+ code = Number(text);
426
+ }
427
+ const def = { code, name: m.name.getText(file), msg: m.initializer.text };
380
428
  // Names identify errors in the IDL: they must be unique across the program.
381
429
  if (errors.some((e) => e.name === def.name))
382
430
  reporter.fail(m, `error "${def.name}" is already declared; error names are program-wide`);
@@ -397,7 +445,8 @@ export function analyze(entry, files) {
397
445
  });
398
446
  if (variants.length === 0 || variants.length > 256)
399
447
  reporter.fail(stmt, "enums need 1..256 variants");
400
- enums.set(stmt.name.text, { name: stmt.name.text, variants });
448
+ const idlMeta = idlMetaOf(stmt, reporter);
449
+ enums.set(stmt.name.text, { name: stmt.name.text, variants, ...(idlMeta ? { idlMeta } : {}) });
401
450
  }
402
451
  }
403
452
  else if (ts.isFunctionDeclaration(stmt)) {
@@ -672,6 +721,8 @@ export function analyze(entry, files) {
672
721
  };
673
722
  reporter.guard(() => checkRecursion([...helperNodes, ...locals.filter((l) => !inline.has(l.decl))], helperDecls, checker, reporter));
674
723
  const accountStructs = new Set();
724
+ const foreignStructs = new Set();
725
+ const ownStructs = new Set();
675
726
  const argStructs = new Set();
676
727
  const instructions = [];
677
728
  for (const fn of functions) {
@@ -716,6 +767,14 @@ export function analyze(entry, files) {
716
767
  }
717
768
  if (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded") {
718
769
  accountStructs.add(a.kind.struct.name);
770
+ // Owner<Account<T>, "…">: another program's account, which Anchor's IDL lists among the types only.
771
+ if (a.kind.kind === "account" && a.constraints.owner)
772
+ foreignStructs.add(a.kind.struct.name);
773
+ else {
774
+ ownStructs.add(a.kind.struct.name);
775
+ if (a.kind.struct.accountDiscriminator.length !== 8)
776
+ reporter.error(a.node, `${a.kind.struct.name}'s discriminator is shorter than 8 bytes: it is another program's account, Owner<Account<${a.kind.struct.name}>, "…">`);
777
+ }
719
778
  if (a.kind.struct.viewsOnly)
720
779
  reporter.error(a.node, `${a.kind.struct.name} holds a string (or an enum carrying one), so it is an argument, return value or event; account data uses FixedString<N>`);
721
780
  }
@@ -725,6 +784,18 @@ export function analyze(entry, files) {
725
784
  // nowhere else (not account data, not nested, not returned) is read as Anchor sends it: @layout borsh, implied.
726
785
  // Anywhere else its FixedVec keeps the padded layout of account data, which an argument cannot have.
727
786
  const hasFixedVec = (n) => structs.get(n).fields.some((f) => f.type.kind === "vec" && f.type.cap !== undefined);
787
+ // An Option anywhere in it (Anchor's BankConfigOpt): Borsh in arguments, one byte when empty.
788
+ const hasOption = (n, seen = new Set()) => !seen.has(n) &&
789
+ structs.get(n).fields.some((f) => {
790
+ const inner = f.type.kind === "option"
791
+ ? "option"
792
+ : f.type.kind === "struct"
793
+ ? f.type.name
794
+ : f.type.kind === "array" && f.type.elem.kind === "struct"
795
+ ? f.type.elem.name
796
+ : undefined;
797
+ return inner === "option" || (inner !== undefined && hasOption(inner, new Set([...seen, n])));
798
+ });
728
799
  const holds = (f, n) => {
729
800
  const inner = f.type.kind === "array" || f.type.kind === "vec" ? f.type.elem : f.type.kind === "option" ? f.type.inner : f.type;
730
801
  return inner.kind === "struct" && inner.name === n;
@@ -754,6 +825,50 @@ export function analyze(entry, files) {
754
825
  reporter.error(ix.node.name ?? ix.node, `argument ${a.name}: ${n} holds a FixedVec and is also account data, nested or returned (a fixed layout there, Borsh in arguments); declare a separate struct for the argument, or pass the list as its own FixedVec<T, N> argument`);
755
826
  }
756
827
  }
828
+ // Structs with Options (at any depth) that travel only in instruction data and events (Anchor's BankConfigOpt):
829
+ // Borsh on the wire, an empty Option one byte, while their C layout stays fixed. Not when they are also account
830
+ // data, nested in a fixed-layout struct that is not one of these, or returned.
831
+ {
832
+ const argStructs = new Set();
833
+ for (const ix of instructions)
834
+ for (const a of ix.args)
835
+ collectStructs(a.type, structs, dataEnums, argStructs);
836
+ // Also what @layout borsh structs (events, accounts) hold: their bytes there are Borsh at every depth.
837
+ const inBorsh = new Set();
838
+ const collectHeld = (n) => {
839
+ for (const f of structs.get(n)?.fields ?? []) {
840
+ const t = f.type.kind === "option" ? f.type.inner : f.type.kind === "array" ? f.type.elem : f.type;
841
+ if (t.kind === "struct" && !inBorsh.has(t.name)) {
842
+ inBorsh.add(t.name);
843
+ collectHeld(t.name);
844
+ }
845
+ }
846
+ };
847
+ for (const sd of structs.values())
848
+ if (sd.layout === "borsh")
849
+ collectHeld(sd.name);
850
+ const wire = new Set([...argStructs, ...inBorsh].filter((n) => structs.get(n).layout !== "borsh" && hasOption(n)));
851
+ const returned = (n) => instructions.some((i) => i.returns?.kind === "struct" && i.returns.name === n);
852
+ for (let changed = true; changed;) {
853
+ changed = false;
854
+ for (const n of [...wire]) {
855
+ const heldBy = [...structs.values()].filter((o) => o.fields.some((f) => holds(f, n)));
856
+ if (accountStructs.has(n) || returned(n) || heldBy.some((o) => o.layout !== "borsh" && !wire.has(o.name))) {
857
+ wire.delete(n);
858
+ changed = true;
859
+ }
860
+ }
861
+ }
862
+ for (const n of wire)
863
+ structs.get(n).wire = "borsh";
864
+ }
865
+ // An Option<Vec<T>> field is Borsh, of no fixed size: a field of an event, not of account data, an argument, a
866
+ // returned struct or a struct nested in another.
867
+ for (const sd of structs.values()) {
868
+ const f = sd.fields.find((x) => x.type.kind === "vec" && x.type.optional);
869
+ if (f && (accountStructs.has(sd.name) || argStructs.has(sd.name) || nestedSomewhere(sd.name) || sd.layout === "borsh"))
870
+ reporter.error(sd.node, `${sd.name}.${f.name}: Option<Vec<T>> fields are for events (emit<${sd.name}>), not account data, arguments or nested structs`);
871
+ }
757
872
  checkSnakeDuplicates(instructions.map((ix) => ({ name: ix.node.name.text, node: ix.node.name })), "instructions", reporter);
758
873
  // emitCpi's event instruction (Anchor's EVENT_IX_TAG) is dispatched before every other instruction.
759
874
  if (instructions.some((ix) => ix.accounts.some((a) => a.kind.kind === "eventAuthority"))) {
@@ -795,6 +910,7 @@ export function analyze(entry, files) {
795
910
  constants,
796
911
  events: collectEvents([...functions, ...helperNodes], structs),
797
912
  accountStructs,
913
+ foreignAccounts: new Set([...foreignStructs].filter((n) => !ownStructs.has(n))),
798
914
  argStructs,
799
915
  fstrings,
800
916
  fixedVecs,
@@ -859,8 +975,26 @@ export function resolveArgAggregate(node, scope, structs) {
859
975
  const top = fixed(node);
860
976
  if (top?.kind === "struct")
861
977
  return { kind: "structRef", struct: top.name, writable: false };
978
+ // Option<S> / S | null of a fixed-size struct whose Borsh bytes are its layout (no Options or Vecs inside).
979
+ {
980
+ let inner;
981
+ if (typesolName(node, scope.imports) === "Option")
982
+ inner = node.typeArguments?.[0];
983
+ else if (ts.isUnionTypeNode(node) && node.types.length === 2) {
984
+ const isNull = (t) => ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword;
985
+ inner = isNull(node.types[1]) ? node.types[0] : isNull(node.types[0]) ? node.types[1] : undefined;
986
+ }
987
+ const s = inner && ts.isTypeReferenceNode(inner) && ts.isIdentifier(inner.typeName) && !inner.typeArguments?.length
988
+ ? structs.get(structNameOf(inner, scope))
989
+ : undefined;
990
+ if (s && s.size !== undefined && !s.vec && s.layout !== "borsh" && s.wire !== "borsh")
991
+ return { kind: "optionArg", option: { kind: "option", inner: { kind: "struct", name: s.name } } };
992
+ }
862
993
  if (top?.kind === "array")
863
994
  return { kind: "arrayArg", array: top };
995
+ const optionalList = optionalVecArg(node, scope, (n) => resolveArgAggregate(n, scope, structs));
996
+ if (optionalList)
997
+ return optionalList;
864
998
  const list = typesolName(node, scope.imports);
865
999
  if (list === "Vec" || list === "FixedVec") {
866
1000
  const [e, n] = node.typeArguments ?? [];
@@ -895,22 +1029,41 @@ export function resolveScalarType(node, scope) {
895
1029
  return { kind: "pubkey" };
896
1030
  if (n === "Hash")
897
1031
  return { kind: "pubkey", hash: true };
1032
+ // An f64 is held as its IEEE bits, a u64 (Borsh writes it as those 8 bytes); the IDL calls it f64.
1033
+ if (n === "f64")
1034
+ return { kind: "int", name: "u64", f64: true };
898
1035
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && scope.enums.has(node.typeName.text))
899
1036
  return { kind: "enum", name: node.typeName.text };
900
1037
  return undefined;
901
1038
  }
902
1039
  /** `Option<T>` or `T | null` with a scalar T. Records the use so a C typedef / IDL type is emitted. */
903
- export function resolveOptionType(node, scope) {
904
- let innerNode;
1040
+ /** The T of `Option<T>` or `T | null`. */
1041
+ function optionInner(node, scope) {
905
1042
  if (typesolName(node, scope.imports) === "Option")
906
- innerNode = node.typeArguments?.[0];
907
- else if (ts.isUnionTypeNode(node) && node.types.length === 2) {
1043
+ return node.typeArguments?.[0];
1044
+ if (ts.isUnionTypeNode(node) && node.types.length === 2) {
908
1045
  const isNull = (t) => ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword;
909
1046
  if (isNull(node.types[1]))
910
- innerNode = node.types[0];
911
- else if (isNull(node.types[0]))
912
- innerNode = node.types[1];
1047
+ return node.types[0];
1048
+ if (isNull(node.types[0]))
1049
+ return node.types[1];
913
1050
  }
1051
+ return undefined;
1052
+ }
1053
+ /**
1054
+ * `Option<Vec<T>>` (or `Vec<T> | null`, or a FixedVec) as an instruction argument: Anchor's `Option<Vec<u8>>`. A tag
1055
+ * byte, then the Borsh Vec when Some; a None reads as an empty list, and `x !== null` tells them apart.
1056
+ */
1057
+ function optionalVecArg(node, scope, inner) {
1058
+ const n = optionInner(node, scope);
1059
+ const list = n && typesolName(n, scope.imports);
1060
+ if (!n || (list !== "Vec" && list !== "FixedVec"))
1061
+ return undefined;
1062
+ const v = inner(n);
1063
+ return v?.kind === "vecArg" && v.elem.kind !== "string" ? { ...v, optional: true } : undefined;
1064
+ }
1065
+ export function resolveOptionType(node, scope) {
1066
+ const innerNode = optionInner(node, scope);
914
1067
  if (!innerNode)
915
1068
  return undefined;
916
1069
  const inner = resolveScalarType(innerNode, scope);
@@ -926,6 +1079,11 @@ export function resolveValueType(node, scope, allowVec = false) {
926
1079
  const opt = resolveOptionType(node, scope);
927
1080
  if (opt)
928
1081
  return opt;
1082
+ if (allowVec) {
1083
+ const v = optionalVecArg(node, scope, (n) => resolveValueType(n, scope, true));
1084
+ if (v)
1085
+ return v;
1086
+ }
929
1087
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && scope.dataEnums?.has(node.typeName.text))
930
1088
  return { kind: "dataEnumArg", name: node.typeName.text };
931
1089
  if (allowVec && typesolName(node, scope.imports) === "Vec") {
@@ -962,6 +1120,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
962
1120
  const structs = new Map();
963
1121
  let scope = scopeFor(new Map());
964
1122
  let imports = scope.imports;
1123
+ const isScalarField = (t) => t.kind === "int" || t.kind === "bool" || t.kind === "pubkey" || t.kind === "enum";
965
1124
  const fieldType = (node) => {
966
1125
  if (node.kind === ts.SyntaxKind.StringKeyword)
967
1126
  return { kind: "string" };
@@ -971,6 +1130,15 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
971
1130
  const opt = resolveOptionType(node, scope);
972
1131
  if (opt)
973
1132
  return opt;
1133
+ // Option<Vec<T>> (events only: Anchor's Option<Vec<Pubkey>>): a tag byte, then the Vec when Some.
1134
+ {
1135
+ const inner = optionInner(node, scope);
1136
+ if (inner && typesolName(inner, imports) === "Vec") {
1137
+ const v = fieldType(inner);
1138
+ if (v.kind === "vec")
1139
+ return { ...v, optional: true };
1140
+ }
1141
+ }
974
1142
  // Option of a struct (account data only): Option<Point> or Point | null
975
1143
  {
976
1144
  let inner;
@@ -985,6 +1153,15 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
985
1153
  scope.options.set(optionKey(t), t);
986
1154
  return { kind: "option", inner: t };
987
1155
  }
1156
+ // Option<FixedArray<T, N>> of fixed-size elements (Anchor's Option<[u16; 3]>).
1157
+ if (inner && typesolName(inner, imports) === "FixedArray") {
1158
+ const arr = fieldType(inner);
1159
+ if (arr.kind === "array" && (isScalarField(arr.elem) || arr.elem.kind === "struct")) {
1160
+ const t = { kind: "array", elem: arr.elem, len: arr.len };
1161
+ scope.options.set(optionKey(t), t);
1162
+ return { kind: "option", inner: t };
1163
+ }
1164
+ }
988
1165
  }
989
1166
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && enumNames.has(node.typeName.text))
990
1167
  return { kind: "dataEnum", name: node.typeName.text };
@@ -1055,7 +1232,18 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1055
1232
  if (problem)
1056
1233
  reporter.fail(m.name, problem);
1057
1234
  const type = fieldType(m.type);
1058
- fields.push({ name, type, node: m });
1235
+ // `/** @bytes */`: an integer the IDL describes as its bytes (Marginfi's WrappedI80F48 { value: [u8; 16] }), or a
1236
+ // FixedArray of them, each its bytes (Marginfi's HealthCache.prices: [[u8; 8]; 16], f64 bits).
1237
+ const bytesTag = ts.getJSDocTags(m).find((t) => t.tagName.text === "bytes");
1238
+ const bytesOf = type.kind === "int" ? type : type.kind === "array" && type.elem.kind === "int" ? type.elem : undefined;
1239
+ if (bytesTag && !bytesOf)
1240
+ reporter.fail(bytesTag, "@bytes is for integer fields (or FixedArrays of integers): the IDL then shows the bytes, [u8; N]");
1241
+ const idlBytes = bytesTag && bytesOf ? Number(/\d+/.exec(bytesOf.name)[0]) / 8 : undefined;
1242
+ const nameTag = ts.getJSDocTags(m).find((t) => t.tagName.text === "idlName");
1243
+ const idlName = typeof nameTag?.comment === "string" ? nameTag.comment.trim() : undefined;
1244
+ if (nameTag && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(idlName ?? ""))
1245
+ reporter.fail(nameTag, "@idlName takes the field's name in the IDL: @idlName _pad0");
1246
+ fields.push({ name, type, node: m, ...(idlBytes ? { idlBytes } : {}), ...(idlName ? { idlName } : {}) });
1059
1247
  }
1060
1248
  checkSnakeDuplicates(decl.members.map((m) => ({ name: m.name.text, node: m })), "fields", reporter);
1061
1249
  const name = decl.name.text;
@@ -1076,7 +1264,13 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1076
1264
  const stored = layoutText === "borsh" ? fields : [...fields.filter((f) => !growable(f)), ...fields.filter(growable)];
1077
1265
  for (const f of stored)
1078
1266
  delete f.node;
1267
+ const idlMeta = idlMetaOf(decl, reporter);
1268
+ if (idlMeta?.repr && layoutText === "borsh")
1269
+ reporter.fail(decl.name, "@repr describes a zero-copy (fixed layout) struct, not a @layout borsh one");
1270
+ const declared = fields.map((f) => f.name);
1079
1271
  structs.set(name, {
1272
+ ...(idlMeta ? { idlMeta } : {}),
1273
+ ...(stored.some((f, i) => f.name !== declared[i]) ? { declared } : {}),
1080
1274
  name,
1081
1275
  fields: stored,
1082
1276
  size: undefined,
@@ -1130,7 +1324,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1130
1324
  }
1131
1325
  if (variants.length < 1 || variants.length > 256)
1132
1326
  reporter.fail(decl, "data enums need 1..256 variants");
1133
- dataEnums.set(decl.name.text, { name: decl.name.text, variants, payload: 0, node: decl });
1327
+ const idlMeta = idlMetaOf(decl, reporter);
1328
+ dataEnums.set(decl.name.text, { name: decl.name.text, variants, payload: 0, node: decl, ...(idlMeta ? { idlMeta } : {}) });
1134
1329
  });
1135
1330
  }
1136
1331
  // Sizes, with cycle detection. `string` fields leave the size undefined (event-only struct).
@@ -1143,7 +1338,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1143
1338
  case "enum":
1144
1339
  return scalarSize(t);
1145
1340
  case "option":
1146
- return 1 + (t.inner.kind === "struct" ? sizeOf(t.inner, at) : scalarSize(t.inner));
1341
+ return 1 + (t.inner.kind === "struct" || t.inner.kind === "array" ? sizeOf(t.inner, at) : scalarSize(t.inner));
1147
1342
  case "dataEnum": {
1148
1343
  const e = dataEnums.get(t.name);
1149
1344
  if (!e)
@@ -1212,6 +1407,43 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1212
1407
  }
1213
1408
  }
1214
1409
  };
1410
+ // A `@repr c` struct that is not packed is Rust's repr(C): each field at a multiple of its alignment and the size a
1411
+ // multiple of the struct's. TypeSOL stores fields back to back, so that holds only when C would add no padding.
1412
+ const alignOf = (t, at) => {
1413
+ switch (t.kind) {
1414
+ case "int": {
1415
+ const bytes = Number(/\d+/.exec(t.name)[0]) / 8;
1416
+ if (bytes > 8)
1417
+ reporter.fail(at, `a ${t.name} field in a repr(C) zero-copy struct: its alignment differs between targets; hold it as /** @bytes */ in a struct of its own (Marginfi's WrappedI80F48) or mark the struct packed`);
1418
+ return bytes;
1419
+ }
1420
+ case "array":
1421
+ return alignOf(t.elem, at);
1422
+ case "struct": {
1423
+ const inner = structs.get(t.name);
1424
+ return inner ? Math.max(inner.idlMeta?.repr?.align ?? 1, ...inner.fields.map((f) => (f.idlBytes ? 1 : alignOf(f.type, at)))) : 1;
1425
+ }
1426
+ case "bool":
1427
+ case "pubkey":
1428
+ case "enum":
1429
+ return 1;
1430
+ default:
1431
+ return reporter.fail(at, "a zero-copy struct holds integers, booleans, Pubkeys, unit enums, fixed arrays and other such structs");
1432
+ }
1433
+ };
1434
+ const zeroCopyOffsets = (s, align) => {
1435
+ let offset = 0;
1436
+ let max = align ?? 1;
1437
+ for (const f of s.fields) {
1438
+ const align = f.idlBytes ? 1 : alignOf(f.type, s.node);
1439
+ max = Math.max(max, align);
1440
+ if (offset % align !== 0)
1441
+ reporter.fail(s.node.name, `${s.name}.${f.name} is at byte ${offset}, which C would pad to a multiple of ${align}: add the padding field repr(C) has there, or mark it packed`);
1442
+ offset += sizeOf(f.type, s.node);
1443
+ }
1444
+ if (offset % max !== 0)
1445
+ reporter.fail(s.node.name, `${s.name} is ${offset} bytes, which C would pad to a multiple of ${max}: add the trailing padding field repr(C) has`);
1446
+ };
1215
1447
  const visit = (s) => {
1216
1448
  if (state.get(s.name) === "done")
1217
1449
  return;
@@ -1247,6 +1479,30 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1247
1479
  };
1248
1480
  for (const s of structs.values())
1249
1481
  reporter.guard(() => visit(s));
1482
+ // The repr(C) offsets matter where the bytes are the struct's memory (bytemuck zero-copy accounts and what they
1483
+ // hold), not for a repr(C) struct that only travels as Borsh (an argument).
1484
+ {
1485
+ const inMemory = new Set();
1486
+ const hold = (n) => {
1487
+ if (inMemory.has(n))
1488
+ return;
1489
+ inMemory.add(n);
1490
+ const sd = structs.get(n);
1491
+ for (const f of sd?.fields ?? []) {
1492
+ const t = f.type.kind === "array" ? f.type.elem : f.type.kind === "option" ? f.type.inner : f.type;
1493
+ if (t.kind === "struct")
1494
+ hold(t.name);
1495
+ }
1496
+ };
1497
+ for (const sd of structs.values())
1498
+ if (sd.idlMeta?.serialization?.startsWith("bytemuck"))
1499
+ hold(sd.name);
1500
+ for (const n of inMemory) {
1501
+ const sd = structs.get(n);
1502
+ if (sd.idlMeta?.repr?.kind === "c" && !sd.idlMeta.repr.packed && sd.size !== undefined)
1503
+ reporter.guard(() => zeroCopyOffsets(sd, sd.idlMeta.repr.align));
1504
+ }
1505
+ }
1250
1506
  for (const s of structs.values())
1251
1507
  if (s.layout === "borsh")
1252
1508
  reporter.guard(() => checkBorshLayout(s, structs, dataEnums, reporter));
@@ -1364,6 +1620,17 @@ export function heapVecOf(s) {
1364
1620
  function checkBorshLayout(s, structs, dataEnums, reporter) {
1365
1621
  const model = { structs };
1366
1622
  const fixed = (t) => borshIdentical(t, model);
1623
+ // A nested struct with Options in it (at any depth) and otherwise fixed-size values: Borsh, field by field.
1624
+ const nestedOptions = (t) => {
1625
+ if (t.kind !== "struct")
1626
+ return false;
1627
+ const n = structs.get(t.name);
1628
+ return (!!n &&
1629
+ n.layout !== "borsh" &&
1630
+ n.fields.every((f) => fixed(f.type) ||
1631
+ nestedOptions(f.type) ||
1632
+ (f.type.kind === "option" && (fixed(f.type.inner) || nestedOptions(f.type.inner)))));
1633
+ };
1367
1634
  for (const f of s.fields) {
1368
1635
  const t = f.type;
1369
1636
  const at = s.node.members.find((m) => m.name && ts.isIdentifier(m.name) && m.name.text === f.name) ?? s.node;
@@ -1385,11 +1652,13 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
1385
1652
  }
1386
1653
  if (t.kind === "vec" && (fixed(t.elem) || t.elem.kind === "fstring"))
1387
1654
  continue;
1388
- if (t.kind === "option" && fixed(t.inner))
1655
+ if (t.kind === "option" && (fixed(t.inner) || nestedOptions(t.inner)))
1656
+ continue;
1657
+ if (nestedOptions(t))
1389
1658
  continue;
1390
1659
  if (t.kind === "struct" && structs.get(t.name)?.layout === "borsh")
1391
1660
  reporter.fail(at, `${t.name} is @layout borsh itself: only account structs take a layout; nest a struct without one`);
1392
- reporter.fail(at, `${typeName(t)} in a @layout borsh struct: its fields may be fixed-size values, FixedString<N>, FixedVec<T, N> (of those or of FixedString) and Option<T>; nested structs and lists hold fixed-size values only`);
1661
+ reporter.fail(at, `${typeName(t)} in a @layout borsh struct: its fields may be fixed-size values, FixedString<N>, FixedVec<T, N> (of those or of FixedString) and Option<T>; nested structs hold fixed-size values and Options, lists fixed-size values only`);
1393
1662
  }
1394
1663
  for (const other of structs.values())
1395
1664
  for (const f of other.fields) {
@@ -1429,10 +1698,21 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1429
1698
  if (p.name.text.includes("__") || p.name.text.includes("$"))
1430
1699
  reporter.error(p.name, `"${p.name.text}": "__" and "$" are reserved in names`);
1431
1700
  const type = resolveValueType(p.type, scope, true) ?? resolveArgAggregate(p.type, scope, structs);
1701
+ if (type?.kind === "optionArg")
1702
+ reporter.fail(p.type, "helpers take the struct itself: check the Option argument is not null and pass it (or its fields)");
1703
+ if (type?.kind === "vecArg" && type.optional)
1704
+ reporter.fail(p.type, "helpers take the list itself: check the Option argument is not null and pass it");
1432
1705
  if (type)
1433
1706
  return { name: p.name.text, type, node: p };
1434
1707
  if (typesolName(p.type, scope.imports) === "SignerSeeds")
1435
1708
  return { name: p.name.text, type: { kind: "signerSeeds" }, node: p };
1709
+ // One of the remaining accounts (remainingAccounts().get(i)), as the instruction holds it: read with readData or
1710
+ // loadAccount, its key, owner, lamports and data length.
1711
+ if (typesolName(p.type, scope.imports) === "RemainingAccount")
1712
+ return { name: p.name.text, type: { kind: "account" }, node: p };
1713
+ // The remaining accounts as a list (`remainingAccounts()` at the call): `.length` and `.get(i)` in the helper.
1714
+ if (typesolName(p.type, scope.imports) === "RemainingAccounts")
1715
+ return { name: p.name.text, type: { kind: "remaining" }, node: p };
1436
1716
  // Accounts the caller already checked: Signer, AccountInfo, Account<T>/Mut<T>, token accounts, programs.
1437
1717
  const wrapped = typesolName(p.type, scope.imports);
1438
1718
  if (wrapped === "HasOne" ||
@@ -1605,15 +1885,17 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1605
1885
  if (value) {
1606
1886
  args.push({ name: p.name.text, type: value, node: p });
1607
1887
  minArgsSize +=
1608
- value.kind === "string" || value.kind === "vecArg"
1609
- ? 4
1610
- : value.kind === "option" || value.kind === "dataEnumArg"
1611
- ? 1
1612
- : value.kind === "structRef"
1613
- ? structs.get(value.struct).size
1614
- : isScalar(value)
1615
- ? scalarSize(value)
1616
- : 0;
1888
+ value.kind === "vecArg" && value.optional
1889
+ ? 1
1890
+ : value.kind === "string" || value.kind === "vecArg"
1891
+ ? 4
1892
+ : value.kind === "option" || value.kind === "optionArg" || value.kind === "dataEnumArg"
1893
+ ? 1
1894
+ : value.kind === "structRef"
1895
+ ? structs.get(value.struct).size
1896
+ : isScalar(value)
1897
+ ? scalarSize(value)
1898
+ : 0;
1617
1899
  return;
1618
1900
  }
1619
1901
  // An account group: its accounts are this instruction's, in their order, named `<param>__<field>`.
@@ -1685,7 +1967,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1685
1967
  if (c.closeTo)
1686
1968
  c.closeTo = sibling(c.closeTo);
1687
1969
  if (c.ata)
1688
- c.ata = { owner: sibling(c.ata.owner), mint: sibling(c.ata.mint) };
1970
+ c.ata = { owner: c.ata.owner.startsWith("@") ? at(c.ata.owner) : sibling(c.ata.owner), mint: sibling(c.ata.mint) };
1689
1971
  }
1690
1972
  return all;
1691
1973
  }
@@ -1803,7 +2085,10 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1803
2085
  if (c.ata) {
1804
2086
  if (a.kind.kind !== "token" && a.kind.kind !== "info")
1805
2087
  reporter.fail(a.node, "Ata<…> applies to a TokenAccount (or an AccountInfo about to be created)");
1806
- for (const n of [c.ata.owner, c.ata.mint])
2088
+ // The owner may be a Pubkey field of a struct account parameter, "@acct.field" (Anchor's
2089
+ // `associated_token::authority = acct.load()?.field`).
2090
+ const owner = c.ata.owner.startsWith("@") ? c.ata.owner.slice(1).split(".")[0] : c.ata.owner;
2091
+ for (const n of [owner, c.ata.mint])
1807
2092
  if (!accounts.some((o) => o.name === n))
1808
2093
  reporter.fail(a.node, `Ata<…>: add an account parameter named "${n}"`);
1809
2094
  }
@@ -1827,7 +2112,11 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1827
2112
  ...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
1828
2113
  ...(c.closeTo ? [c.closeTo] : []),
1829
2114
  ...(c.ata
1830
- ? [c.ata.owner, c.ata.mint, ...(a.kind.kind === "token" ? [] : accounts.filter((o) => o.kind.kind === "tokenProgram").map((o) => o.name))]
2115
+ ? [
2116
+ c.ata.owner.startsWith("@") ? c.ata.owner.slice(1).split(".")[0] : c.ata.owner,
2117
+ c.ata.mint,
2118
+ ...(a.kind.kind === "token" ? [] : accounts.filter((o) => o.kind.kind === "tokenProgram").map((o) => o.name)),
2119
+ ]
1831
2120
  : []),
1832
2121
  ];
1833
2122
  for (const r of refs) {
@@ -1864,6 +2153,9 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1864
2153
  a.constraints.owner ||
1865
2154
  a.constraints.dup))
1866
2155
  reporter.error(a.node, "Migrate<From, To> takes no constraints yet: check the old fields with require(…, …) on acct.from");
2156
+ for (const a of accounts)
2157
+ if (a.kind.kind === "instructionsSysvar" && a.constraints.address && a.constraints.address.base58 !== "Sysvar1nstructions1111111111111111111111111")
2158
+ reporter.error(a.node, "Address<InstructionsSysvar, …> must name the Instructions sysvar (Sysvar1nstructions1111111111111111111111111)");
1867
2159
  const name = snakeCase(fn.name.text);
1868
2160
  // `/** @discriminator spl-transfer-hook-interface:execute */` (sha256 preimage) or `@discriminator 0x...` (raw bytes)
1869
2161
  // lets an instruction implement another program's interface.
@@ -134,7 +134,8 @@ export class AliasEmitter extends EmitterBase {
134
134
  }
135
135
  helperTakesMutAccounts(node) {
136
136
  const h = this.helperOf(node);
137
- return !!h?.params.some((p) => p.account && isWritable(p.account));
137
+ // A RemainingAccount(s) parameter may be loaded with loadAccountMut inside.
138
+ return !!h?.params.some((p) => (p.account ? isWritable(p.account) : p.type.kind === "account" || p.type.kind === "remaining"));
138
139
  }
139
140
  /**
140
141
  * Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
@@ -156,7 +157,7 @@ export class AliasEmitter extends EmitterBase {
156
157
  else if (ts.isIdentifier(callee)) {
157
158
  if (this.lookup(callee.text)?.closure)
158
159
  found = true;
159
- else if (["realloc", "close"].includes(this.exportName(callee) ?? ""))
160
+ else if (["realloc", "resizeAccount", "close"].includes(this.exportName(callee) ?? ""))
160
161
  found = true;
161
162
  else if (this.helperOf(n) && (this.helperTakesMutAccounts(n) || n.arguments.some(isClosure)))
162
163
  found = true;
@@ -49,6 +49,8 @@ export declare abstract class EmitterBase {
49
49
  protected readonly inlining: Set<ts.Node>;
50
50
  /** Enclosing loops, innermost last; each has a `continue` label. */
51
51
  protected readonly loops: string[];
52
+ /** loadAccountMut calls whose claim a loop drops at each iteration's end: the C variable that records it. */
53
+ protected readonly claimSlots: Map<ts.Node, string>;
52
54
  protected readonly ix: Instruction | undefined;
53
55
  protected readonly helper: Helper | undefined;
54
56
  /** Type names in effect (a generic helper expanded where it is called binds its type parameters here). */
@@ -119,6 +121,7 @@ export declare abstract class EmitterBase {
119
121
  protected abstract ref(node: ts.Expression): Ref | undefined;
120
122
  protected abstract call(node: ts.CallExpression, topLevel: boolean): Value | undefined;
121
123
  protected abstract isRemaining(node: ts.Expression): boolean;
124
+ protected abstract remainingBase(node: ts.Expression): string;
122
125
  protected abstract handle(node: ts.Expression): string | undefined;
123
126
  protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
124
127
  protected abstract isTxIx(node: ts.Expression): boolean;
@@ -133,6 +136,7 @@ export declare abstract class EmitterBase {
133
136
  protected abstract createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
134
137
  protected abstract systemTransfer(node: ts.CallExpression): undefined;
135
138
  protected abstract createAccount(node: ts.CallExpression, system: AccountParam): undefined;
139
+ protected abstract createPda(node: ts.CallExpression): Value;
136
140
  protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
137
141
  protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
138
142
  protected abstract ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
@@ -162,5 +166,6 @@ export declare abstract class EmitterBase {
162
166
  ci: string;
163
167
  next?: string;
164
168
  alwaysNext?: boolean;
169
+ atNext?: () => void;
165
170
  }, body: (element: ts.Expression, index: ts.Expression) => void): void;
166
171
  }