@typesol/cli 0.43.0 → 0.44.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 (64) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/NOTICE +71 -0
  3. package/README.md +25 -11
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +4 -0
  9. package/dist/compiler/emit/alias.d.ts +1 -1
  10. package/dist/compiler/emit/alias.js +10 -4
  11. package/dist/compiler/emit/base.d.ts +3 -1
  12. package/dist/compiler/emit/base.js +20 -3
  13. package/dist/compiler/emit/borsh.js +11 -5
  14. package/dist/compiler/emit/calls.d.ts +13 -0
  15. package/dist/compiler/emit/calls.js +91 -8
  16. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  17. package/dist/compiler/emit/cpi-core.js +35 -7
  18. package/dist/compiler/emit/create.js +3 -0
  19. package/dist/compiler/emit/expressions.js +6 -1
  20. package/dist/compiler/emit/function.js +10 -0
  21. package/dist/compiler/emit/shared.d.ts +17 -0
  22. package/dist/compiler/emit/shared.js +36 -3
  23. package/dist/compiler/emit/statements.js +17 -4
  24. package/dist/compiler/emit/storage.d.ts +2 -0
  25. package/dist/compiler/emit/storage.js +16 -8
  26. package/dist/compiler/index.d.ts +15 -1
  27. package/dist/compiler/index.js +40 -3
  28. package/dist/compiler/toolchain.d.ts +41 -1
  29. package/dist/compiler/toolchain.js +102 -3
  30. package/dist/testing-stake.d.ts +2 -1
  31. package/dist/testing-stake.js +2 -1
  32. package/dist/testing.js +6 -4
  33. package/dist/tools/clientgen.d.ts +15 -0
  34. package/dist/tools/clientgen.js +173 -7
  35. package/dist/tools/cpigen.d.ts +0 -15
  36. package/dist/tools/cpigen.js +19 -8
  37. package/dist/tools/doctor.d.ts +17 -2
  38. package/dist/tools/doctor.js +64 -4
  39. package/dist/tools/portgen.js +43 -18
  40. package/dist/workspace.d.ts +20 -0
  41. package/dist/workspace.js +173 -6
  42. package/docs/ai.md +10 -5
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +63 -17
  45. package/docs/case-study-escrow.md +1 -1
  46. package/docs/case-study-phoenix.md +10 -10
  47. package/docs/case-study-raydium-amm.md +3 -3
  48. package/docs/case-study-spl-stake-pool.md +5 -5
  49. package/docs/cli.md +17 -8
  50. package/docs/client.md +11 -3
  51. package/docs/errors.md +1 -1
  52. package/docs/language.md +10 -5
  53. package/docs/mainnet.md +21 -10
  54. package/docs/migrate-from-anchor.md +2 -1
  55. package/docs/runtime.md +11 -1
  56. package/docs/security-model.md +38 -6
  57. package/docs/stability.md +21 -2
  58. package/docs/testing.md +25 -0
  59. package/docs/troubleshooting.md +12 -0
  60. package/llms-full.txt +168 -52
  61. package/llms.txt +1 -1
  62. package/package.json +3 -1
  63. package/runtime/typesol_rt.h +22 -13
  64. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
