@typesol/cli 0.49.0 → 0.50.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 (56) hide show
  1. package/CHANGELOG.md +397 -0
  2. package/NOTICE +9 -0
  3. package/README.md +25 -8
  4. package/SECURITY.md +4 -3
  5. package/dist/compiler/analyze.d.ts +2 -0
  6. package/dist/compiler/analyze.js +7 -1
  7. package/dist/compiler/emit/base.d.ts +4 -3
  8. package/dist/compiler/emit/base.js +9 -3
  9. package/dist/compiler/emit/borsh.js +8 -8
  10. package/dist/compiler/emit/calls.d.ts +6 -0
  11. package/dist/compiler/emit/calls.js +71 -12
  12. package/dist/compiler/emit/cpi-core.js +3 -3
  13. package/dist/compiler/emit/cpi.js +2 -2
  14. package/dist/compiler/emit/expressions.d.ts +1 -0
  15. package/dist/compiler/emit/expressions.js +12 -0
  16. package/dist/compiler/emit/function.js +12 -8
  17. package/dist/compiler/emit/program.js +8 -2
  18. package/dist/compiler/emit/rbtree.js +1 -1
  19. package/dist/compiler/emit/shared.d.ts +12 -2
  20. package/dist/compiler/emit/shared.js +26 -6
  21. package/dist/compiler/emit/statements.d.ts +8 -1
  22. package/dist/compiler/emit/statements.js +53 -5
  23. package/dist/compiler/emit/storage.js +12 -10
  24. package/dist/compiler/emit/views.js +1 -1
  25. package/dist/compiler/index.d.ts +15 -1
  26. package/dist/compiler/index.js +50 -9
  27. package/dist/keys.d.ts +12 -1
  28. package/dist/keys.js +57 -7
  29. package/dist/workspace.d.ts +8 -0
  30. package/dist/workspace.js +90 -15
  31. package/docker/deps/0.50.0.lock.json +1206 -0
  32. package/docs/architecture.md +1 -1
  33. package/docs/audit.md +13 -12
  34. package/docs/case-study-jito-mev.md +14 -14
  35. package/docs/case-study-marginfi.md +127 -127
  36. package/docs/case-study-multisig.md +16 -4
  37. package/docs/case-study-raydium-clmm.md +44 -28
  38. package/docs/case-study-raydium-cp-swap.md +18 -18
  39. package/docs/cli.md +4 -3
  40. package/docs/language-accounts.md +16 -10
  41. package/docs/language-basics.md +4 -1
  42. package/docs/language-builtins.md +4 -2
  43. package/docs/language-cpi.md +34 -0
  44. package/docs/language-native.md +50 -4
  45. package/docs/language-statements.md +2 -1
  46. package/docs/language-types.md +13 -3
  47. package/docs/runtime.md +19 -2
  48. package/docs/security-model.md +4 -3
  49. package/docs/stability.md +5 -4
  50. package/docs/testing.md +6 -2
  51. package/lib/typesol.d.ts +25 -3
  52. package/llms-full.txt +136 -31
  53. package/package.json +1 -1
  54. package/releases/0.49.0.json +857 -0
  55. package/runtime/typesol_builtins.c +47 -2
  56. package/runtime/typesol_rt.h +129 -3
