@typesol/cli 0.49.0 → 0.51.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 (79) hide show
  1. package/CHANGELOG.md +541 -0
  2. package/NOTICE +9 -0
  3. package/README.md +34 -15
  4. package/SECURITY.md +6 -3
  5. package/dist/cli.js +36 -5
  6. package/dist/compiler/analyze.d.ts +10 -1
  7. package/dist/compiler/analyze.js +234 -20
  8. package/dist/compiler/diagnostics.d.ts +4 -0
  9. package/dist/compiler/diagnostics.js +5 -1
  10. package/dist/compiler/emit/base.d.ts +35 -4
  11. package/dist/compiler/emit/base.js +46 -4
  12. package/dist/compiler/emit/borsh.js +8 -8
  13. package/dist/compiler/emit/calls.d.ts +6 -0
  14. package/dist/compiler/emit/calls.js +98 -18
  15. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  16. package/dist/compiler/emit/cpi-core.js +11 -5
  17. package/dist/compiler/emit/cpi.js +6 -4
  18. package/dist/compiler/emit/create.js +9 -9
  19. package/dist/compiler/emit/expressions.d.ts +9 -1
  20. package/dist/compiler/emit/expressions.js +77 -0
  21. package/dist/compiler/emit/function.d.ts +2 -0
  22. package/dist/compiler/emit/function.js +71 -15
  23. package/dist/compiler/emit/outline.d.ts +35 -0
  24. package/dist/compiler/emit/outline.js +547 -0
  25. package/dist/compiler/emit/program.js +19 -4
  26. package/dist/compiler/emit/rbtree.js +1 -1
  27. package/dist/compiler/emit/shared.d.ts +69 -4
  28. package/dist/compiler/emit/shared.js +44 -9
  29. package/dist/compiler/emit/statements.d.ts +36 -2
  30. package/dist/compiler/emit/statements.js +332 -29
  31. package/dist/compiler/emit/storage.d.ts +16 -0
  32. package/dist/compiler/emit/storage.js +134 -13
  33. package/dist/compiler/emit/views.js +1 -1
  34. package/dist/compiler/hints.d.ts +1 -1
  35. package/dist/compiler/hints.js +9 -1
  36. package/dist/compiler/idl.js +1 -1
  37. package/dist/compiler/index.d.ts +30 -2
  38. package/dist/compiler/index.js +94 -16
  39. package/dist/compiler/model.d.ts +13 -1
  40. package/dist/compiler/stack.d.ts +71 -0
  41. package/dist/compiler/stack.js +309 -0
  42. package/dist/compiler/toolchain.d.ts +87 -5
  43. package/dist/compiler/toolchain.js +384 -19
  44. package/dist/keys.d.ts +12 -1
  45. package/dist/keys.js +57 -7
  46. package/dist/workspace.d.ts +9 -0
  47. package/dist/workspace.js +91 -16
  48. package/docker/deps/0.50.0.lock.json +1206 -0
  49. package/docker/deps/0.51.0.lock.json +1206 -0
  50. package/docs/architecture.md +1 -1
  51. package/docs/audit.md +16 -13
  52. package/docs/case-study-escrow.md +1 -1
  53. package/docs/case-study-jito-mev.md +14 -14
  54. package/docs/case-study-marginfi.md +127 -127
  55. package/docs/case-study-multisig.md +16 -4
  56. package/docs/case-study-raydium-clmm.md +44 -28
  57. package/docs/case-study-raydium-cp-swap.md +18 -18
  58. package/docs/cli.md +5 -4
  59. package/docs/glossary.md +2 -1
  60. package/docs/language-accounts.md +16 -10
  61. package/docs/language-basics.md +29 -2
  62. package/docs/language-builtins.md +4 -2
  63. package/docs/language-cpi.md +34 -0
  64. package/docs/language-native.md +50 -4
  65. package/docs/language-pdas.md +6 -2
  66. package/docs/language-statements.md +103 -12
  67. package/docs/language-types.md +93 -8
  68. package/docs/runtime.md +20 -3
  69. package/docs/security-model.md +6 -3
  70. package/docs/stability.md +10 -5
  71. package/docs/testing.md +6 -2
  72. package/docs/troubleshooting.md +45 -1
  73. package/lib/typesol.d.ts +25 -3
  74. package/llms-full.txt +403 -54
  75. package/package.json +1 -1
  76. package/releases/0.49.0.json +857 -0
  77. package/releases/0.50.0.json +874 -0
  78. package/runtime/typesol_builtins.c +47 -2
  79. package/runtime/typesol_rt.h +254 -54