@@ -4,7 +4,7 @@ import { borshIdentical, 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, } 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, } 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.
@@ -219,6 +219,12 @@ export class CallEmitter extends ExpressionEmitter {
219
219
  const d = this.accountParam(args[1], "close's destination");
220
220
  if (!isWritable(d.kind))
221
221
  this.fail(args[1], "the destination must be writable (Mut<...>)");
222
+ // In a helper both may be one account the caller passed twice (Dup<…>): closing into itself is refused.
223
+ if (a.index === -1 || d.index === -1)
224
+ this.line(`if (a_${a.name} == a_${d.name}) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: close's destination is the account itself");`);
225
+ else if (a === d)
226
+ this.fail(args[1], "the destination is the account being closed; name another writable account");
227
+ this.assertNotUsedAfterClose(a, node);
222
228
  this.line(`TS_TRY(ts_close(a_${a.name}, a_${d.name}));`);
223
229
  this.forgetOwners();
224
230
  return undefined;
@@ -372,7 +378,9 @@ export class CallEmitter extends ExpressionEmitter {
372
378
  if (a.type.kind !== "int" || !sameType(a.type, b.type))
373
379
  this.fail(node, `${builtin}(a, b) takes two integers of the same type`);
374
380
  const t = this.tmp("mm");
375
- this.line(`${INT_INFO[a.type.name].c} ${t} = (${a.c} ${builtin === "min" ? "<" : ">"} ${b.c}) ? ${a.c} : ${b.c};`);
381
+ // A u256 is four limbs, compared by the runtime.
382
+ const less = a.type.name === "u256" ? `ts_u256_cmp(${a.c}, ${b.c}) ${builtin === "min" ? "<" : ">"} 0` : `${a.c} ${builtin === "min" ? "<" : ">"} ${b.c}`;
383
+ this.line(`${INT_INFO[a.type.name].c} ${t} = (${less}) ? ${a.c} : ${b.c};`);
376
384
  return { c: t, type: a.type };
377
385
  }
378
386
  case "realloc": {
@@ -2346,6 +2354,47 @@ export class CallEmitter extends ExpressionEmitter {
2346
2354
  visit(body);
2347
2355
  return found;
2348
2356
  }
2357
+ /**
2358
+ * After close(acct, dest) the account holds no data and belongs to the System Program: reading or writing it later in
2359
+ * the function (or on a later turn of a loop around the close) would read zeros or write bytes that are dropped. The
2360
+ * same holds for a reference into it read later. Refused, like a view used after closeRaw (assertNoViewAfter).
2361
+ */
2362
+ assertNotUsedAfterClose(a, at) {
2363
+ let fn = at.parent;
2364
+ while (fn && !ts.isFunctionLike(fn))
2365
+ fn = fn.parent;
2366
+ const body = fn && fn.body;
2367
+ if (!body)
2368
+ return;
2369
+ const loops = [];
2370
+ for (let n = at.parent; n && n !== fn; n = n.parent)
2371
+ if (ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n))
2372
+ loops.push(n);
2373
+ const later = (n) => n.pos >= at.end || loops.some((l) => n.pos >= l.pos && n.end <= l.end && !(n.pos >= at.pos && n.end <= at.end));
2374
+ let hit;
2375
+ const visit = (n) => {
2376
+ if (hit)
2377
+ return;
2378
+ // Its address stays what it was: `acct.key` after the close is fine.
2379
+ if (ts.isPropertyAccessExpression(n) && n.name.text === "key" && this.probe(() => this.accountAt(n.expression)) === a)
2380
+ return;
2381
+ // A name or group field naming the account (not a property name: `x.vault`'s `vault` is not `vault`).
2382
+ const named = ts.isPropertyAccessExpression(n) ||
2383
+ (ts.isIdentifier(n) && !(ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) && !ts.isPropertyAssignment(n.parent));
2384
+ if (named && later(n) && this.probe(() => this.accountAt(n)) === a)
2385
+ hit = n;
2386
+ if (!hit)
2387
+ ts.forEachChild(n, visit);
2388
+ };
2389
+ visit(body);
2390
+ if (!hit)
2391
+ for (const scope of this.scopes)
2392
+ for (const l of scope.values())
2393
+ if (l.decl && l.paths?.some((p) => p === a.name || p.startsWith(`${a.name}.`) || p.startsWith(`${a.name}[]`)) && this.usedAfter(l.decl, at))
2394
+ hit = l.decl;
2395
+ if (hit)
2396
+ this.fail(hit, `${a.name} is closed by close(${a.name}, …) and used after it: a closed account has no data (writes to it are dropped, reads see zeros). Do everything with ${a.name} before closing it (its key stays readable)`);
2397
+ }
2349
2398
  /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
2350
2399
  helperResizes(body) {
2351
2400
  return this.helperCalls(body, ["closeRaw", "resizeAccount"]);
@@ -2503,6 +2552,8 @@ export class CallEmitter extends ExpressionEmitter {
2503
2552
  // A helper that takes accounts may change account data, so account text it gets is copied first.
2504
2553
  // A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
2505
2554
  const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
2555
+ // What a helper can write: account data (through its accounts) and the caller's places it takes as Inout<T>.
2556
+ const mayWrite = takesAccounts || h.params.some((p) => p.inout);
2506
2557
  // A helper that closes or resizes an account it is given ends the caller's views of it (any account it may be).
2507
2558
  if (takesAccounts && this.helperResizes(h.node))
2508
2559
  this.assertNoViewAfter("?", node, `${h.display}() (it may close or resize an account it is given)`);
@@ -2521,16 +2572,21 @@ export class CallEmitter extends ExpressionEmitter {
2521
2572
  pieces.push(raw);
2522
2573
  else {
2523
2574
  pieces.push(values.length);
2524
- values.push(takesAccounts ? this.ownedString(raw) : raw);
2575
+ // Text viewing account data or an Inout place may change under the helper: it gets the bytes as they are now.
2576
+ values.push(mayWrite ? this.ownedString(raw) : raw);
2525
2577
  }
2526
2578
  });
2527
2579
  if (h.params.some((p) => p.inout))
2528
2580
  this.checkInoutCall(node, h, argNodes, pieces.map((x) => (typeof x === "string" ? x : undefined)));
2529
- // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased).
2581
+ // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased): the
2582
+ // account however it is named here (a parameter, an account group's field, a struct loaded with loadAccountMut).
2530
2583
  for (const [i, p] of h.params.entries())
2531
- if (p.account && p.account.kind === "account" && p.account.mut && ts.isIdentifier(argNodes[i]))
2532
- this.assertNotAliased([argNodes[i].text], node, h.display);
2533
- const args = ["params", ...pieces.map((x) => (typeof x === "number" ? (values[x].type.kind === "pubkey" ? `*(${values[x].c})` : values[x].c) : x))];
2584
+ if (p.account && p.account.kind === "account" && p.account.mut)
2585
+ this.assertNotAliased(this.pathsOf(argNodes[i]), node, h.display, true);
2586
+ const args = [
2587
+ "params",
2588
+ ...pieces.map((x) => (typeof x === "number" ? (passedByPointer(values[x].type) ? this.pointerArg(values[x], mayWrite) : values[x].c) : x)),
2589
+ ];
2534
2590
  if (!h.returns) {
2535
2591
  this.line(`TS_TRY(fn_${h.name}(${args.join(", ")}));`);
2536
2592
  return undefined;
@@ -2552,6 +2608,32 @@ export class CallEmitter extends ExpressionEmitter {
2552
2608
  this.line(`TS_TRY(fn_${h.name}(${[...args, `&${t}`].join(", ")}));`);
2553
2609
  return h.returns.kind === "pubkey" ? { c: `(&${t})`, type: h.returns } : { c: t, type: h.returns };
2554
2610
  }
2611
+ /**
2612
+ * A Pubkey, Option, string or u256 helper argument, passed as a pointer (see passedByPointer). When the helper can
2613
+ * write (it takes accounts or Inout places) and the argument is not a named C object nothing passed can reach (see
2614
+ * unreachableArg), the pointer is to a copy taken here: JS gives the helper the value as it is at the call. A
2615
+ * helper that writes nothing reads the caller's value in place.
2616
+ */
2617
+ pointerArg(v, mayWrite) {
2618
+ if (v.type.kind === "pubkey") {
2619
+ if (!mayWrite || unreachableArg(v.c, true))
2620
+ return v.c;
2621
+ const t = this.tmp("argk");
2622
+ this.line(`SolPubkey ${t} = *(${v.c});`);
2623
+ return `(&${t})`;
2624
+ }
2625
+ const own = /^\(\*(p_\w+)\)$/.exec(v.c);
2626
+ if (own)
2627
+ return own[1];
2628
+ if (/^\w+$/.test(v.c))
2629
+ return `(&${v.c})`;
2630
+ // A field read in place (`d_x->opt`): an Option's C struct is packed, so its address is fine to take.
2631
+ if (!mayWrite && v.type.kind === "option" && /^\w+(?:(?:->|\.)\w+)+$/.test(v.c))
2632
+ return `(&${v.c})`;
2633
+ const t = this.tmp("argv");
2634
+ this.line(`${valueC(v.type)} ${t} = ${v.c};`);
2635
+ return `(&${t})`;
2636
+ }
2555
2637
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
2556
2638
  helperArg(h, p, n) {
2557
2639
  if (p.account) {
@@ -2952,7 +3034,8 @@ export class CallEmitter extends ExpressionEmitter {
2952
3034
  if (ts.isCallExpression(n) && this.exportName(n.expression) === "signer") {
2953
3035
  if (n.arguments.length !== 1)
2954
3036
  this.fail(n, "signer([...seeds]) takes the seeds (with the bump) as an array; signer([]) signs for nothing");
2955
- return this.seeds(n.arguments[0], 0);
3037
+ // Bound to a name or given to a helper: the list outlives this expression, so its seeds are copied now.
3038
+ return this.seeds(n.arguments[0], 0, true);
2956
3039
  }
2957
3040
  this.fail(n, "pass signer([...seeds with the bump]) or a SignerSeeds parameter");
2958
3041
  }
@@ -8,11 +8,13 @@ export declare abstract class CpiCoreEmitter extends ViewEmitter {
8
8
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
9
9
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
10
10
  */
11
- protected seeds(node: ts.Expression, extra: number): {
11
+ protected seeds(node: ts.Expression, extra: number, bound?: boolean): {
12
12
  name: string;
13
13
  count: number;
14
14
  idl: IdlSeed[] | undefined;
15
15
  };
16
+ /** A call that runs none of the program's code and writes nothing: an integer cast, min / max, a list's get(i). */
17
+ protected pureCall(n: ts.CallExpression): boolean;
16
18
  protected describeSeed(el: ts.Expression): IdlSeed | undefined;
17
19
  protected recordPda(account: AccountParam, idl: IdlSeed[] | undefined): void;
18
20
  /**
@@ -10,21 +10,42 @@ export class CpiCoreEmitter extends ViewEmitter {
10
10
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
11
11
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
12
12
  */
13
- seeds(node, extra) {
13
+ seeds(node, extra, bound = false) {
14
14
  if (!ts.isArrayLiteralExpression(node))
15
15
  this.fail(node, "seeds must be an array literal");
16
16
  if (node.elements.length > MAX_SEEDS)
17
17
  this.fail(node, `at most ${MAX_SEEDS} seeds`);
18
18
  const parts = [];
19
19
  let idl = [];
20
- // Without calls or writes among the seeds, nothing can change a seed before the CPI reads it: account fields are
21
- // then passed in place instead of copied.
22
- const mutates = (n) => ts.isCallExpression(n) ||
20
+ // The array points at its seeds, which are read when the CPI runs. Seeds that are not constants are copied when
21
+ // the list is written, as JS reads them then, unless nothing can run between the list and the CPI that reads it:
22
+ // no calls or writes among the seeds, nor in the other arguments of the call consuming the list (evaluated before
23
+ // or after it). A list bound to a name or passed to a helper (`bound`) outlives its expression: always copied.
24
+ const mutates = (n) => (ts.isCallExpression(n) && !this.pureCall(n)) ||
23
25
  (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
24
- ts.isPrefixUnaryExpression(n) ||
26
+ (ts.isPrefixUnaryExpression(n) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) ||
25
27
  ts.isPostfixUnaryExpression(n) ||
26
28
  ts.forEachChild(n, mutates) === true;
27
- const inPlace = !node.elements.some(mutates);
29
+ // The argument holding the list (`signer([…])`, a list of signer lists, an object of CPI options) and the call it
30
+ // is an argument of.
31
+ let consumer = node.parent;
32
+ let list = node;
33
+ const wraps = (n) => ts.isParenthesizedExpression(n) ||
34
+ ts.isArrayLiteralExpression(n) ||
35
+ ts.isObjectLiteralExpression(n) ||
36
+ ts.isPropertyAssignment(n) ||
37
+ (ts.isCallExpression(n) && this.exportName(n.expression) === "signer");
38
+ while (consumer && wraps(consumer)) {
39
+ list = consumer;
40
+ consumer = consumer.parent;
41
+ }
42
+ const others = consumer && ts.isCallExpression(consumer) ? consumer.arguments.filter((a) => a !== list) : [];
43
+ const inPlace = !bound && !mutates(list) && !others.some(mutates);
44
+ // Seeds no write can change: account keys, constants, instruction arguments, a helper's by-pointer parameters.
45
+ const constant = (el, c) => /^\(?&\w+->key\)?$/.test(c) ||
46
+ /^\(&(?:TSK_|arg_)\w+\)$/.test(c) ||
47
+ /^\(&\(\*p_\w+\)\)$/.test(c) ||
48
+ (ts.isIdentifier(el) && /^\(&\w+\)$/.test(c) && this.lookup(el.text)?.mutable === false);
28
49
  const mark = this.lines.length;
29
50
  for (const el of node.elements) {
30
51
  const desc = this.describeSeed(el);
@@ -55,7 +76,7 @@ export class CpiCoreEmitter extends ViewEmitter {
55
76
  }
56
77
  // Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
57
78
  const v = this.expr(el);
58
- if (v.type.kind === "pubkey" && (isStable(v.c) || (inPlace && /^\(&d_\w+(->\w+)+\)$/.test(v.c))))
79
+ if (v.type.kind === "pubkey" && (constant(el, v.c) || (inPlace && (isStable(v.c) || /^\(&d_\w+(->\w+)+\)$/.test(v.c)))))
59
80
  parts.push(`{(const uint8_t *)${v.c.startsWith("(") ? v.c : `(${v.c})`}, 32}`);
60
81
  else if (v.type.kind === "int" && inPlace && v.literal === undefined && /^d_\w+(->\w+)+$/.test(v.c))
61
82
  parts.push(`{(const uint8_t *)&${v.c}, ${INT_INFO[v.type.name].bytes}}`);
@@ -100,6 +121,13 @@ export class CpiCoreEmitter extends ViewEmitter {
100
121
  this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
101
122
  return { name, count: parts.length, idl };
102
123
  }
124
+ /** A call that runs none of the program's code and writes nothing: an integer cast, min / max, a list's get(i). */
125
+ pureCall(n) {
126
+ const fn = this.exportName(n.expression);
127
+ if (fn && (Object.hasOwn(INT_INFO, fn) || fn === "min" || fn === "max" || fn === "bigEndian"))
128
+ return true;
129
+ return ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get" && n.arguments.length === 1;
130
+ }
103
131
  describeSeed(el) {
104
132
  // Anchor's IDL records `x.to_be_bytes()` as the argument (or field) itself, without the byte order.
105
133
  if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian" && el.arguments.length === 1)
@@ -490,6 +490,9 @@ export class CreateEmitter extends CpiCoreEmitter {
490
490
  this.fail(node, `${call}(...) needs to know the token program: pass it, ${call}(payer, ${tokenPrograms[0].name}) (found ${tokenPrograms.map((o) => o.name).join(", ")})`);
491
491
  }
492
492
  const { owner, mint } = target.constraints.ata;
493
+ // The Associated Token Account program takes the owner as an account of the instruction, not as a key.
494
+ if (owner.startsWith("@"))
495
+ this.fail(node, `${call}(...) creates the account through the Associated Token Account program, which needs the owner as an account: "${owner}" is a stored key. Take the owner as a parameter (checked against ${owner.slice(1)}) and name it in Ata<…>`);
493
496
  const a = `a_${target.name}`;
494
497
  const create = `TS_TRY(ts_ata_create(params, a_${ataProgram.name}, a_${payer.name}, ${a}, a_${owner}, a_${mint}, a_${system.name}, a_${tokenProgram.name}, false));`;
495
498
  let result;
@@ -885,10 +885,13 @@ export class ExpressionEmitter extends StorageEmitter {
885
885
  }
886
886
  if (exp.type.kind !== "int")
887
887
  this.fail(node.right, "the exponent of ** must be an integer");
888
+ // Any exponent past 255 overflows unless the base is 0 or 1: a u256 one is not needed, and has no C shift.
889
+ if (exp.type.name === "u256")
890
+ this.fail(node.right, "the exponent of ** is a u128 or smaller integer: convert it (u64(e))");
888
891
  const r = this.tmp("pr");
889
892
  const sq = this.tmp("ps");
890
893
  const e = this.tmp("pe");
891
- this.line(`${ct} ${r} = 1;`);
894
+ this.line(`${ct} ${r} = ${type.name === "u256" ? intLiteral(1n, "u256") : "1"};`);
892
895
  this.line(`${ct} ${sq} = ${base.c};`);
893
896
  if (INT_INFO[exp.type.name].signed)
894
897
  this.line(`if (${exp.c} < 0) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: negative exponent");`);
@@ -1131,6 +1134,8 @@ export class ExpressionEmitter extends StorageEmitter {
1131
1134
  // (in JS the bigint would just grow). `>>` on signed types is arithmetic, as in JS.
1132
1135
  if (right.type.kind !== "int")
1133
1136
  this.fail(node, "shift amounts must be integers");
1137
+ if (right.type.name === "u256")
1138
+ this.fail(node, "shift by a u64 (or smaller) amount");
1134
1139
  const bits = INT_INFO[type.name].bytes * 8;
1135
1140
  const sh = this.tmp("sh");
1136
1141
  const rinfo = INT_INFO[right.type.name];
@@ -197,6 +197,16 @@ export class FunctionEmitter extends StatementEmitter {
197
197
  // here, not closed, not a @layout borsh heap copy (a lost update when packed back). A close destination is in place:
198
198
  // a duplicate shares its record, so the rent lands in both views.
199
199
  const closing = new Set(ix.accounts.flatMap((a) => (a.constraints.closeTo ? [a.name] : [])));
200
+ // An account the body closes with close(account, destination) is closed too.
201
+ const visitClose = (nd) => {
202
+ if (ts.isCallExpression(nd) && this.exportName(nd.expression) === "close" && nd.arguments[0]) {
203
+ const closed = this.accountAt(nd.arguments[0]);
204
+ if (closed)
205
+ closing.add(closed.name);
206
+ }
207
+ ts.forEachChild(nd, visitClose);
208
+ };
209
+ visitClose(ix.node.body);
200
210
  const inPlace = (a) => {
201
211
  const k = a.kind;
202
212
  if (closing.has(a.name))
@@ -177,6 +177,23 @@ export declare function fieldC(t: FieldType): string;
177
177
  export declare function storageDecl(t: FieldType, name: string): string;
178
178
  /** Why an account of kind `have` cannot be passed where a helper takes `want`, or undefined when it can. */
179
179
  export declare function accountMismatch(have: ParamKind, want: ParamKind): string | undefined;
180
+ /**
181
+ * Helper parameters held in a C struct (a Pubkey, an Option, a string view, a u256) that are passed as a const pointer
182
+ * instead of by value. The SBF target passes every C struct argument `byval`, as a pointer to the caller's object, and
183
+ * its backend makes no copy: a helper that is not inlined then reads the caller's object itself, and sees its own writes
184
+ * to it (`rotate(v, v.admin)` reading v.admin after `v.admin = …`). A copy written in C does not help either: clang
185
+ * forwards it into the byval argument, as byval promises a copy. So these are pointers, and the call site copies what
186
+ * the helper could write (see Calls.pointerArg); a pointer to a copy is kept, as the helper may write the original.
187
+ */
188
+ export declare const passedByPointer: (t: ValueType) => boolean;
189
+ /**
190
+ * Whether a C argument names memory that no helper can write: a named C object (a local, a temporary, an instruction
191
+ * argument, a constant), a field of a struct instruction argument (decoded into memory of its own, read-only), an
192
+ * account's key, the program's id, or a helper's own by-pointer parameter. `c` is the pointer for a Pubkey, the
193
+ * value otherwise. A helper's by-pointer parameter points at a copy, or at an object the helper cannot reach: helpers
194
+ * reach memory only through the accounts, remaining accounts and Inout places they are given, and pass on a subset.
195
+ */
196
+ export declare const unreachableArg: (c: string, pubkey: boolean) => boolean;
180
197
  /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
181
198
  export declare function helperSignature(h: Helper): string;
182
199
  export interface EmitOptions {
@@ -26,7 +26,14 @@ export const STRING = { kind: "string" };
26
26
  export const HASH = { kind: "pubkey", hash: true };
27
27
  export const cBytes = (bytes) => `{${bytes.join(", ")}}`;
28
28
  /** C expressions that nothing in a TypeSOL expression can change: temporaries, locals, arguments, account keys, constants. */
29
- export const isStable = (c) => /^\w+$/.test(c) || /^\(&\w+\)$/.test(c) || /^&\w+->key$/.test(c) || /^\(\(uint8_t\)\d+\)$/.test(c) || /^\(?-?\d+U?LL\)?$/.test(c);
29
+ export const isStable = (c) => /^\w+$/.test(c) ||
30
+ /^\(&\w+\)$/.test(c) ||
31
+ /^&\w+->key$/.test(c) ||
32
+ /^\(\(uint8_t\)\d+\)$/.test(c) ||
33
+ /^\(?-?\d+U?LL\)?$/.test(c) ||
34
+ // A helper's by-pointer parameter (see passedByPointer): nothing the helper does changes what it points at.
35
+ /^\(&?\(\*p_\w+\)\)$/.test(c) ||
36
+ /^\(\*p_\w+\)$/.test(c);
30
37
  /** A C string literal of the UTF-8 bytes. Octal escapes (at most three digits) cannot swallow following characters. */
31
38
  export const cString = (s) => `"${[...Buffer.from(s, "utf8")].map((b) => (b >= 0x20 && b < 0x7f && b !== 0x22 && b !== 0x5c && b !== 0x3f ? String.fromCharCode(b) : `\\${b.toString(8).padStart(3, "0")}`)).join("")}"`;
32
39
  export function intLiteral(value, name) {
@@ -203,6 +210,29 @@ export function accountMismatch(have, want) {
203
210
  }
204
211
  return ok && mutOk ? undefined : name(want);
205
212
  }
213
+ /**
214
+ * Helper parameters held in a C struct (a Pubkey, an Option, a string view, a u256) that are passed as a const pointer
215
+ * instead of by value. The SBF target passes every C struct argument `byval`, as a pointer to the caller's object, and
216
+ * its backend makes no copy: a helper that is not inlined then reads the caller's object itself, and sees its own writes
217
+ * to it (`rotate(v, v.admin)` reading v.admin after `v.admin = …`). A copy written in C does not help either: clang
218
+ * forwards it into the byval argument, as byval promises a copy. So these are pointers, and the call site copies what
219
+ * the helper could write (see Calls.pointerArg); a pointer to a copy is kept, as the helper may write the original.
220
+ */
221
+ export const passedByPointer = (t) => t.kind === "pubkey" || t.kind === "option" || t.kind === "string" || (t.kind === "int" && t.name === "u256");
222
+ /**
223
+ * Whether a C argument names memory that no helper can write: a named C object (a local, a temporary, an instruction
224
+ * argument, a constant), a field of a struct instruction argument (decoded into memory of its own, read-only), an
225
+ * account's key, the program's id, or a helper's own by-pointer parameter. `c` is the pointer for a Pubkey, the
226
+ * value otherwise. A helper's by-pointer parameter points at a copy, or at an object the helper cannot reach: helpers
227
+ * reach memory only through the accounts, remaining accounts and Inout places they are given, and pass on a subset.
228
+ */
229
+ export const unreachableArg = (c, pubkey) => pubkey
230
+ ? /^\(&\w+\)$/.test(c) ||
231
+ /^\(?&\w+->key\)?$/.test(c) ||
232
+ /^\(&\(\*p_\w+\)\)$/.test(c) ||
233
+ c === "params->program_id" ||
234
+ /^\(&\(\*arg_\w+\)(?:\.\w+)+\)$/.test(c)
235
+ : /^\w+$/.test(c) || /^\(\*p_\w+\)$/.test(c) || /^\(\*arg_\w+\)(?:\.\w+)+$/.test(c);
206
236
  /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
207
237
  export function helperSignature(h) {
208
238
  const params = ["TsParams *params"];
@@ -222,8 +252,11 @@ export function helperSignature(h) {
222
252
  // The remaining accounts: the index of the first one among the instruction's accounts.
223
253
  else if (p.type.kind === "remaining")
224
254
  params.push(`uint64_t p_${p.name}`);
225
- else if (p.type.kind === "pubkey")
226
- params.push(`SolPubkey p_${p.name}`); // by value: a copy taken at the call
255
+ // Pubkeys, Options, strings and u256s by pointer (see passedByPointer), never as a C struct by value. `restrict`:
256
+ // nothing changes what it points at while the helper runs (a copy taken for the call, or memory the helper cannot
257
+ // write), so clang may keep what it read in registers across the helper's other writes, as it did for byval.
258
+ else if (passedByPointer(p.type))
259
+ params.push(`const ${p.type.kind === "pubkey" ? "SolPubkey" : valueC(p.type)} *restrict p_${p.name}`);
227
260
  else if (p.type.kind === "arrayArg")
228
261
  params.push(storageDecl(p.type.array, `(*p_${p.name})`));
229
262
  else
@@ -183,8 +183,9 @@ export class StatementEmitter extends CpiEmitter {
183
183
  const typed = subject.literal !== undefined ? this.literal(subject.literal, U64, stmt.expression) : subject;
184
184
  if (typed.type.kind !== "int" && typed.type.kind !== "enum")
185
185
  this.fail(stmt.expression, "switch works on integers and enums");
186
- // C cannot switch on 128-bit values: pick the case's index with comparisons, then switch on that.
187
- const wide = typed.type.kind === "int" && INT_INFO[typed.type.name].bytes === 16;
186
+ // C cannot switch on 128-bit values or u256 limbs: pick the case's index with comparisons, then switch on that.
187
+ const limbs = typed.type.kind === "int" && typed.type.name === "u256";
188
+ const wide = limbs || (typed.type.kind === "int" && INT_INFO[typed.type.name].bytes === 16);
188
189
  const t = this.tmp("sw");
189
190
  this.line(`${scalarC(typed.type)} ${t} = ${typed.c};`);
190
191
  const pick = wide ? this.tmp("swi") : undefined;
@@ -225,7 +226,8 @@ export class StatementEmitter extends CpiEmitter {
225
226
  this.line(`}`);
226
227
  if (pick && cases.length) {
227
228
  const pad = " ".repeat(this.indent);
228
- this.lines.splice(pickAt + 1, 0, ...cases.map((c, i) => `${pad}${i ? "else " : ""}if (${t} == ${c}) ${pick} = ${i};`));
229
+ const eq = (c) => (limbs ? `ts_u256_cmp(${t}, ${c}) == 0` : `${t} == ${c}`);
230
+ this.lines.splice(pickAt + 1, 0, ...cases.map((c, i) => `${pad}${i ? "else " : ""}if (${eq(c)}) ${pick} = ${i};`));
229
231
  }
230
232
  }
231
233
  forLoop(stmt) {
@@ -1990,7 +1992,18 @@ export class StatementEmitter extends CpiEmitter {
1990
1992
  return;
1991
1993
  }
1992
1994
  const mark = this.lines.length;
1993
- const rhs = this.expect(this.expr(valueNode, place.type), place.type, valueNode);
1995
+ // `x <<= n` / `x >>= n`: the amount has a type of its own, as in `x << n` (a literal is a u64).
1996
+ const shift = op === ts.SyntaxKind.LessThanLessThanToken || op === ts.SyntaxKind.GreaterThanGreaterThanToken;
1997
+ let rhs;
1998
+ if (shift) {
1999
+ rhs = this.expr(valueNode);
2000
+ if (rhs.literal !== undefined)
2001
+ rhs = this.literal(rhs.literal, U64, valueNode);
2002
+ if (rhs.type.kind !== "int")
2003
+ this.fail(valueNode, "shift amounts must be integers");
2004
+ }
2005
+ else
2006
+ rhs = this.expect(this.expr(valueNode, place.type), place.type, valueNode);
1994
2007
  current = this.settle(current, mark);
1995
2008
  this.line(place.write(this.arith(op, current, rhs, target).c) + ";");
1996
2009
  return;
@@ -67,6 +67,8 @@ export declare abstract class StorageEmitter extends AliasEmitter {
67
67
  protected lowerInOrder(nodes: readonly ts.Expression[], types: ValueType[]): Value[];
68
68
  /** An index evaluated into a temporary (sign and 128-bit range checked), bounds not yet checked. */
69
69
  protected indexValue(n: ts.Expression): string;
70
+ /** An integer index in a u64 temporary: a negative one, or one past u64 (128-bit, u256 limbs), is out of bounds. */
71
+ private indexTemp;
70
72
  protected checkIndex(t: string, len: string): void;
71
73
  /** Bounds-checked index into a temporary. `len` is a C expression. */
72
74
  protected index(n: ts.Expression, len: string | number): string;
@@ -470,11 +470,24 @@ export class StorageEmitter extends AliasEmitter {
470
470
  const idx = v.literal !== undefined ? this.literal(v.literal, U64, n) : v;
471
471
  if (idx.type.kind !== "int")
472
472
  this.fail(n, "array index must be an integer");
473
+ const t = this.indexTemp(idx);
474
+ return t;
475
+ }
476
+ /** An integer index in a u64 temporary: a negative one, or one past u64 (128-bit, u256 limbs), is out of bounds. */
477
+ indexTemp(idx) {
478
+ if (idx.type.kind !== "int")
479
+ throw new Error("unreachable: an index is an integer");
473
480
  const t = this.tmp("idx");
481
+ const oob = `TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds")`;
482
+ if (idx.type.name === "u256") {
483
+ this.line(`if (!ts_u256_fits(${idx.c}, 64)) ${oob};`);
484
+ this.line(`uint64_t ${t} = (${idx.c}).w[0];`);
485
+ return t;
486
+ }
474
487
  if (INT_INFO[idx.type.name].signed)
475
- this.line(`if (${idx.c} < 0) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
488
+ this.line(`if (${idx.c} < 0) ${oob};`);
476
489
  if (INT_INFO[idx.type.name].bytes === 16)
477
- this.line(`if (${idx.c} > UINT64_MAX) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
490
+ this.line(`if (${idx.c} > UINT64_MAX) ${oob};`);
478
491
  this.line(`uint64_t ${t} = (uint64_t)(${idx.c});`);
479
492
  return t;
480
493
  }
@@ -487,12 +500,7 @@ export class StorageEmitter extends AliasEmitter {
487
500
  const idx = v.literal !== undefined ? this.literal(v.literal, U64, n) : v;
488
501
  if (idx.type.kind !== "int")
489
502
  this.fail(n, "array index must be an integer");
490
- const t = this.tmp("idx");
491
- if (INT_INFO[idx.type.name].signed)
492
- this.line(`if (${idx.c} < 0) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
493
- if (INT_INFO[idx.type.name].bytes === 16)
494
- this.line(`if (${idx.c} > UINT64_MAX) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
495
- this.line(`uint64_t ${t} = (uint64_t)(${idx.c});`);
503
+ const t = this.indexTemp(idx);
496
504
  this.line(`if (${t} >= ${typeof len === "number" ? `${len}ULL` : len}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
497
505
  return t;
498
506
  }
@@ -5,7 +5,7 @@ import { type Sbpf } from "./toolchain.js";
5
5
  import type { ProgramModel } from "./model.js";
6
6
  export { CompileError, formatDiagnostic, type Diagnostic } from "./diagnostics.js";
7
7
  export type { ProgramModel } from "./model.js";
8
- export { SBPF_VERSIONS, type Sbpf } from "./toolchain.js";
8
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN, type Sbpf } from "./toolchain.js";
9
9
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
10
10
  export declare function typescriptHint(d: ts.Diagnostic): string | undefined;
11
11
  export interface Generated {
@@ -20,7 +20,15 @@ export declare function generate(entry: string, opts?: EmitOptions): Generated;
20
20
  export interface BuildManifest {
21
21
  program: string;
22
22
  compiler: string;
23
+ /** The first line of `clang --version`: the compiler of the generated C. */
23
24
  clang: string;
25
+ /** The platform-tools version (`v1.52`), when the SDK's layout tells it for sure (from 0.44.0). */
26
+ platformTools?: string;
27
+ /** The machine that built it: `process.platform` and `process.arch` (from 0.44.0). */
28
+ host?: {
29
+ os: string;
30
+ arch: string;
31
+ };
24
32
  /** The TypeScript version that type-checked the sources (pinned: it decides what compiles). */
25
33
  typescript: string;
26
34
  sbpf: Sbpf;
@@ -45,6 +53,12 @@ export declare function build(entry: string, outDir: string, programAddress: str
45
53
  }): BuildResult;
46
54
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
47
55
  export declare const COMPILER_VERSION: string;
56
+ /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
57
+ export declare function describeToolchain(m: Pick<BuildManifest, "clang" | "platformTools" | "host" | "compiler">): string;
58
+ /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
59
+ export declare function toolchainDifferences(a: Partial<BuildManifest>, b: Partial<BuildManifest>): string[];
60
+ /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
61
+ export declare function elfLength(elf: Buffer): number;
48
62
  /**
49
63
  * Whether `deployed` (a .so, e.g. from `solana program dump`) is exactly what `entry` builds to. Program accounts
50
64
  * keep the ELF zero-padded to their allocation, so trailing zeros are ignored.
@@ -7,10 +7,10 @@ import { analyze, LIB_PATH } from "./analyze.js";
7
7
  import { hintForTypeScript } from "./hints.js";
8
8
  import { emitProgram } from "./emit/index.js";
9
9
  import { buildIdl } from "./idl.js";
10
- import { buildSharedObject, toolchainVersion } from "./toolchain.js";
10
+ import { buildSharedObject, checkToolchain, shortClang, TESTED_TOOLCHAIN } from "./toolchain.js";
11
11
  import { RUNTIME_DIR } from "./toolchain.js";
12
12
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
13
- export { SBPF_VERSIONS } from "./toolchain.js";
13
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN } from "./toolchain.js";
14
14
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
15
15
  export function typescriptHint(d) {
16
16
  return hintForTypeScript(d, ts.flattenDiagnosticMessageText(d.messageText, "\n"), LIB_PATH);
@@ -33,6 +33,8 @@ export function build(entry, outDir, programAddress, opts = {}) {
33
33
  const soPath = `${base}.so`;
34
34
  const idlPath = `${base}.json`;
35
35
  writeFileSync(cPath, gen.c);
36
+ // Before clang runs: an untested toolchain is a warning (once), or an error in strict mode.
37
+ const toolchain = checkToolchain();
36
38
  buildSharedObject(cPath, soPath, opts.sbpf);
37
39
  const idl = buildIdl(gen.model, programAddress);
38
40
  writeFileSync(idlPath, JSON.stringify(idl, null, 2) + "\n");
@@ -44,7 +46,9 @@ export function build(entry, outDir, programAddress, opts = {}) {
44
46
  const manifest = {
45
47
  program: gen.model.name,
46
48
  compiler: COMPILER_VERSION,
47
- clang: toolchainVersion(),
49
+ clang: toolchain.clang,
50
+ ...(toolchain.platformTools ? { platformTools: toolchain.platformTools } : {}),
51
+ host: { os: process.platform, arch: process.arch },
48
52
  typescript: ts.version,
49
53
  sbpf: opts.sbpf ?? "v0",
50
54
  profile: !!opts.profile,
@@ -57,6 +61,39 @@ export function build(entry, outDir, programAddress, opts = {}) {
57
61
  }
58
62
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
59
63
  export const COMPILER_VERSION = createRequire(import.meta.url)("../../package.json").version;
64
+ /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
65
+ export function describeToolchain(m) {
66
+ return [
67
+ shortClang(m.clang),
68
+ `platform-tools ${m.platformTools ?? "unknown"}`,
69
+ m.host ? `${m.host.os}-${m.host.arch}` : "host unknown",
70
+ `TypeSOL ${m.compiler}`,
71
+ ...(m.clang === TESTED_TOOLCHAIN.clang ? ["the tested toolchain"] : []),
72
+ ].join(", ");
73
+ }
74
+ /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
75
+ export function toolchainDifferences(a, b) {
76
+ const out = [];
77
+ if (a.compiler !== b.compiler)
78
+ out.push("TypeSOL version");
79
+ if (a.clang !== b.clang)
80
+ out.push("clang");
81
+ if (a.platformTools && b.platformTools && a.platformTools !== b.platformTools)
82
+ out.push("platform-tools");
83
+ if (a.typescript !== b.typescript)
84
+ out.push("TypeScript");
85
+ if (a.sbpf !== b.sbpf)
86
+ out.push("SBPF version");
87
+ // The host is recorded, not compared: one clang version is meant to give the same bytes on every host.
88
+ return out;
89
+ }
90
+ /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
91
+ export function elfLength(elf) {
92
+ if (elf.length < 0x40 || elf.readUInt32BE(0) !== 0x7f454c46)
93
+ return elf.length;
94
+ const end = Number(elf.readBigUInt64LE(0x28)) + elf.readUInt16LE(0x3a) * elf.readUInt16LE(0x3c);
95
+ return end > 0 && end <= elf.length ? end : elf.length;
96
+ }
60
97
  /**
61
98
  * Whether `deployed` (a .so, e.g. from `solana program dump`) is exactly what `entry` builds to. Program accounts
62
99
  * keep the ELF zero-padded to their allocation, so trailing zeros are ignored.