@@ -422,12 +422,13 @@ export class EmitterBase {
422
422
  * `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: a Rust panic logs what that solana-program's panic handler
423
423
  * logs and then aborts, so the runtime reports "SBF program panicked". rustc before 1.73 (solana-program 1.14 to
424
424
  * 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.
425
+ * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. `"pinocchio"`: pinocchio's
426
+ * `default_panic_handler!` hook logs the location's file alone, then "** PANICKED **", and std aborts. By default it
427
+ * logs the message and calls sol_panic_ with the location.
427
428
  */
428
429
  panicStyle() {
429
430
  const v = this.model.constants.get("PANIC_STYLE")?.value;
430
- return v === "solana-1.14" || v === "solana-1.18" ? v : undefined;
431
+ return v === "solana-1.14" || v === "solana-1.18" || v === "pinocchio" ? v : undefined;
431
432
  }
432
433
  /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
433
434
  panicC(message, location) {
@@ -436,6 +437,11 @@ export class EmitterBase {
436
437
  return [`sol_log(${cString(`panicked at '${message}', ${location}`)});`, `abort();`, `__builtin_unreachable();`];
437
438
  if (style === "solana-1.18")
438
439
  return [`sol_log(${cString(`panicked at ${location}:\n${message}`)});`, `abort();`, `__builtin_unreachable();`];
440
+ if (style === "pinocchio") {
441
+ // `location.file()` verbatim: the location without its ":line" / ":line:column" (a bare file is kept whole).
442
+ const file = location.replace(/:\d+(?::\d+)?$/, "");
443
+ return [`ts_panic_file(${cString(file)}, ${Buffer.byteLength(file)});`];
444
+ }
439
445
  const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(location);
440
446
  const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [location, "0", "0"];
441
447
  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,6 +1,6 @@
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";
@@ -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;
@@ -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
  }
@@ -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]);
@@ -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": {
@@ -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;
@@ -1183,7 +1242,7 @@ export class CallEmitter extends ExpressionEmitter {
1183
1242
  if (!st) {
1184
1243
  this.line(`${fieldC(vt.elem)} ${t};`);
1185
1244
  this.writeAggregate({ lv: t, type: vt.elem, writable: true }, valueNode);
1186
- return (el) => this.line(`ts_memcpy(&${el.lv}, &${t}, sizeof(${t}));`);
1245
+ return (el) => this.line(`TS_MEMCPY(&${el.lv}, &${t}, sizeof(${t}));`);
1187
1246
  }
1188
1247
  const val = this.ownedString(this.expect(this.expr(valueNode, st), st, valueNode));
1189
1248
  if (st.kind === "pubkey")
@@ -2401,7 +2460,7 @@ export class CallEmitter extends ExpressionEmitter {
2401
2460
  this.writeAggregate({ lv: `(*${tmp})`, type: { kind: "struct", name: To }, writable: true }, node.arguments[1]);
2402
2461
  this.line(`TS_TRY(ts_resize(params, a_${payer.name}, a_${a.name}, 8 + sizeof(TSS_${To}), entry_${a.name}));`);
2403
2462
  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}));`);
2463
+ this.line(`TS_MEMCPY(a_${a.name}->data + 8, ${tmp}, sizeof(TSS_${To}));`);
2405
2464
  this.line(`TSS_${To} *dt_${a.name} = (TSS_${To} *)(a_${a.name}->data + 8);`);
2406
2465
  this.line(`(void)dt_${a.name};`);
2407
2466
  this.created.add(a.name);
@@ -3012,7 +3071,7 @@ export class CallEmitter extends ExpressionEmitter {
3012
3071
  const t = this.tmp("argc");
3013
3072
  this.hoistLazy(t, (n) => (type.kind === "array" ? storageDecl(type, `(*${n})`) : `${fieldC(type)} *${n}`));
3014
3073
  this.line(`if (${t} == NULL) TS_TRY(ts_alloc(${n}, (uint8_t **)&${t}));`);
3015
- this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
3074
+ this.line(`TS_MEMCPY(${t}, &${lv}, ${n});`);
3016
3075
  return t;
3017
3076
  }