@@ -50,6 +50,14 @@ export class EmitterBase {
50
50
  inlining = new Set();
51
51
  /** Enclosing loops, innermost last; each has a `continue` label. */
52
52
  loops = [];
53
+ /**
54
+ * Enclosing labeled statements (`outer: for …`, `done: { … }`), innermost last: the name, the `loops` depth its loop
55
+ * has (its `continue` label is `loops[depth]` while its body is emitted), the C label after it that `break name`
56
+ * jumps to, and whether a jump used that label.
57
+ */
58
+ labels = [];
59
+ /** The claim slots each loop body drops at its iteration's end (see iterationClaims), for a labeled jump out of it. */
60
+ loopClaims = new Map();
53
61
  /** loadAccountMut calls whose claim a loop drops at each iteration's end: the C variable that records it. */
54
62
  claimSlots = new Map();
55
63
  ix;
@@ -68,8 +76,16 @@ export class EmitterBase {
68
76
  */
69
77
  panicAt;
70
78
  profile;
79
+ /** The layout chosen for a program that does not fit the stack otherwise (empty: none). */
80
+ stack;
81
+ /** This function's statements each get a C block of their own (StackPlan.scope; see statement()). */
82
+ scopeTemps;
83
+ /** The blocks opened for scopeTemps, numbered within the function. */
84
+ scopeBlocks = 0;
71
85
  constructor(analysis, target, opts = {}) {
72
86
  this.profile = !!opts.profile;
87
+ this.stack = opts.stack ?? {};
88
+ this.scopeTemps = !!this.stack.scope?.has("accounts" in target ? `ix_${target.name}` : `fn_${target.name}`);
73
89
  this.reporter = analysis.reporter;
74
90
  this.model = analysis.model;
75
91
  // Each function resolves `typesol` names through its own file's imports.
@@ -243,7 +259,7 @@ export class EmitterBase {
243
259
  const t = probe.type;
244
260
  return t.kind === "pubkey" ? (t.hash ? { kind: "pubkey", hash: true } : { kind: "pubkey" }) : t;
245
261
  }
246
- return this.fail(node, `cannot tell what ${tp} is from literal arguments; ${usage}`);
262
+ return this.fail(node, `cannot tell what ${tp} is from these arguments (literals, lists and functions do not say); ${usage}`);
247
263
  });
248
264
  }
249
265
  line(s) {
@@ -254,6 +270,24 @@ export class EmitterBase {
254
270
  s = s.replace(/\*\(&(\w+->(?:key|owner))\)/g, "$1");
255
271
  this.lines.push(" ".repeat(this.indent) + s);
256
272
  }
273
+ /**
274
+ * A list or struct this instruction holds itself, which the build may keep on the heap to fit the stack: the key of
275
+ * `node` (a declaration or a helper call) and whether StackPlan.heap names it. Only in an instruction's own body (not
276
+ * in a closure or a helper expanded into it), and recorded among StackPlan.candidates when the build asks for them.
277
+ */
278
+ autoHeap(node, what) {
279
+ if (!this.ix || this.helper || node.flags & ts.NodeFlags.Synthesized || node.pos < 0)
280
+ return false;
281
+ if (ts.findAncestor(node.parent, ts.isFunctionLike) !== this.ix.node)
282
+ return false;
283
+ const key = `${node.getSourceFile().fileName}:${node.getStart()}`;
284
+ this.stack.candidates?.push({ key, fn: `ix_${this.ix.name}`, at: this.location(node), ...what });
285
+ return !what.stack && !what.heap && !!this.stack.heap?.has(key);
286
+ }
287
+ /** `/** @stack *\/` on a declaration (or its statement): never kept on the heap by the build. */
288
+ stackTagged(d) {
289
+ return [d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "stack"));
290
+ }
257
291
  /** `file.ts:line` of a node, for messages. */