3018
3077
  /**
@@ -330,7 +330,7 @@ export class CpiCoreEmitter extends ViewEmitter {
330
330
  fixed += bytes;
331
331
  if (dynamic)
332
332
  this.line(`if (${len} + ${n} > ${max}) TS_FAIL(${errorCode}, "TypeSOL: ${what} too large");`);
333
- this.line(`ts_memcpy(${buf} + ${len}, ${src}, ${n});`);
333
+ this.line(`${bytes === undefined ? "ts_memcpy" : "TS_MEMCPY"}(${buf} + ${len}, ${src}, ${n});`);
334
334
  this.line(`${len} += ${n};`);
335
335
  };
336
336
  const finish = (at) => {
@@ -542,7 +542,7 @@ export class CpiCoreEmitter extends ViewEmitter {
542
542
  this.line(`uint64_t ${at} = ${count};`);
543
543
  write((src, n) => {
544
544
  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});`);
545
+ this.line(`${/^\d+$/.test(n) ? "TS_MEMCPY" : "ts_memcpy"}(${bytes} + ${at}, ${src}, ${n});`);
546
546
  this.line(`${at} += ${n};`);
547
547
  }, { dst: bytes, cap: String(cap), at });
548
548
  this.line(`${info.len} = (uint32_t)${at};`);
@@ -603,7 +603,7 @@ export class CpiCoreEmitter extends ViewEmitter {
603
603
  const t = this.tmp("bv");
604
604
  this.line(`${fieldC(type)} ${t};`);
605
605
  if (type.kind === "struct")
606
- this.line(`ts_memzero(&${t}, sizeof(${t}));`);
606
+ this.line(`TS_ZERO_LOCAL(&${t}, sizeof(${t}));`);
607
607
  this.writeAggregate({ lv: t, type, writable: true }, arg, true);
608
608
  r = { lv: t, type, writable: true };
609
609
  }
@@ -389,7 +389,7 @@ export class CpiEmitter extends MetaplexEmitter {
389
389
  if (!src || src.type.kind !== "dataEnum" || src.type.name !== enumName)
390
390
  this.fail(e, `expected a ${enumName}`);
391
391
  this.line(`TSE_${enumName} ${t};`);
392
- this.line(`ts_memcpy(&${t}, &${src.lv}, sizeof(${t}));`);
392
+ this.line(`TS_MEMCPY(&${t}, &${src.lv}, sizeof(${t}));`);
393
393
  return (put) => this.serializeDataEnumLv(t, enumName, put);
394
394
  }
395
395
  else if (vt) {
@@ -415,7 +415,7 @@ export class CpiEmitter extends MetaplexEmitter {
415
415
  this.fail(e, `expected a ${typeName(f.type)} from account data`);
416
416
  const n = this.fieldBytes(f.type);
417
417
  this.line(`uint8_t ${t}[${n}];`);
418
- this.line(`ts_memcpy(${t}, &${src.lv}, ${n});`);
418
+ this.line(`TS_MEMCPY(${t}, &${src.lv}, ${n});`);
419
419
  return (put) => put(t, String(n), n);
420
420
  }
421
421
  };
@@ -86,6 +86,7 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
86
86
  * that overflows then would make the result overflow too). A negative exponent aborts, as JS throws a RangeError.
87
87
  */
88
88
  protected power(node: ts.BinaryExpression, hint?: ValueType): Value;
89
+ private powerOf;
89
90
  protected binary(node: ts.BinaryExpression, hint?: ValueType): Value;
90
91
  /** Checked integer arithmetic into a fresh temporary. */
91
92
  protected arith(op: ts.BinaryOperator, left: Value, right: Value, node: ts.Node): Value;