258
292
  location(node) {
259
293
  const sf = node.getSourceFile();
@@ -371,6 +405,7 @@ export class EmitterBase {
371
405
  scopes: this.scopes.length,
372
406
  indent: this.indent,
373
407
  loops: this.loops.length,
408
+ labels: this.labels.length,
374
409
  frames: this.inlineFrames.length,
375
410
  created: new Set(this.created),
376
411
  pendingInit: new Set(this.pendingInit),
@@ -389,6 +424,7 @@ export class EmitterBase {
389
424
  this.scopes.length = saved.scopes;
390
425
  this.indent = saved.indent;
391
426
  this.loops.length = saved.loops;
427
+ this.labels.length = saved.labels;
392
428
  this.inlineFrames.length = saved.frames;
393
429
  for (const [set, from] of [
394
430
  [this.created, saved.created],
@@ -422,12 +458,13 @@ export class EmitterBase {
422
458
  * `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: a Rust panic logs what that solana-program's panic handler
423
459
  * logs and then aborts, so the runtime reports "SBF program panicked". rustc before 1.73 (solana-program 1.14 to
424
460
  * 1.17) formats a panic as `panicked at '<message>', <file>:<line>:<col>`; from 1.73 (solana-program 1.18's toolchain)
425
- * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. By default it logs the message
426
- * and calls sol_panic_ with the location.
461
+ * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. `"pinocchio"`: pinocchio's
462
+ * `default_panic_handler!` hook logs the location's file alone, then "** PANICKED **", and std aborts. By default it
463
+ * logs the message and calls sol_panic_ with the location.
427
464
  */
428
465
  panicStyle() {
429
466
  const v = this.model.constants.get("PANIC_STYLE")?.value;
430
- return v === "solana-1.14" || v === "solana-1.18" ? v : undefined;
467
+ return v === "solana-1.14" || v === "solana-1.18" || v === "pinocchio" ? v : undefined;
431
468
  }
432
469
  /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
433
470
  panicC(message, location) {
@@ -436,6 +473,11 @@ export class EmitterBase {
436
473
  return [`sol_log(${cString(`panicked at '${message}', ${location}`)});`, `abort();`, `__builtin_unreachable();`];
437
474
  if (style === "solana-1.18")
438
475
  return [`sol_log(${cString(`panicked at ${location}:\n${message}`)});`, `abort();`, `__builtin_unreachable();`];
476
+ if (style === "pinocchio") {
477
+ // `location.file()` verbatim: the location without its ":line" / ":line:column" (a bare file is kept whole).
478
+ const file = location.replace(/:\d+(?::\d+)?$/, "");
479
+ return [`ts_panic_file(${cString(file)}, ${Buffer.byteLength(file)});`];
480
+ }
439
481
  const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(location);
440
482
  const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [location, "0", "0"];
441
483
  return [
@@ -250,7 +250,7 @@ function codec(s, model, o) {
250
250
  const n = fixedBytes(f.type, model);
251
251
  return [
252
252
  need(String(n), after(i), pad),
253
- `${pad}ts_memcpy(&${lv}.${f.name}, src + at, ${n});`,
253
+ `${pad}TS_MEMCPY(&${lv}.${f.name}, src + at, ${n});`,
254
254
  `${pad}at += ${n};`,
255
255
  ...validate(f.type, `${lv}.${f.name}`, pad),
256
256
  ];
@@ -279,7 +279,7 @@ function codec(s, model, o) {
279
279
  `${pad}${lv}.some = ${tag};`,
280
280
  `${pad}if (${tag}) {`,
281
281
  need(String(n), rest, `${pad} `),
282
- `${pad} ts_memcpy(&${lv}.v, src + at, ${n});`,
282
+ `${pad} TS_MEMCPY(&${lv}.v, src + at, ${n});`,
283
283
  `${pad} at += ${n};`,
284
284
  ...validate(t.inner, `${lv}.v`, `${pad} `),
285
285
  `${pad}}`,
@@ -315,7 +315,7 @@ function codec(s, model, o) {
315
315
  continue;
316
316
  }
317
317
  const n = fixedBytes(f.type, model);
318
- lines.push(need(String(n), rest, `${pad} `), `${pad} ts_memcpy(&${flv}, src + at, ${n});`, `${pad} at += ${n};`, ...validate(f.type, flv, `${pad} `));
318
+ lines.push(need(String(n), rest, `${pad} `), `${pad} TS_MEMCPY(&${flv}, src + at, ${n});`, `${pad} at += ${n};`, ...validate(f.type, flv, `${pad} `));
319
319
  }
320
320
  lines.push(`${pad} break;`, `${pad}}`);
321
321
  });
@@ -367,7 +367,7 @@ function codec(s, model, o) {
367
367
  return sub.fields.flatMap((f, i) => {
368
368
  if (borshIdentical(f.type, model)) {
369
369
  const n = fixedBytes(f.type, model);
370
- return [room(String(n), after(i), pad), `${pad}ts_memcpy(dst + at, &${lv}.${f.name}, ${n});`, `${pad}at += ${n};`];
370
+ return [room(String(n), after(i), pad), `${pad}TS_MEMCPY(dst + at, &${lv}.${f.name}, ${n});`, `${pad}at += ${n};`];
371
371
  }
372
372
  return packVar(f.type, `${lv}.${f.name}`, after(i), pad);
373
373
  });
@@ -386,7 +386,7 @@ function codec(s, model, o) {
386
386
  room(`(uint64_t)(${lv}.some ? ${1 + n} : 1)`, rest, pad),
387
387
  `${pad}dst[at++] = ${lv}.some ? 1 : 0;`,
388
388
  `${pad}if (${lv}.some) {`,
389
- `${pad} ts_memcpy(dst + at, &${lv}.v, ${n});`,
389
+ `${pad} TS_MEMCPY(dst + at, &${lv}.v, ${n});`,
390
390
  `${pad} at += ${n};`,
391
391
  `${pad}}`,
392
392
  ];
@@ -413,7 +413,7 @@ function codec(s, model, o) {
413
413
  continue;
414
414
  }
415
415
  const n = fixedBytes(f.type, model);
416
- lines.push(room(String(n), rest, `${pad} `), `${pad} ts_memcpy(dst + at, &${flv}, ${n});`, `${pad} at += ${n};`);
416
+ lines.push(room(String(n), rest, `${pad} `), `${pad} TS_MEMCPY(dst + at, &${flv}, ${n});`, `${pad} at += ${n};`);
417
417
  }
418
418
  lines.push(`${pad} break;`, `${pad}}`);
419
419
  });
@@ -434,11 +434,11 @@ function codec(s, model, o) {
434
434
  let bytes = 0;
435
435
  while (j < s.fields.length && borshIdentical(s.fields[j].type, model))
436
436
  bytes += fixedBytes(s.fields[j++].type, model);
437
- unpackLines.push(` ts_memcpy(&out->${f.name}, src + at, ${bytes});`, ` at += ${bytes};`);
437
+ unpackLines.push(` TS_MEMCPY(&out->${f.name}, src + at, ${bytes});`, ` at += ${bytes};`);
438
438
  for (const g of s.fields.slice(i, j))
439
439
  unpackLines.push(...validate(g.type, `out->${g.name}`, " "));
440
440
  // A pack can be short of room only after a String / Vec / Option grew; the start always fits (cap >= MIN).
441
- packLines.push(...(i > 0 ? [room(String(bytes), minAfter[j - 1], " ")] : []), ` ts_memcpy(dst + at, &in->${f.name}, ${bytes});`, ` at += ${bytes};`);
441
+ packLines.push(...(i > 0 ? [room(String(bytes), minAfter[j - 1], " ")] : []), ` TS_MEMCPY(dst + at, &in->${f.name}, ${bytes});`, ` at += ${bytes};`);
442
442
  i = j;
443
443
  continue;
444
444
  }
@@ -3,6 +3,12 @@ import { type AccountParam, type ErrorDef, type FieldType, type Helper, type Str
3
3
  import { type Value, type Ref, type CpiAcct, type CpiProgram, type Closure } from "./shared.js";
4
4
  import { ExpressionEmitter } from "./expressions.js";
5
5
  export declare abstract class CallEmitter extends ExpressionEmitter {
6
+ /**
7
+ * Closing an account of this program (`close`, `CloseTo<…>`): TS_CLOSE with the smallest size the account was
8
+ * checked to hold when it loaded (its discriminator and the struct's empty size, or a @layout borsh struct's smallest
9
+ * Borsh form). From TS_ZERO_RUN_MIN bytes on its data is zeroed by the memset syscall; below, by stores as before.
10
+ */
11
+ protected closeCall(a: AccountParam, dest: string): string;
6
12
  protected call(node: ts.CallExpression, topLevel: boolean): Value | undefined;
7
13
  /** "unsupported call" naming the callee, with the TypeSOL form of common JavaScript calls. */
8
14
  private unsupportedCall;
@@ -1,10 +1,10 @@
1
1
  import ts from "typescript";
2
2
  import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf, typesolName } from "../analyze.js";
3
- import { borshIdentical, borshNativeStructUnsupported } from "./borsh.js";
3
+ import { borshIdentical, borshMinSize, borshNativeStructUnsupported } from "./borsh.js";
4
4
  import { ANCHOR_ERRORS } from "../anchor-errors.js";
5
5
  import { decodeAddress } from "../../keys.js";
6
6
  import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
7
- import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, passedByPointer, unreachableArg, } from "./shared.js";
7
+ import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, passedByPointer, unreachableArg, fitSuffix, } from "./shared.js";
8
8
  import { ExpressionEmitter } from "./expressions.js";
9
9
  /**
10
10
  * Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
@@ -42,6 +42,19 @@ const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "
42
42
  /** The byte builders of a FixedVec<u8, N> (byteListMethod). */
43
43
  const BYTE_METHODS = new Set(["pushLE", "pushKey", "pushBorsh", "setLE", "truncate"]);
44
44
  export class CallEmitter extends ExpressionEmitter {
45
+ /**
46
+ * Closing an account of this program (`close`, `CloseTo<…>`): TS_CLOSE with the smallest size the account was
47
+ * checked to hold when it loaded (its discriminator and the struct's empty size, or a @layout borsh struct's smallest
48
+ * Borsh form). From TS_ZERO_RUN_MIN bytes on its data is zeroed by the memset syscall; below, by stores as before.
49
+ */
50
+ closeCall(a, dest) {
51
+ const k = a.kind;
52
+ if (k.kind !== "account" || !k.struct)
53
+ return `ts_close(a_${a.name}, ${dest})`;
54
+ const s = k.struct;
55
+ const min = s.layout === "borsh" ? String(s.accountDiscriminator.length + borshMinSize(s, this.model)) : `${s.accountDiscriminator.length} + ${emptySizeC(s)}`;
56
+ return `TS_CLOSE(a_${a.name}, ${dest}, ${min})`;
57
+ }
45
58
  call(node, topLevel) {
46
59
  const callee = node.expression;
47
60
  const args = node.arguments;
@@ -78,10 +91,13 @@ export class CallEmitter extends ExpressionEmitter {
78
91
  case "require": {
79
92
  if (args.length !== 2)
80
93
  this.fail(node, "require(condition, error) takes two arguments");
81
- const cond = this.expect(this.expr(args[0], BOOL), BOOL, args[0]);
94
+ let cond = this.expect(this.expr(args[0], BOOL), BOOL, args[0]);
82
95
  if (!this.namesError(args[1])) {
83
96
  // A code computed at run time (a helper that returns its error as a value): u32, the program error it names.
97
+ // The condition is evaluated first, as JS does: held when computing the code runs code that may change it.
98
+ const mark = this.lines.length;
84
99
  const v = this.expr(args[1], U32);
100
+ cond = this.settle(cond, mark);
85
101
  if (v.type.kind === "string")
86
102
  this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
87
103
  const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
@@ -122,12 +138,13 @@ export class CallEmitter extends ExpressionEmitter {
122
138
  if (args.length > 2 || args.some((a, i) => !(i === 0 && silent) && text(a) === undefined))
123
139
  this.fail(node, 'panic() takes an optional message (or null to log nothing) and an optional "file:line:column" location: string literals or string constants');
124
140
  const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
125
- if (silent && this.panicStyle())
141
+ const style = this.panicStyle();
142
+ if (silent && (style === "solana-1.14" || style === "solana-1.18"))
126
143
  this.fail(args[0], "under PANIC_STYLE a panic logs its message, as solana_program's panic handler always does: pass the message");
127
144
  // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"), or the panic line
128
145
  // logs: the given one, as a ported program's panic reports it, else this source line (with its column under
129
- // PANIC_STYLE, as Rust always gives one).
130
- const at = args.length > 1 ? text(args[1]) : this.panicStyle() ? this.locationWithColumn(node) : this.location(node);
146
+ // PANIC_STYLE, as Rust always gives one). Under "pinocchio" only its file is logged (a bare file is accepted).
147
+ const at = args.length > 1 ? text(args[1]) : style ? this.locationWithColumn(node) : this.location(node);
131
148
  for (const l of this.panicC(msg, at))
132
149
  this.line(l);
133
150
  return undefined;
@@ -224,7 +241,7 @@ export class CallEmitter extends ExpressionEmitter {
224
241
  const b = this.tmp("bump");
225
242
  this.line(`uint8_t ${b} = ${bump.c};`);
226
243
  this.line(`${seeds.name}[${seeds.count}] = (SolSignerSeed){&${b}, 1};`);
227
- this.line(`TS_TRY(ts_require_pda(a_${a.name}, ${seeds.name}, ${seeds.count + 1}, params->program_id));`);
244
+ this.line(`TS_TRY(ts_require_pda${fitSuffix(seeds)}(a_${a.name}, ${seeds.name}, ${seeds.count + 1}, params->program_id));`);
228
245
  return undefined;
229
246
  }
230
247
  case "close": {
@@ -242,7 +259,7 @@ export class CallEmitter extends ExpressionEmitter {
242
259
  else if (a === d)
243
260
  this.fail(args[1], "the destination is the account being closed; name another writable account");
244
261
  this.assertNotUsedAfterClose(a, node);
245
- this.line(`TS_TRY(ts_close(a_${a.name}, a_${d.name}));`);
262
+ this.line(`TS_TRY(${this.closeCall(a, `a_${d.name}`)});`);
246
263
  this.forgetOwners();
247
264
  return undefined;
248
265
  }
@@ -423,7 +440,13 @@ export class CallEmitter extends ExpressionEmitter {
423
440
  const payer = this.accountParam(args[2], "the payer");
424
441
  if (payer.kind.kind !== "signer" || !payer.kind.mut)
425
442
  this.fail(args[2], "the payer must be a Mut<Signer>");
426
- const min = struct ? `8 + sizeof(TSS_${struct.name})` : "0";
443
+ // The smallest size the account may take: its discriminator and the struct, or for a @layout borsh struct its
444
+ // smallest Borsh form (as its load checks); the value written back at the end must still fit (3004 if not).
445
+ const min = !struct
446
+ ? "0"
447
+ : struct.layout === "borsh"
448
+ ? String(struct.accountDiscriminator.length + borshMinSize(struct, this.model))
449
+ : `${struct.accountDiscriminator.length} + sizeof(TSS_${struct.name})`;
427
450
  this.line(`TS_TRY(ts_realloc(params, a_${payer.name}, a_${acct.name}, ${size.c}, entry_${acct.name}, ${min}));`);
428
451
  return undefined;
429
452
  }
@@ -648,7 +671,7 @@ export class CallEmitter extends ExpressionEmitter {
648
671
  const t = this.tmp("pda");
649
672
  const b = this.tmp("bump");
650
673
  this.line(`SolPubkey ${t}; uint8_t ${b};`);
651
- this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
674
+ this.line(`if (ts_find_pda${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
652
675
  return { c: `((uint64_t)${b})`, type: { kind: "int", name: "u8" } };
653
676
  }
654
677
  case "initAccount": {
@@ -659,6 +682,8 @@ export class CallEmitter extends ExpressionEmitter {
659
682
  const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
660
683
  if (!s || s.size === undefined || s.vec || s.layout === "borsh")
661
684
  this.fail(node, "initAccount<T>(account) takes a fixed-layout account struct of this program (no growable Vec, not @layout borsh)");
685
+ if (s.accountDiscriminator.length !== 8)
686
+ this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: it is another program's account`);
662
687
  if (args.length !== 1)
663
688
  this.fail(node, "initAccount<T>(account) takes one account");
664
689
  let h = this.handle(args[0]);
@@ -682,7 +707,7 @@ export class CallEmitter extends ExpressionEmitter {
682
707
  const t = this.tmp("cpa");
683
708
  this.model.options.set("pubkey", PUBKEY);
684
709
  this.line(`${optC(PUBKEY)} ${t};`);
685
- this.line(`${t}.some = ts_create_pda_address(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
710
+ this.line(`${t}.some = ts_create_pda_address${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
686
711
  return { c: t, type: { kind: "option", inner: PUBKEY } };
687
712
  }
688
713
  case "logBase64": {
@@ -700,6 +725,8 @@ export class CallEmitter extends ExpressionEmitter {
700
725
  this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
701
726
  return undefined;
702
727
  }
728
+ case "getReturnData":
729
+ this.fail(node, "bind both results where it is called: const [program, data] = getReturnData()");
703
730
  case "findProgramAddressWithBump":
704
731
  this.fail(node, "bind both results where it is called: const [address, bump] = findProgramAddressWithBump(seeds, program)");
705
732
  case "findProgramAddress": {
@@ -711,7 +738,7 @@ export class CallEmitter extends ExpressionEmitter {
711
738
  const t = this.tmp("pda");
712
739
  const b = this.tmp("bump");
713
740
  this.line(`SolPubkey ${t}; uint8_t ${b};`);
714
- this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
741
+ this.line(`if (ts_find_pda${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
715
742
  return { c: `(&${t})`, type: PUBKEY };
716
743
  }
717
744
  case "metadataAddress":
@@ -890,12 +917,44 @@ export class CallEmitter extends ExpressionEmitter {
890
917
  this.line(`ts_memzero_bulk(${a}->data + ${o}, ${n});`);
891
918
  return undefined;
892
919
  }
920
+ case "copyData": {
921
+ // A native program's `data.copy_within(from..from + length, to)` (or a copy of a struct out of the account and
922
+ // back in at another offset): the memmove syscall, about constant compute units whatever the length, where a
923
+ // whole-struct assignment moves words one by one. Overlapping ranges are allowed.
924
+ if (args.length !== 4)
925
+ this.fail(node, "copyData(account, from, to, length) takes an account, two byte offsets and a length");
926
+ // The length does not change: views of the account made before stay valid (they read the copied bytes).
927
+ let a = this.handle(args[0]);
928
+ if (a) {
929
+ if (!this.nativeAccountWrites())
930
+ this.line(`TS_TRY(ts_check_writable(${a}));`);
931
+ }
932
+ else {
933
+ const acct = this.accountParam(args[0], "copyData's account");
934
+ if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
935
+ this.fail(args[0], "copyData needs a Mut<AccountInfo> parameter or a remaining account");
936
+ a = `a_${acct.name}`;
937
+ }
938
+ const from = this.expect(this.expr(args[1], U64), U64, args[1]);
939
+ const f = this.tmp("from");
940
+ this.line(`uint64_t ${f} = ${from.c};`);
941
+ const to = this.expect(this.expr(args[2], U64), U64, args[2]);
942
+ const t = this.tmp("to");
943
+ this.line(`uint64_t ${t} = ${to.c};`);
944
+ const len = this.expect(this.expr(args[3], U64), U64, args[3]);
945
+ const n = this.tmp("len");
946
+ this.line(`uint64_t ${n} = ${len.c};`);
947
+ this.line(`if (${f} > ${a}->data_len || ${a}->data_len - ${f} < ${n} || ${t} > ${a}->data_len || ${a}->data_len - ${t} < ${n}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: copy past the end of the account data");`);
948
+ this.line(`ts_memmove_bulk(${a}->data + ${t}, ${a}->data + ${f}, ${n});`);
949
+ return undefined;
950
+ }
893
951
  case "log64": {
894
952
  // Rust's `sol_log_64(a, b, c, d, e)`: the runtime writes "Program log: 0x<a>, 0x<b>, 0x<c>, 0x<d>, 0x<e>" (hex).
895
953
  if (args.length !== 5)
896
954
  this.fail(node, "log64(a, b, c, d, e) takes five u64 values");
897
- const vs = args.map((a) => this.expect(this.expr(a, U64), U64, a).c);
898
- const ts_ = vs.map((v) => {
955
+ // Left to right, each value held before the next argument is lowered (a later one may run code that changes it).
956
+ const ts_ = args.map((a) => {
957
+ const v = this.expect(this.expr(a, U64), U64, a).c;
899
958
  const t = this.tmp("l64");
900
959
  this.line(`uint64_t ${t} = ${v};`);
901
960
  return t;
@@ -1163,6 +1222,15 @@ export class CallEmitter extends ExpressionEmitter {
1163
1222
  const hint = Object.hasOwn(hints, text) ? hints[text] : undefined;
1164
1223
  if (hint)
1165
1224
  return `unsupported call: ${text}; use ${hint}`;
1225
+ let bare = callee;
1226
+ while (ts.isParenthesizedExpression(bare))
1227
+ bare = bare.expression;
1228
+ if (ts.isArrowFunction(bare) || ts.isFunctionExpression(bare))
1229
+ return "a function called where it is written is not supported: bind it first (const f = (…) => …) and call f(…)";
1230
+ if (ts.isIdentifier(callee) && this.model.instructions.some((ix) => ix.node.name?.text === callee.text))
1231
+ return `${callee.text} is an instruction: one instruction cannot call another; move the shared code into a helper (a function that is not exported) and call it from both`;
1232
+ if (ts.isPropertyAccessExpression(callee) && ["call", "apply", "bind"].includes(callee.name.text) && !this.accountAt(callee.expression))
1233
+ return `${text}(…) is not supported: functions take what they use as parameters (there is no this); call ${callee.expression.getText()}(…) with them`;
1166
1234
  if (ts.isPropertyAccessExpression(callee) && this.accountAt(callee.expression))
1167
1235
  return `unsupported call: the account ${callee.expression.getText()} has no method ${callee.name.text}`;
1168
1236
  return `unsupported call: ${text.length > 60 ? `${text.slice(0, 57)}…` : text}`;
@@ -1183,7 +1251,7 @@ export class CallEmitter extends ExpressionEmitter {
1183
1251
  if (!st) {
1184
1252
  this.line(`${fieldC(vt.elem)} ${t};`);
1185
1253
  this.writeAggregate({ lv: t, type: vt.elem, writable: true }, valueNode);
1186
- return (el) => this.line(`ts_memcpy(&${el.lv}, &${t}, sizeof(${t}));`);
1254
+ return (el) => this.line(`TS_MEMCPY(&${el.lv}, &${t}, sizeof(${t}));`);
1187
1255
  }
1188
1256
  const val = this.ownedString(this.expect(this.expr(valueNode, st), st, valueNode));
1189
1257
  if (st.kind === "pubkey")
@@ -2401,7 +2469,7 @@ export class CallEmitter extends ExpressionEmitter {
2401
2469
  this.writeAggregate({ lv: `(*${tmp})`, type: { kind: "struct", name: To }, writable: true }, node.arguments[1]);
2402
2470
  this.line(`TS_TRY(ts_resize(params, a_${payer.name}, a_${a.name}, 8 + sizeof(TSS_${To}), entry_${a.name}));`);
2403
2471
  this.line(`ts_memcpy(a_${a.name}->data, TS_DISC_${To}, 8);`);
2404
- this.line(`ts_memcpy(a_${a.name}->data + 8, ${tmp}, sizeof(TSS_${To}));`);
2472
+ this.line(`TS_MEMCPY(a_${a.name}->data + 8, ${tmp}, sizeof(TSS_${To}));`);
2405
2473
  this.line(`TSS_${To} *dt_${a.name} = (TSS_${To} *)(a_${a.name}->data + 8);`);
2406
2474
  this.line(`(void)dt_${a.name};`);
2407
2475
  this.created.add(a.name);
@@ -2672,6 +2740,18 @@ export class CallEmitter extends ExpressionEmitter {
2672
2740
  }
2673
2741
  const t = this.tmp();
2674
2742
  if (h.returns.kind === "struct") {
2743
+ const S = this.model.structs.get(h.returns.name);
2744
+ // To fit the stack, an instruction's result may live on the heap instead, one allocation per call site taken
2745
+ // when first reached (as a /** @heap */ local's), so a call in a loop reuses it as it reuses the stack slot.
2746
+ const decl = node.parent && ts.isParenthesizedExpression(node.parent) ? node.parent.parent : node.parent;
2747
+ const stackTag = !!decl && ts.isVariableDeclaration(decl) && this.stackTagged(decl);
2748
+ if (S?.size !== undefined && this.autoHeap(node, { name: `the result of ${h.display}()`, c: t, bytes: S.size, stack: stackTag })) {
2749
+ const sname = h.returns.name;
2750
+ this.hoistLazy(t, (n) => `TSS_${sname} *${n}`);
2751
+ this.line(`if (${t} == NULL) TS_TRY(ts_alloc(sizeof(TSS_${h.returns.name}), (uint8_t **)&${t}));`);
2752
+ this.line(`TS_TRY(fn_${h.name}(${[...args, t].join(", ")}));`);
2753
+ return { c: t, type: { kind: "structRef", struct: h.returns.name, writable: true } };
2754
+ }
2675
2755
  // The result lives in a local the caller owns: a reference to it reads and copies like any struct. Declared at
2676
2756
  // the top of the function, so a reference taken inside a block (a ternary's branch) stays valid after it.
2677
2757
  this.hoisted.push(` TSS_${h.returns.name} ${t};`);
@@ -2763,7 +2843,7 @@ export class CallEmitter extends ExpressionEmitter {
2763
2843
  if (r && r.type.kind === "option" && sameType(r.type.inner, want))
2764
2844
  r = this.someValue(r);
2765
2845
  if (!r || !sameType(r.type, want))
2766
- this.fail(n, `expected a ${typeName(want)}`);
2846
+ this.fail(n, `expected a ${typeName(want)}${this.parentNote(r?.type, want, n)}`);
2767
2847
  return this.snapshotPlace(r.lv, want, h, n);
2768
2848
  }
2769
2849
  case "dataEnumArg": {
@@ -3012,7 +3092,7 @@ export class CallEmitter extends ExpressionEmitter {
3012
3092
  const t = this.tmp("argc");
3013
3093
  this.hoistLazy(t, (n) => (type.kind === "array" ? storageDecl(type, `(*${n})`) : `${fieldC(type)} *${n}`));
3014
3094
  this.line(`if (${t} == NULL) TS_TRY(ts_alloc(${n}, (uint8_t **)&${t}));`);
3015
- this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
3095
+ this.line(`TS_MEMCPY(${t}, &${lv}, ${n});`);
3016
3096
  return t;
3017
3097
  }
3018
3098
  /**
@@ -9,11 +9,14 @@ export declare abstract class CpiCoreEmitter extends ViewEmitter {
9
9
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
10
10
  * `withBump`: the list ends with its bump (signer seeds, createProgramAddress), so it may hold MAX_SEEDS entries;
11
11
  * otherwise the derivation adds the bump, and the list holds one fewer.
12
+ * `fit`: every seed's length is known here (at most 32 bytes; only a `string` value's is not), so a derivation can
13
+ * leave out the run-time check of the limits (the count is checked here in every case).
12
14
  */
13
15
  protected seeds(node: ts.Expression, extra: number, bound?: boolean, withBump?: boolean): {
14
16
  name: string;
15
17
  count: number;
16
18
  idl: IdlSeed[] | undefined;
19
+ fit: boolean;
17
20
  };
18
21
  /**
19
22
  * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
@@ -11,6 +11,8 @@ export class CpiCoreEmitter extends ViewEmitter {
11
11
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
12
12
  * `withBump`: the list ends with its bump (signer seeds, createProgramAddress), so it may hold MAX_SEEDS entries;
13
13
  * otherwise the derivation adds the bump, and the list holds one fewer.
14
+ * `fit`: every seed's length is known here (at most 32 bytes; only a `string` value's is not), so a derivation can
15
+ * leave out the run-time check of the limits (the count is checked here in every case).
14
16
  */
15
17
  seeds(node, extra, bound = false, withBump = false) {
16
18
  if (!ts.isArrayLiteralExpression(node))
@@ -21,6 +23,7 @@ export class CpiCoreEmitter extends ViewEmitter {
21
23
  this.fail(node, `at most ${MAX_SEEDS - 1} seeds: the bump the derivation adds makes ${MAX_SEEDS}, Solana's limit`);
22
24
  const parts = [];
23
25
  let idl = [];
26
+ let fit = true;
24
27
  // The array points at its seeds, which are read when the CPI runs. Seeds that are not constants are copied when
25
28
  // the list is written, as JS reads them then, unless nothing can run between the list and the CPI that reads it:
26
29
  // no calls or writes among the seeds, nor in the other arguments of the call consuming the list (evaluated before
@@ -89,6 +92,9 @@ export class CpiCoreEmitter extends ViewEmitter {
89
92
  const t = this.tmp("seed");
90
93
  this.line(`TS_Str ${t} = ${this.ownedString(v).c};`);
91
94
  parts.push(`{${t}.ptr, ${t}.len}`);
95
+ // A string constant's length is known here; any other string's only at run time.
96
+ if (v.stringLiteral === undefined || Buffer.byteLength(v.stringLiteral, "utf8") > 32)
97
+ fit = false;
92
98
  }
93
99
  else if (v.type.kind === "int") {
94
100
  const typed = v.literal !== undefined ? this.literal(v.literal, U64, el) : v;
@@ -113,13 +119,13 @@ export class CpiCoreEmitter extends ViewEmitter {
113
119
  const reusable = extra === 0 && parts.length > 0 && this.lines.length === mark;
114
120
  const known = reusable ? this.seedArrays.get(key) : undefined;
115
121
  if (known && this.scopes.includes(known.scope) && this.lines[known.at]?.trim() === known.text)
116
- return { name: known.name, count: parts.length, idl };
122
+ return { name: known.name, count: parts.length, idl, fit };
117
123
  const name = this.tmp("seeds");
118
124
  const slots = parts.length + extra;
119
125
  this.line(`SolSignerSeed ${name}[${Math.max(slots, 1)}] = {${parts.join(", ")}};`);
120
126
  if (reusable)
121
127
  this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
122
- return { name, count: parts.length, idl };
128
+ return { name, count: parts.length, idl, fit };
123
129
  }
124
130
  /**
125
131
  * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
@@ -330,7 +336,7 @@ export class CpiCoreEmitter extends ViewEmitter {
330
336
  fixed += bytes;
331
337
  if (dynamic)
332
338
  this.line(`if (${len} + ${n} > ${max}) TS_FAIL(${errorCode}, "TypeSOL: ${what} too large");`);
333
- this.line(`ts_memcpy(${buf} + ${len}, ${src}, ${n});`);
339
+ this.line(`${bytes === undefined ? "ts_memcpy" : "TS_MEMCPY"}(${buf} + ${len}, ${src}, ${n});`);
334
340
  this.line(`${len} += ${n};`);
335
341
  };
336
342
  const finish = (at) => {
@@ -542,7 +548,7 @@ export class CpiCoreEmitter extends ViewEmitter {
542
548
  this.line(`uint64_t ${at} = ${count};`);
543
549
  write((src, n) => {
544
550
  this.line(`if (${n} > ${cap} - ${at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: ${method}() past the FixedVec's room");`);
545
- this.line(`ts_memcpy(${bytes} + ${at}, ${src}, ${n});`);
551
+ this.line(`${/^\d+$/.test(n) ? "TS_MEMCPY" : "ts_memcpy"}(${bytes} + ${at}, ${src}, ${n});`);
546
552
  this.line(`${at} += ${n};`);
547
553
  }, { dst: bytes, cap: String(cap), at });
548
554
  this.line(`${info.len} = (uint32_t)${at};`);
@@ -603,7 +609,7 @@ export class CpiCoreEmitter extends ViewEmitter {
603
609
  const t = this.tmp("bv");
604
610
  this.line(`${fieldC(type)} ${t};`);
605
611
  if (type.kind === "struct")
606
- this.line(`ts_memzero(&${t}, sizeof(${t}));`);
612
+ this.line(`TS_ZERO_LOCAL(&${t}, sizeof(${t}));`);
607
613
  this.writeAggregate({ lv: t, type, writable: true }, arg, true);
608
614
  r = { lv: t, type, writable: true };
609
615
  }
@@ -264,7 +264,7 @@ export class CpiEmitter extends MetaplexEmitter {
264
264
  else if (ts.isShorthandPropertyAssignment(p))
265
265
  given.set(p.name.text, p.name);
266
266
  else
267
- this.fail(p, "use plain `field: value` entries");
267
+ this.fail(p, ts.isSpreadAssignment(p) ? "spread (...) is not supported in emit<T>(…): write each field, field: value" : "use plain `field: value` entries");
268
268
  }
269
269
  for (const k of given.keys())
270
270
  if (!s.fields.some((f) => f.name === k))
@@ -305,7 +305,9 @@ export class CpiEmitter extends MetaplexEmitter {
305
305
  else if (ts.isShorthandPropertyAssignment(p))
306
306
  fields.set(p.name.text, p.name);
307
307
  else
308
- this.fail(p, "use plain `field: value` entries");
308
+ this.fail(p, ts.isSpreadAssignment(p)
309
+ ? "spread (...) is not supported in an event's nested struct: write each field, field: value"
310
+ : "use plain `field: value` entries");
309
311
  }
310
312
  for (const k of fields.keys())
311
313
  if (!sd.fields.some((x) => x.name === k))
@@ -389,7 +391,7 @@ export class CpiEmitter extends MetaplexEmitter {
389
391
  if (!src || src.type.kind !== "dataEnum" || src.type.name !== enumName)
390
392
  this.fail(e, `expected a ${enumName}`);
391
393
  this.line(`TSE_${enumName} ${t};`);
392
- this.line(`ts_memcpy(&${t}, &${src.lv}, sizeof(${t}));`);
394
+ this.line(`TS_MEMCPY(&${t}, &${src.lv}, sizeof(${t}));`);
393
395
  return (put) => this.serializeDataEnumLv(t, enumName, put);
394
396
  }
395
397
  else if (vt) {
@@ -415,7 +417,7 @@ export class CpiEmitter extends MetaplexEmitter {
415
417
  this.fail(e, `expected a ${typeName(f.type)} from account data`);
416
418
  const n = this.fieldBytes(f.type);
417
419
  this.line(`uint8_t ${t}[${n}];`);
418
- this.line(`ts_memcpy(${t}, &${src.lv}, ${n});`);
420
+ this.line(`TS_MEMCPY(${t}, &${src.lv}, ${n});`);
419
421
  return (put) => put(t, String(n), n);
420
422
  }
421
423
  };