@@ -900,6 +900,18 @@ export class ExpressionEmitter extends StorageEmitter {
900
900
  const exp = this.expr(node.right);
901
901
  // JS reads the base first: if the exponent ran statements (a helper that changes it), use the value read before.
902
902
  base = this.settle(base, mark);
903
+ // Inside panicsAt the operands keep its location, but `**` itself keeps TypeSOL's failure (5100 on overflow):
904
+ // Rust's `pow` panics with other messages, so its multiplications do not take the panic.
905
+ const outer = this.panicAt;
906
+ this.panicAt = undefined;
907
+ try {
908
+ return this.powerOf(node, hint, base, exp);
909
+ }
910
+ finally {
911
+ this.panicAt = outer;
912
+ }
913
+ }
914
+ powerOf(node, hint, base, exp) {
903
915
  this.refuseF64(node, "**", base, exp);
904
916
  if (base.literal !== undefined)
905
917
  base = this.literal(base.literal, hint?.kind === "int" ? hint : U64, node.left);
@@ -64,7 +64,7 @@ export class FunctionEmitter extends StatementEmitter {
64
64
  const n = k.struct.accountDiscriminator.length;
65
65
  // A shorter discriminator (another program's zero-copy account): AccountLoader's checks with its length.
66
66
  if (n !== 8)
67
- head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
67
+ head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
68
68
  else
69
69
  head.push(k.struct.idlMeta?.serialization?.startsWith("bytemuck")
70
70
  ? ` TS_TRY(ts_check_loader_account(${v}, ${owner}, TS_DISC_${k.struct.name}, ${emptySizeC(k.struct)}));`
@@ -144,15 +144,18 @@ export class FunctionEmitter extends StatementEmitter {
144
144
  // unused slots start as zero: ts_unpack_* only writes what the Borsh bytes hold.
145
145
  const S = k.struct.name;
146
146
  head.push(` TSS_${S} *d_${a.name} = NULL;`, ` TS_TRY(ts_alloc(sizeof(TSS_${S}), (uint8_t **)&d_${a.name}));`);
147
+ // The Borsh bytes start after the discriminator, of whichever length the struct declares (the checks above
148
+ // ensured the account holds it and the smallest Borsh form after it).
149
+ const n = k.struct.accountDiscriminator.length;
147
150
  if (k.kind === "account")
148
- head.push(` TS_TRY(ts_unpack_${S}(${v}->data + 8, ${v}->data_len - 8, d_${a.name}, NULL));`);
151
+ head.push(` TS_TRY(ts_unpack_${S}(${v}->data + ${n}, ${v}->data_len - ${n}, d_${a.name}, NULL));`);
149
152
  }
150
153
  else if (k.kind === "account" || k.kind === "init" || k.kind === "zeroed" || k.kind === "initIfNeeded") {
151
154
  head.push(` TSS_${k.struct.name} *d_${a.name} = (TSS_${k.struct.name} *)(${v}->data + ${k.struct.accountDiscriminator.length});`);
152
155
  if (k.struct.vec) {
153
156
  head.push(` uint64_t entry_${a.name} = ${v}->data_len;`, ` (void)entry_${a.name};`);
154
157
  if (k.kind === "account")
155
- head.push(...vecLenCheck(k.struct, v, `d_${a.name}`));
158
+ head.push(...vecLenCheck(k.struct, v, `d_${a.name}`, " ", k.struct.accountDiscriminator.length));
156
159
  }
157
160
  }
158
161
  // realloc(x, …) needs the size the account had when the instruction started (the 10 KiB growth limit), as does
@@ -366,7 +369,7 @@ export class FunctionEmitter extends StatementEmitter {
366
369
  const ft = a.type.kind === "structRef" ? { kind: "struct", name: a.type.struct } : a.type.array;
367
370
  const size = this.fieldBytes(ft);
368
371
  need(String(size));
369
- head.push(` ${decl};`, ` TS_TRY(ts_alloc(${size}, (uint8_t **)&${v}));`, ` ts_memcpy(${v}, ${at}, ${size});`, ` off += ${size};`);
372
+ head.push(` ${decl};`, ` TS_TRY(ts_alloc(${size}, (uint8_t **)&${v}));`, ` TS_MEMCPY(${v}, ${at}, ${size});`, ` off += ${size};`);
370
373
  head.push(...this.validation(`(*${v})`, ft, " "));
371
374
  }
372
375
  else if (a.type.kind === "dataEnumArg") {
@@ -374,7 +377,7 @@ export class FunctionEmitter extends StatementEmitter {
374
377
  const e = this.model.dataEnums.get(a.type.name);
375
378
  const v = `arg_${a.name}__v`;
376
379
  need("1");
377
- head.push(` TSE_${e.name} ${v};`, ` ts_memzero(&${v}, sizeof(${v}));`, ` ${v}.tag = *(${at});`, ` off += 1;`);
380
+ head.push(` TSE_${e.name} ${v};`, ` TS_ZERO_LOCAL(&${v}, sizeof(${v}));`, ` ${v}.tag = *(${at});`, ` off += 1;`);
378
381
  head.push(` switch (${v}.tag) {`);
379
382
  e.variants.forEach((variant, i) => {
380
383
  head.push(` case ${i}: {`);
@@ -394,7 +397,7 @@ export class FunctionEmitter extends StatementEmitter {
394
397
  const lv = `${v}.v.${variant.name}.${f.name}`;
395
398
  const size = this.fieldBytes(f.type);
396
399
  head.push(` if (params->data_len < off + ${size}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: instruction data too short");`);
397
- head.push(` ts_memcpy(&${lv}, params->data + off, ${size});`, ` off += ${size};`);
400
+ head.push(` TS_MEMCPY(&${lv}, params->data + off, ${size});`, ` off += ${size};`);
398
401
  head.push(...this.validation(lv, f.type, " "));
399
402
  continue;
400
403
  }
@@ -549,14 +552,15 @@ export class FunctionEmitter extends StatementEmitter {
549
552
  .map((a) => {
550
553
  const v = `a_${a.name}`;
551
554
  const S = a.kind.struct.name;
552
- return `if (${a.optional ? `${v} != NULL && ` : ""}${v}->data_len >= 8 && ts_key_eq(&${v}->owner, params->program_id)) TS_TRY(ts_pack_${S}(d_${a.name}, ${v}->data + 8, ${v}->data_len - 8, NULL));`;
555
+ const n = a.kind.struct.accountDiscriminator.length;
556
+ return `if (${a.optional ? `${v} != NULL && ` : ""}${v}->data_len >= ${n} && ts_key_eq(&${v}->owner, params->program_id)) TS_TRY(ts_pack_${S}(d_${a.name}, ${v}->data + ${n}, ${v}->data_len - ${n}, NULL));`;
553
557
  });
554
558
  return [
555
559
  ...packs,
556
560
  ...this.ix.accounts
557
561
  .filter((a) => a.constraints.closeTo)
558
562
  .map((a) => {
559
- const line = `TS_TRY(ts_close(a_${a.name}, a_${a.constraints.closeTo}));`;
563
+ const line = `TS_TRY(${this.closeCall(a, `a_${a.constraints.closeTo}`)});`;
560
564
  const optional = this.optionalIn(line);
561
565
  return optional.length ? `if (${optional.map((n) => `a_${n} != NULL`).join(" && ")}) ${line}` : line;
562
566
  }),
@@ -61,10 +61,16 @@ export function emitProgram(analysis, opts = {}) {
61
61
  }
62
62
  // `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: panics log as that solana_program's panic handler does and
63
63
  // abort (read by the emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
64
+ // `"pinocchio"`: pinocchio's panic hook (the location's file, then "** PANICKED **", then abort), through one helper.
64
65
  const panicStyle = model.constants.get("PANIC_STYLE");
65
66
  if (panicStyle) {
66
- if (panicStyle.value !== "solana-1.14" && panicStyle.value !== "solana-1.18")
67
- reporter.error(analysis.sourceFile, 'PANIC_STYLE must be "solana-1.14" (panics log `panicked at \'<message>\', <file>:<line>:<col>` and abort, as programs built with solana-program 1.14 to 1.17 do) or "solana-1.18" (`panicked at <file>:<line>:<col>:` and the message on the next line, then abort, as solana-program 1.18\'s); leave it out for the default');
67
+ if (panicStyle.value !== "solana-1.14" && panicStyle.value !== "solana-1.18" && panicStyle.value !== "pinocchio")
68
+ reporter.error(analysis.sourceFile, 'PANIC_STYLE must be "solana-1.14" (panics log `panicked at \'<message>\', <file>:<line>:<col>` and abort, as programs built with solana-program 1.14 to 1.17 do), "solana-1.18" (`panicked at <file>:<line>:<col>:` and the message on the next line, then abort, as solana-program 1.18\'s) or "pinocchio" (the file alone, then `** PANICKED **`, then abort, as pinocchio\'s entrypoint! hook); leave it out for the default');
69
+ else if (panicStyle.value === "pinocchio") {
70
+ if (panicFlag?.value === true)
71
+ reporter.error(analysis.sourceFile, 'PANIC_ON_OVERFLOW cannot be used with PANIC_STYLE = "pinocchio": that panic hook logs the file the panic is in, which an overflow outside panicsAt does not have; wrap the arithmetic in panicsAt(location, …) instead');
72
+ out.push(`#define TS_PANIC_PINOCCHIO 1`);
73
+ }
68
74
  else if (panicFlag?.value === true)
69
75
  out.push(`#define TS_PANIC_ABORT 1`);
70
76
  }
@@ -49,7 +49,7 @@ function emitTree(model, t) {
49
49
  ` int c;`,
50
50
  ` TS_TRY(${p}_cmp(params, key, (const ${K} *)(ts_rbt_node(t, ${S}, parent) + 16), &c));`,
51
51
  ` if (c == 0) {`,
52
- ` ts_memcpy(ts_rbt_node(t, ${S}, parent) + ${16 + ks}, value, ${vs});`,
52
+ ` TS_MEMCPY(ts_rbt_node(t, ${S}, parent) + ${16 + ks}, value, ${vs});`,
53
53
  ` *out = parent;`,
54
54
  ` return SUCCESS;`,
55
55
  ` }`,
@@ -218,9 +218,10 @@ export declare function vecPlace(s: StructDef, base: string, k: number): {
218
218
  };
219
219
  /**
220
220
  * C lines checking that an account's size matches its growable Vecs' lengths (`d`: its TSS_<S> pointer, `a`: its
221
- * TsAccount). One Vec: ts_check_vec_len; more: each length read only once the bytes before it are known to exist.
221
+ * TsAccount, `disc`: its discriminator's length). One Vec after an 8-byte discriminator: ts_check_vec_len; otherwise
222
+ * each length read only once the bytes before it are known to exist.
222
223
  */
223
- export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: string): string[];
224
+ export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: string, disc?: number): string[];
224
225
  /** C typedef name of a FixedVec<T, N>: `{ uint32_t len; T items[N]; }`. */
225
226
  export declare function fixedVecC(t: FieldType & {
226
227
  kind: "vec";
@@ -237,3 +238,12 @@ export declare const F64_TO_INT: (to: string) => string;
237
238
  export declare const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
238
239
  /** An integer used where an f64 is expected. */
239
240
  export declare const INT_TO_F64: (from: string) => string;
241
+ /**
242
+ * Whether a C lvalue is reached through a pointer the optimizer cannot see behind: account data (`d_acct->f`, a
243
+ * Migrate's `(*df_a)`, a view made in place), a view or reference local, a helper's pointer parameter (`(*p_x).f`). Not a local of the
244
+ * function (`st3.f`, `l_x___v`) nor a helper's result (`(*ret)`, `(*(&t4))`), whose copies clang may fold away when it
245
+ * unrolls them: those take the memory syscalls only where it would emit a loop (runtime/typesol_rt.h).
246
+ */
247
+ export declare function throughPointer(lv: string): boolean;
248
+ /** A whole copy between two places of one type: TS_COPY when both are reached through pointers, else TS_COPY_LOCAL. */
249
+ export declare function copyMacro(dst: string, src: string): string;
@@ -295,19 +295,20 @@ export function vecPlace(s, base, k) {
295
295
  }
296
296
  /**
297
297
  * C lines checking that an account's size matches its growable Vecs' lengths (`d`: its TSS_<S> pointer, `a`: its
298
- * TsAccount). One Vec: ts_check_vec_len; more: each length read only once the bytes before it are known to exist.
298
+ * TsAccount, `disc`: its discriminator's length). One Vec after an 8-byte discriminator: ts_check_vec_len; otherwise
299
+ * each length read only once the bytes before it are known to exist.
299
300
  */
300
- export function vecLenCheck(s, a, d, pad = " ") {
301
+ export function vecLenCheck(s, a, d, pad = " ", disc = 8) {
301
302
  const vs = s.vecs ?? [];
302
- if (vs.length === 1)
303
+ if (vs.length === 1 && disc === 8)
303
304
  return [`${pad}TS_TRY(ts_check_vec_len(${a}, sizeof(TSS_${s.name}), ${d}->${vs[0].name}__len, TS_ELEM_${s.name}));`];
304
305
  const o = `${d.replace(/\W/g, "")}__vo`;
305
306
  const lines = [`${pad}{`, `${pad} uint64_t ${o} = sizeof(TSS_${s.name}) + (uint64_t)${d}->${vs[0].name}__len * ${vs[0].elemSize};`];
306
307
  for (const v of vs.slice(1)) {
307
- lines.push(`${pad} if (${a}->data_len < 8 + ${o} + 4) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`);
308
- lines.push(`${pad} ${o} += 4 + (uint64_t)((${laterVecC(s.name, v.name)} *)(${a}->data + 8 + ${o}))->len * ${v.elemSize};`);
308
+ lines.push(`${pad} if (${a}->data_len < ${disc} + ${o} + 4) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`);
309
+ lines.push(`${pad} ${o} += 4 + (uint64_t)((${laterVecC(s.name, v.name)} *)(${a}->data + ${disc} + ${o}))->len * ${v.elemSize};`);
309
310
  }
310
- lines.push(`${pad} if (${a}->data_len != 8 + ${o}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`, `${pad}}`);
311
+ lines.push(`${pad} if (${a}->data_len != ${disc} + ${o}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`, `${pad}}`);
311
312
  return lines;
312
313
  }
313
314
  /** C typedef name of a FixedVec<T, N>: `{ uint32_t len; T items[N]; }`. */
@@ -330,3 +331,22 @@ export const F64_TO_INT = (to) => `an f64 is not an integer, so it is not conver
330
331
  export const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
331
332
  /** An integer used where an f64 is expected. */
332
333
  export const INT_TO_F64 = (from) => `a ${from} is not an f64, so it is not converted: an f64 is made from its IEEE 754 bits with f64FromBits(bits)`;
334
+ /**
335
+ * Whether a C lvalue is reached through a pointer the optimizer cannot see behind: account data (`d_acct->f`, a
336
+ * Migrate's `(*df_a)`, a view made in place), a view or reference local, a helper's pointer parameter (`(*p_x).f`). Not a local of the
337
+ * function (`st3.f`, `l_x___v`) nor a helper's result (`(*ret)`, `(*(&t4))`), whose copies clang may fold away when it
338
+ * unrolls them: those take the memory syscalls only where it would emit a loop (runtime/typesol_rt.h).
339
+ */
340
+ export function throughPointer(lv) {
341
+ const m = /^\(\*([A-Za-z_][A-Za-z0-9_]*)\)/.exec(lv);
342
+ if (m)
343
+ return m[1] !== "ret";
344
+ // A view made where it is read (`(*((TSS_T *)(acct->data + off)))`, a tree node's value), not a local's address.
345
+ if (lv.startsWith("(*(") && !lv.startsWith("(*(&"))
346
+ return true;
347
+ return /^d_[A-Za-z0-9_]+->/.test(lv);
348
+ }
349
+ /** A whole copy between two places of one type: TS_COPY when both are reached through pointers, else TS_COPY_LOCAL. */
350
+ export function copyMacro(dst, src) {
351
+ return throughPointer(dst) && throughPointer(src) ? "TS_COPY" : "TS_COPY_LOCAL";
352
+ }
@@ -164,9 +164,16 @@ export declare abstract class StatementEmitter extends CpiEmitter {
164
164
  protected heapLocal(d: ts.VariableDeclaration, aggregate: boolean): boolean;
165
165
  /** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
166
166
  protected checkHeapRoom(bytes: number, at: ts.Node): void;
167
+ /**
168
+ * `const [program, data] = getReturnData()`: Rust's `get_return_data()`, the return data as the runtime holds it
169
+ * (sol_get_return_data): the program that set it and its bytes, read into 1 KiB of this function's stack frame (the
170
+ * runtime's maximum, so nothing is cut). Rust's `None` is `data.length === 0n` (the runtime keeps no empty return
171
+ * data), with `program` then all zeros.
172
+ */
173
+ protected programAndReturnData(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, call: ts.CallExpression, mutable: boolean): void;
167
174
  /**
168
175
  * `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
169
- * Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
176
+ * Pubkey::find_program_address(…)`, both from one search (with getReturnData, the only array destructuring).
170
177
  */
171
178
  protected addressAndBump(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, mutable: boolean): void;
172
179
  /**