@typesol/cli 0.42.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 (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  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 +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
@@ -1,18 +1,20 @@
1
1
  import ts from "typescript";
2
2
  import { type AccountParam, type IdlSeed } from "../model.js";
3
- import { type Value, type CpiAcct } from "./shared.js";
4
- import { CallEmitter } from "./calls.js";
3
+ import { type Value, type Ref, type CpiAcct } from "./shared.js";
4
+ import { ViewEmitter } from "./views.js";
5
5
  /** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
6
- export declare abstract class CpiCoreEmitter extends CallEmitter {
6
+ export declare abstract class CpiCoreEmitter extends ViewEmitter {
7
7
  /**
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
  /**
@@ -81,4 +83,21 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
81
83
  protected nestedStructs(name: string): Set<string>;
82
84
  /** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
83
85
  protected fixedLayoutStructs(): Set<string>;
86
+ /**
87
+ * Byte builders on a `FixedVec<u8, N>` (a local list or one in account data), for a native program's hand-built byte
88
+ * strings (Phoenix's event batches: `[15] ‖ Borsh(header) ‖ events`, a u16 count patched in, truncated back to the
89
+ * header after each flush): `pushLE` (an integer at its width), `pushKey` (32 bytes), `pushBorsh` (a value's Borsh
90
+ * encoding, the codecs invoke, events and storeBorsh use), `setLE(offset, v)` (overwrite within the length) and
91
+ * `truncate(n)`. Every write is bounds-checked (5104) and the length moves only once all of it fit, so a failed call
92
+ * appends nothing.
93
+ */
94
+ protected byteListMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
95
+ /**
96
+ * `pushBorsh(value)`: lower the value now and return the writer of its Borsh bytes. Structs (a place, or an object
97
+ * literal given its type: `pushBorsh<Header>({ … })`) are their fixed layout when that is their Borsh form, else go
98
+ * through the struct's Borsh encoder (storeBorsh's); data enums are a tag and the variant's fields, FixedArrays their
99
+ * elements, lists a u32 count and their elements, and integers, booleans, Pubkeys, strings and Options as in invoke
100
+ * data.
101
+ */
102
+ private borshPiece;
84
103
  }
@@ -1,29 +1,51 @@
1
1
  import ts from "typescript";
2
- import { argIdlName, fieldIdlName, snakeCase } from "../analyze.js";
2
+ import { argIdlName, fieldIdlName, resolveScalarType, snakeCase } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
4
- import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
5
- import { CallEmitter } from "./calls.js";
4
+ import { accountLimit, MAX_SEEDS, PUBKEY, U64, isStable, cString, fieldC, scalarStorageC, optC, vecCount, } from "./shared.js";
5
+ import { borshIdentical, borshNativeStructUnsupported } from "./borsh.js";
6
+ import { ViewEmitter } from "./views.js";
6
7
  /** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
7
- export class CpiCoreEmitter extends CallEmitter {
8
+ export class CpiCoreEmitter extends ViewEmitter {
8
9
  /**
9
10
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
10
11
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
11
12
  */
12
- seeds(node, extra) {
13
+ seeds(node, extra, bound = false) {
13
14
  if (!ts.isArrayLiteralExpression(node))
14
15
  this.fail(node, "seeds must be an array literal");
15
16
  if (node.elements.length > MAX_SEEDS)
16
17
  this.fail(node, `at most ${MAX_SEEDS} seeds`);
17
18
  const parts = [];
18
19
  let idl = [];
19
- // Without calls or writes among the seeds, nothing can change a seed before the CPI reads it: account fields are
20
- // then passed in place instead of copied.
21
- 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)) ||
22
25
  (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
23
- ts.isPrefixUnaryExpression(n) ||
26
+ (ts.isPrefixUnaryExpression(n) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) ||
24
27
  ts.isPostfixUnaryExpression(n) ||
25
28
  ts.forEachChild(n, mutates) === true;
26
- 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);
27
49
  const mark = this.lines.length;
28
50
  for (const el of node.elements) {
29
51
  const desc = this.describeSeed(el);
@@ -54,7 +76,7 @@ export class CpiCoreEmitter extends CallEmitter {
54
76
  }
55
77
  // Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
56
78
  const v = this.expr(el);
57
- 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)))))
58
80
  parts.push(`{(const uint8_t *)${v.c.startsWith("(") ? v.c : `(${v.c})`}, 32}`);
59
81
  else if (v.type.kind === "int" && inPlace && v.literal === undefined && /^d_\w+(->\w+)+$/.test(v.c))
60
82
  parts.push(`{(const uint8_t *)&${v.c}, ${INT_INFO[v.type.name].bytes}}`);
@@ -99,6 +121,13 @@ export class CpiCoreEmitter extends CallEmitter {
99
121
  this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
100
122
  return { name, count: parts.length, idl };
101
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
+ }
102
131
  describeSeed(el) {
103
132
  // Anchor's IDL records `x.to_be_bytes()` as the argument (or field) itself, without the byte order.
104
133
  if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian" && el.arguments.length === 1)
@@ -132,7 +161,7 @@ export class CpiCoreEmitter extends CallEmitter {
132
161
  const k = this.model.constants.get(el.text);
133
162
  if (k && typeof k.value === "string")
134
163
  return { kind: "const", value: [...Buffer.from(k.value, "utf8")] };
135
- if (k && typeof k.value === "object")
164
+ if (k && typeof k.value === "object" && k.value !== null)
136
165
  return { kind: "const", value: k.value.pubkey };
137
166
  if (k && typeof k.value === "bigint") {
138
167
  // Little-endian two's complement in the constant's width (16 bytes for u128/i128), as the program hashes it.
@@ -407,4 +436,224 @@ export class CpiCoreEmitter extends CallEmitter {
407
436
  visit({ kind: "struct", name });
408
437
  return out;
409
438
  }
439
+ /**
440
+ * Byte builders on a `FixedVec<u8, N>` (a local list or one in account data), for a native program's hand-built byte
441
+ * strings (Phoenix's event batches: `[15] ‖ Borsh(header) ‖ events`, a u16 count patched in, truncated back to the
442
+ * header after each flush): `pushLE` (an integer at its width), `pushKey` (32 bytes), `pushBorsh` (a value's Borsh
443
+ * encoding, the codecs invoke, events and storeBorsh use), `setLE(offset, v)` (overwrite within the length) and
444
+ * `truncate(n)`. Every write is bounds-checked (5104) and the length moves only once all of it fit, so a failed call
445
+ * appends nothing.
446
+ */
447
+ byteListMethod(node, method, v) {
448
+ const args = node.arguments;
449
+ const info = v.vec;
450
+ const vt = v.type;
451
+ if (info.cap === undefined || info.heap || info.big !== undefined || vt.elem.kind !== "int" || vt.elem.name !== "u8")
452
+ this.fail(node.expression, `${method}() builds bytes in a FixedVec<u8, N> (a local list, or one in account data)`);
453
+ if (!v.writable)
454
+ this.fail(node, this.readOnly(v));
455
+ const cap = info.cap;
456
+ const bytes = `((uint8_t *)${info.items})`;
457
+ const count = vecCount(info);
458
+ /** An integer at a width: the type argument's, or the value's own (a bare literal has none). */
459
+ const intValue = (valueNode, fn) => {
460
+ const targ = node.typeArguments?.[0];
461
+ const t = targ ? resolveScalarType(targ, this.scope) : undefined;
462
+ if (targ && (!t || t.kind !== "int"))
463
+ this.fail(targ, `${fn}<T>: T is an integer type (u8 … u128, i8 … i128)`);
464
+ const val = t ? this.expect(this.expr(valueNode, t), t, valueNode) : this.expr(valueNode);
465
+ if (val.literal !== undefined)
466
+ this.fail(valueNode, `${fn} needs the integer's width: ${fn}<u16>(…) or ${fn}(u16(…))`);
467
+ if (val.type.kind !== "int")
468
+ this.fail(valueNode, `${fn} takes an integer (u8 … u128, i8 … i128)${val.type.kind === "pubkey" ? "; a Pubkey is pushKey(key)" : ""}`);
469
+ if (val.type.name === "u256")
470
+ this.fail(valueNode, "u256 is for computation: convert to u128 (or smaller) first");
471
+ return val;
472
+ };
473
+ switch (method) {
474
+ case "truncate": {
475
+ // Vec::truncate, but a length past the current one fails (Rust's `drain(n..)` panics there) instead of doing nothing.
476
+ if (args.length !== 1)
477
+ this.fail(node, "truncate(length) takes the new length");
478
+ const k = this.expect(this.expr(args[0], U64), U64, args[0]);
479
+ const n = this.tmp("n");
480
+ this.line(`uint64_t ${n} = ${k.c};`);
481
+ this.line(`if (${n} > ${count}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: truncate() past the FixedVec's length");`);
482
+ this.line(`${info.len} = (uint32_t)${n};`);
483
+ return undefined;
484
+ }
485
+ case "setLE": {
486
+ // `data[off..off + size].copy_from_slice(&v.to_le_bytes())`: within the length, as Rust's slice indexing.
487
+ if (args.length !== 2)
488
+ this.fail(node, "setLE(offset, value) takes a byte offset and an integer");
489
+ const off = this.expect(this.expr(args[0], U64), U64, args[0]);
490
+ const o = this.tmp("off");
491
+ this.line(`uint64_t ${o} = ${off.c};`);
492
+ const val = intValue(args[1], "setLE");
493
+ const size = scalarSize(val.type);
494
+ const ct = scalarStorageC(val.type);
495
+ const w = this.tmp("le");
496
+ this.line(`${ct} ${w} = (${ct})(${val.c});`);
497
+ this.line(`if (${o} > ${count} || ${count} - ${o} < ${size}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: setLE() past the FixedVec's length");`);
498
+ this.line(`ts_memcpy(${bytes} + ${o}, &${w}, ${size});`);
499
+ return undefined;
500
+ }
501
+ }
502
+ if (args.length !== 1)
503
+ this.fail(node, `${method}(value) takes one value`);
504
+ const arg = args[0];
505
+ // The value first (as JS evaluates the argument before the call runs), then its bytes after the current length.
506
+ let write;
507
+ if (method === "pushLE") {
508
+ const val = intValue(arg, "pushLE");
509
+ const ct = scalarStorageC(val.type);
510
+ const w = this.tmp("le");
511
+ this.line(`${ct} ${w} = (${ct})(${val.c});`);
512
+ write = (put) => put(`&${w}`, String(scalarSize(val.type)));
513
+ }
514
+ else if (method === "pushKey") {
515
+ if (node.typeArguments?.length)
516
+ this.fail(node, "pushKey(key) takes no type argument");
517
+ const k = this.expect(this.expr(arg, PUBKEY), PUBKEY, arg);
518
+ const t = this.tmp("key");
519
+ this.line(`SolPubkey ${t} = *(${k.c});`);
520
+ write = (put) => put(`&${t}`, "32");
521
+ }
522
+ else
523
+ write = this.borshPiece(node, arg);
524
+ const at = this.tmp("at");
525
+ this.line(`uint64_t ${at} = ${count};`);
526
+ write((src, n) => {
527
+ this.line(`if (${n} > ${cap} - ${at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: ${method}() past the FixedVec's room");`);
528
+ this.line(`ts_memcpy(${bytes} + ${at}, ${src}, ${n});`);
529
+ this.line(`${at} += ${n};`);
530
+ }, { dst: bytes, cap: String(cap), at });
531
+ this.line(`${info.len} = (uint32_t)${at};`);
532
+ return undefined;
533
+ }
534
+ /**
535
+ * `pushBorsh(value)`: lower the value now and return the writer of its Borsh bytes. Structs (a place, or an object
536
+ * literal given its type: `pushBorsh<Header>({ … })`) are their fixed layout when that is their Borsh form, else go
537
+ * through the struct's Borsh encoder (storeBorsh's); data enums are a tag and the variant's fields, FixedArrays their
538
+ * elements, lists a u32 count and their elements, and integers, booleans, Pubkeys, strings and Options as in invoke
539
+ * data.
540
+ */
541
+ borshPiece(node, arg) {
542
+ const targ = node.typeArguments?.[0];
543
+ let r;
544
+ if (ts.isObjectLiteralExpression(arg)) {
545
+ const name = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? targ.typeName.text : undefined;
546
+ const type = name && this.model.structs.get(name)?.size !== undefined
547
+ ? { kind: "struct", name }
548
+ : name && this.model.dataEnums.has(name)
549
+ ? { kind: "dataEnum", name }
550
+ : undefined;
551
+ if (!type)
552
+ this.fail(arg, "pushBorsh({ … }) needs the value's type: buf.pushBorsh<Header>({ … }) (a struct or data enum), or bind it to a typed const first");
553
+ // A data enum literal of a fixed-size variant: the tag and the variant's fields (packed, their Borsh form) in a
554
+ // temporary of exactly those bytes, then one room check and one copy. Not the whole enum zeroed, filled and
555
+ // copied, then written as a tag and a switch on it.
556
+ if (type.kind === "dataEnum") {
557
+ const lit = this.dataEnumLiteral(type.name, arg);
558
+ const size = 1 + lit.variant.fields.reduce((n, f) => n + this.fieldBytes(f.type), 0);
559
+ // Integers, booleans, enums and Pubkeys: each field's value in a local of its own (in source order), then one
560
+ // room check and a store of each at its offset, as pushLE would write them one by one.
561
+ if (lit.variant.fields.every((f) => isScalar(f.type))) {
562
+ const locals = new Map(lit.variant.fields.map((f) => [f.name, this.tmp("bf")]));
563
+ for (const f of lit.variant.fields)
564
+ this.line(`${fieldC(f.type)} ${locals.get(f.name)};`);
565
+ lit.writeFields((field) => locals.get(field));
566
+ return (_put, room) => {
567
+ this.line(`if (${size} > ${room.cap} - ${room.at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushBorsh() past the FixedVec's room");`);
568
+ this.line(`${room.dst}[${room.at}] = ${lit.vi};`);
569
+ let off = 1;
570
+ for (const f of lit.variant.fields) {
571
+ const n = this.fieldBytes(f.type);
572
+ this.line(`ts_memcpy(${room.dst} + ${room.at} + ${off}, &${locals.get(f.name)}, ${n});`);
573
+ off += n;
574
+ }
575
+ this.line(`${room.at} += ${size};`);
576
+ };
577
+ }
578
+ if (lit.variant.fields.every((f) => borshIdentical(f.type, this.model))) {
579
+ const t = this.tmp("bv");
580
+ this.line(`struct __attribute__((packed)) { uint8_t tag; TSV_${lit.e.name}__${lit.variant.name} v; } ${t};`);
581
+ this.line(`${t}.tag = ${lit.vi};`);
582
+ lit.writeFields(`${t}.v`);
583
+ return (put) => put(`&${t}`, String(size));
584
+ }
585
+ }
586
+ const t = this.tmp("bv");
587
+ this.line(`${fieldC(type)} ${t};`);
588
+ if (type.kind === "struct")
589
+ this.line(`ts_memzero(&${t}, sizeof(${t}));`);
590
+ this.writeAggregate({ lv: t, type, writable: true }, arg, true);
591
+ r = { lv: t, type, writable: true };
592
+ }
593
+ else if (targ)
594
+ this.fail(targ, "pushBorsh<T> takes a type only for an object literal; the value's own type is used otherwise");
595
+ const kind = r?.type.kind ?? this.peekKind(arg);
596
+ if (kind === "struct" || kind === "array" || kind === "dataEnum") {
597
+ r ??= this.ref(arg);
598
+ const place = r;
599
+ if (place.type.kind === "dataEnum") {
600
+ const name = place.type.name;
601
+ const e = this.model.dataEnums.get(name);
602
+ // Fixed-size payloads are packed in the variant's C struct as Borsh lays them out: the tag, then one copy.
603
+ if (e.variants.every((v) => v.fields.every((f) => borshIdentical(f.type, this.model))))
604
+ return (put) => {
605
+ put(`&${place.lv}.tag`, "1");
606
+ if (e.variants.every((v) => !v.fields.length))
607
+ return;
608
+ this.line(`switch (${place.lv}.tag) {`);
609
+ e.variants.forEach((v, i) => {
610
+ const size = v.fields.reduce((n, f) => n + this.fieldBytes(f.type), 0);
611
+ if (!size)
612
+ return;
613
+ this.line(`case ${i}: {`);
614
+ put(`&${place.lv}.v.${v.name}`, String(size));
615
+ this.line(`break; }`);
616
+ });
617
+ this.line(`}`);
618
+ };
619
+ return (put) => this.serializeDataEnumLv(place.lv, name, (src, n) => put(src, n));
620
+ }
621
+ if (borshIdentical(place.type, this.model)) {
622
+ const n = this.fieldBytes(place.type);
623
+ return (put) => put(`&${place.lv}`, String(n));
624
+ }
625
+ if (place.type.kind === "array")
626
+ this.fail(arg, `${typeName(place.type)} has no Borsh form of its own here (its elements hold Options, data enums or text)`);
627
+ const s = this.model.structs.get(place.type.name);
628
+ const why = borshNativeStructUnsupported(s, this.model);
629
+ if (why)
630
+ this.fail(arg, `pushBorsh cannot encode ${s.name}: ${why}`);
631
+ this.model.borshNative.add(s.name);
632
+ return (_put, room) => {
633
+ // The encoder writes into the room left and reports how much it wrote; the length moves only afterwards.
634
+ const w = this.tmp("bw");
635
+ this.line(`uint64_t ${w} = 0;`);
636
+ this.line(`if (ts_benc_${s.name}(&${place.lv}, ${room.dst} + ${room.at}, ${room.cap} - ${room.at}, &${w})) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushBorsh() past the FixedVec's room");`);
637
+ this.line(`${room.at} += ${w};`);
638
+ };
639
+ }
640
+ const list = kind === "vec" ? this.listSpan(arg) : undefined;
641
+ if (list) {
642
+ // A Borsh Vec: the count as u32, then the elements (their fixed layout is their Borsh form).
643
+ if (!borshIdentical(list.elem, this.model))
644
+ this.fail(arg, `a list of ${typeName(list.elem)} has no Borsh form of its own here`);
645
+ const size = this.fieldBytes(list.elem);
646
+ const c = this.tmp("vn");
647
+ this.line(`uint32_t ${c} = (uint32_t)${list.count};`);
648
+ return (put) => {
649
+ put(`&${c}`, "4");
650
+ put(`(const uint8_t *)${list.items}`, `(uint64_t)${c} * ${size}`);
651
+ };
652
+ }
653
+ const val = this.expr(arg);
654
+ if (val.literal !== undefined)
655
+ this.fail(arg, "pushBorsh needs the integer's width: pushLE<u16>(…), pushBorsh(u16(…))");
656
+ // serialize() emits its temporaries between the pieces; collect them and replay into the writer.
657
+ return (put) => this.serialize(val, arg, (src, n) => put(src, n));
658
+ }
410
659
  }
@@ -235,6 +235,7 @@ export class CpiEmitter extends MetaplexEmitter {
235
235
  this.line(`for (uint64_t ${i}b = ${base} + ${range.from}; ${i}b < ${base} + ${range.to}; ${i}b++) ts_info(params->ka[${i}b], &params->infos[${k}++]);`);
236
236
  const ixName = this.tmp("cpi");
237
237
  this.line(`SolInstruction ${ixName} = {&${programKey}, ${m}, ${n}, (uint8_t *)${data.items}, ${data.count}};`);
238
+ this.forgetOwners();
238
239
  if (multi)
239
240
  this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, ${multi.ptr}, ${multi.count}));`);
240
241
  else if (seeds) {
@@ -325,8 +326,13 @@ export class CpiEmitter extends MetaplexEmitter {
325
326
  const ft = f.type;
326
327
  const t = this.tmp("evv");
327
328
  this.line(`${fixedVecC(ft)} ${t};`);
328
- this.line(`ts_memzero(&${t}, sizeof(${t}));`);
329
- this.writeAggregate({ lv: t, type: ft, writable: true }, e);
329
+ // A literal is built in place, its free slots zeroed; anything else may fill only the first ones.
330
+ if (this.isListLiteral(e))
331
+ this.writeAggregate({ lv: t, type: ft, writable: true }, e, true);
332
+ else {
333
+ this.line(`ts_memzero_bulk(&${t}, sizeof(${t}));`);
334
+ this.writeAggregate({ lv: t, type: ft, writable: true }, e);
335
+ }
330
336
  const n = this.fieldBytes(ft);
331
337
  return (put) => put(`&${t}`, String(n), n);
332
338
  }
@@ -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;
@@ -260,8 +260,10 @@ export class ExpressionEmitter extends StorageEmitter {
260
260
  this.fail(node, `"${node.text}" is a function: call it (${node.text}(…)), bind it with const, or pass it to a helper or list method; it cannot be stored or returned as a value`);
261
261
  if (l.type.kind === "array")
262
262
  this.fail(node, `"${node.text}" is an array; use .get(i)`);
263
- if (l.type.kind === "vec")
263
+ if (l.type.kind === "vec" || l.type.kind === "rawArray")
264
264
  this.fail(node, `"${node.text}" is a list; use .get(i) and .length`);
265
+ if (l.type.kind === "rbTree")
266
+ this.fail(node, `"${node.text}" is a RedBlackTree; use its methods (get, insert, remove, min, max, for … of)`);
265
267
  if (l.type.kind === "remaining")
266
268
  return { c: l.c, type: l.type };
267
269
  return l.type.kind === "pubkey" && !l.ptr ? { c: `(&${l.c})`, type: l.type } : { c: l.c, type: l.type };
@@ -270,6 +272,8 @@ export class ExpressionEmitter extends StorageEmitter {
270
272
  if (k) {
271
273
  if (typeof k.value === "boolean")
272
274
  return { c: k.value ? "true" : "false", type: BOOL };
275
+ if (k.value === null)
276
+ this.fail(node, `${k.name} = null only tells failures to log nothing; it is not a value`);
273
277
  if (typeof k.value === "object")
274
278
  return { c: `(&TSK_${k.name})`, type: PUBKEY };
275
279
  if (typeof k.value === "string") {
@@ -350,6 +354,9 @@ export class ExpressionEmitter extends StorageEmitter {
350
354
  }
351
355
  property(node) {
352
356
  const field = node.name.text;
357
+ const view = this.viewProperty(node);
358
+ if (view)
359
+ return view;
353
360
  // A BigVec's room: the elements the account holds past the struct.
354
361
  if (field === "capacity" && this.peekKind(node.expression) === "vec") {
355
362
  const r = this.ref(node.expression);
@@ -690,7 +697,7 @@ export class ExpressionEmitter extends StorageEmitter {
690
697
  const k = this.model.constants.get(e.text);
691
698
  if (k && typeof k.value === "string")
692
699
  return k.value;
693
- if (k && typeof k.value === "object")
700
+ if (k && typeof k.value === "object" && k.value !== null)
694
701
  return base58(Uint8Array.from(k.value.pubkey));
695
702
  }
696
703
  return undefined;
@@ -878,10 +885,13 @@ export class ExpressionEmitter extends StorageEmitter {
878
885
  }
879
886
  if (exp.type.kind !== "int")
880
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))");
881
891
  const r = this.tmp("pr");
882
892
  const sq = this.tmp("ps");
883
893
  const e = this.tmp("pe");
884
- this.line(`${ct} ${r} = 1;`);
894
+ this.line(`${ct} ${r} = ${type.name === "u256" ? intLiteral(1n, "u256") : "1"};`);
885
895
  this.line(`${ct} ${sq} = ${base.c};`);
886
896
  if (INT_INFO[exp.type.name].signed)
887
897
  this.line(`if (${exp.c} < 0) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: negative exponent");`);
@@ -954,6 +964,11 @@ export class ExpressionEmitter extends StorageEmitter {
954
964
  // An Option<Vec<T>> argument: None leaves its view's pointer NULL (a Some, empty or not, points into the data).
955
965
  if (v.type.kind === "vecArg" && v.type.optional)
956
966
  return { c: `((${v.c}).ptr ${neg ? "!=" : "=="} NULL)`, type: BOOL };
967
+ // A RedBlackTree's get / remove of a struct value (a reference, NULL when absent) and its min / max node.
968
+ if (v.type.kind === "structRef" && v.type.nullable)
969
+ return { c: `(${v.c} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
970
+ if (v.type.kind === "rbEntry")
971
+ return { c: `((${v.c}).index ${neg ? "!=" : "=="} 0)`, type: BOOL };
957
972
  if (v.type.kind !== "option" && v.type.kind !== "optionArg")
958
973
  this.fail(other, "only Option values can be compared with null");
959
974
  return { c: neg ? `((${v.c}).some != 0)` : `((${v.c}).some == 0)`, type: BOOL };
@@ -1066,9 +1081,24 @@ export class ExpressionEmitter extends StorageEmitter {
1066
1081
  const t = this.tmp();
1067
1082
  const K = ts.SyntaxKind;
1068
1083
  this.line(`${ct} ${t};`);
1069
- const overflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
1084
+ const failOverflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
1070
1085
  if (type.name === "u256")
1071
- return this.arith256(op, left, right, node, t, overflow);
1086
+ return this.arith256(op, left, right, node, t, failOverflow);
1087
+ // Inside panicsAt(location, …): Rust's panic, with the message its overflow checks give this operator.
1088
+ const at = this.panicAt;
1089
+ const rust = (message) => `{ ${this.panicC(message, at).join(" ")} }`;
1090
+ const negate = ts.isPrefixUnaryExpression(node) && node.operator === K.MinusToken;
1091
+ const rustOverflow = {
1092
+ [K.PlusToken]: "attempt to add with overflow",
1093
+ [K.MinusToken]: negate ? "attempt to negate with overflow" : "attempt to subtract with overflow",
1094
+ [K.AsteriskToken]: "attempt to multiply with overflow",
1095
+ [K.SlashToken]: "attempt to divide with overflow",
1096
+ [K.PercentToken]: "attempt to calculate the remainder with overflow",
1097
+ };
1098
+ const overflow = at && rustOverflow[op] ? rust(rustOverflow[op]) : failOverflow;
1099
+ const divZero = at && (op === K.SlashToken || op === K.PercentToken)
1100
+ ? rust(op === K.SlashToken ? "attempt to divide by zero" : "attempt to calculate the remainder with a divisor of zero")
1101
+ : `TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero")`;
1072
1102
  switch (op) {
1073
1103
  case K.PlusToken:
1074
1104
  // u64 through the runtime helpers: one compare instead of a materialized carry flag on SBF.
@@ -1084,7 +1114,7 @@ export class ExpressionEmitter extends StorageEmitter {
1084
1114
  break;
1085
1115
  case K.SlashToken:
1086
1116
  case K.PercentToken: {
1087
- this.line(`if (${right.c} == 0) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
1117
+ this.line(`if (${right.c} == 0) ${divZero};`);
1088
1118
  if (INT_INFO[type.name].signed)
1089
1119
  this.line(`if (${left.c} == ${intLiteral(INT_INFO[type.name].min, type.name)} && ${right.c} == -1) ${overflow};`);
1090
1120
  if (type.name === "u128")
@@ -1104,16 +1134,22 @@ export class ExpressionEmitter extends StorageEmitter {
1104
1134
  // (in JS the bigint would just grow). `>>` on signed types is arithmetic, as in JS.
1105
1135
  if (right.type.kind !== "int")
1106
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");
1107
1139
  const bits = INT_INFO[type.name].bytes * 8;
1108
1140
  const sh = this.tmp("sh");
1109
1141
  const rinfo = INT_INFO[right.type.name];
1110
- this.line(`if (${rinfo.signed ? `${right.c} < 0 || ` : ""}${right.c} >= ${bits}) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range");`);
1142
+ // Rust's shift check is the amount only; the bits `<<` loses below stay TypeSOL's failure (JS's bigint keeps them).
1143
+ const range = at !== undefined
1144
+ ? rust(op === K.LessThanLessThanToken ? "attempt to shift left with overflow" : "attempt to shift right with overflow")
1145
+ : `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range")`;
1146
+ this.line(`if (${rinfo.signed ? `${right.c} < 0 || ` : ""}${right.c} >= ${bits}) ${range};`);
1111
1147
  this.line(`uint64_t ${sh} = (uint64_t)(${right.c});`);
1112
1148
  if (op === K.GreaterThanGreaterThanToken)
1113
1149
  this.line(`${t} = (${ct})(${left.c} >> ${sh});`);
1114
1150
  else {
1115
1151
  this.line(`${t} = (${ct})((${unsignedC(type.name)})${left.c} << ${sh});`);
1116
- this.line(`if ((${ct})(${t} >> ${sh}) != ${left.c}) ${overflow};`);
1152
+ this.line(`if ((${ct})(${t} >> ${sh}) != ${left.c}) ${failOverflow};`);
1117
1153
  }
1118
1154
  break;
1119
1155
  }
@@ -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))
@@ -1,12 +1,15 @@
1
+ import ts from "typescript";
1
2
  import { accountLimit, cBytes, scalarStorageC, optC, storageDecl, helperSignature, fieldC, fixedVecC, laterVecC } from "./shared.js";
2
3
  import { FunctionEmitter } from "./function.js";
3
4
  import { emitBorshCodecs, emitNativeBorshCodecs } from "./borsh.js";
5
+ import { emitRbTrees } from "./rbtree.js";
4
6
  /**
5
7
  * The whole C translation unit: type declarations (structs, options, enums, events), every helper and instruction
6
8
  * (lowered by FunctionEmitter), and the entry point that dispatches on the instruction discriminator.
7
9
  */
8
10
  export function emitProgram(analysis, opts = {}) {
9
11
  const { model, reporter } = analysis;
12
+ model.ownerCache = makesNativeViews(model);
10
13
  // Bodies first: they register events, string-literal errors and PDA descriptions.
11
14
  const helperBodies = [];
12
15
  const emittedHelpers = new Set();
@@ -56,11 +59,26 @@ export function emitProgram(analysis, opts = {}) {
56
59
  else if (panicFlag.value)
57
60
  out.push(`#define TS_PANIC_ON_OVERFLOW 1`);
58
61
  }
62
+ // `const PANIC_STYLE = "solana-1.14"`: panics log as solana_program 1.14's panic handler does and abort (read by the
63
+ // emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
64
+ const panicStyle = model.constants.get("PANIC_STYLE");
65
+ if (panicStyle) {
66
+ if (panicStyle.value !== "solana-1.14")
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); leave it out for the default");
68
+ else if (panicFlag?.value === true)
69
+ out.push(`#define TS_PANIC_ABORT 1`);
70
+ }
59
71
  // `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut / storeBorsh / BigVec writes leave writability and aliasing to the
60
72
  // runtime, as a native program does (read by the emitter; nothing to define in C).
61
73
  const nativeWrites = model.constants.get("NATIVE_ACCOUNT_WRITES");
62
74
  if (nativeWrites && typeof nativeWrites.value !== "boolean")
63
75
  reporter.error(analysis.sourceFile, "NATIVE_ACCOUNT_WRITES must be true or false");
76
+ // resizeAccount on a remaining account: the entrypoint records every account's size when the instruction starts.
77
+ if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_entry_len(")))
78
+ out.push(`#define TS_RECORD_ENTRY_LEN 1`);
79
+ // Native account views share one owner-check cache (ts_owned), zeroed in the entry point.
80
+ if (model.ownerCache)
81
+ out.push(`#define TS_OWNER_CACHE 1`);
64
82
  // An error with code 0 must not return 0 (success): see ts_fail.
65
83
  if ([...model.errorEnums.values()].some((m) => [...m.values()].some((e) => e.code === 0)))
66
84
  out.push(`#define TS_CUSTOM_ZERO 1`);
@@ -167,7 +185,7 @@ export function emitProgram(analysis, opts = {}) {
167
185
  for (const t of model.localVecs.values())
168
186
  deps(t);
169
187
  for (const k of model.constants.values())
170
- if (typeof k.value === "object")
188
+ if (typeof k.value === "object" && k.value !== null)
171
189
  out.push(`static const SolPubkey TSK_${k.name} = {${cBytes(k.value.pubkey)}};`);
172
190
  out.push(...emitBorshCodecs(model), ...emitNativeBorshCodecs(model));
173
191
  const helpers = [...model.helpers.values()];
@@ -175,6 +193,8 @@ export function emitProgram(analysis, opts = {}) {
175
193
  out.push(helperSignature(h) + ";");
176
194
  if (helpers.length)
177
195
  out.push("");
196
+ // RedBlackTree instances: after the helper prototypes (a comparator is a helper), before the code that uses them.
197
+ out.push(...emitRbTrees(model));
178
198
  out.push(...helperBodies, ...ixBodies);
179
199
  const limit = accountLimit(model);
180
200
  out.push(`_Static_assert(TS_MAX_ACCOUNTS == ${limit}, "TS_MAX_ACCOUNTS");`);
@@ -188,6 +208,8 @@ export function emitProgram(analysis, opts = {}) {
188
208
  // Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
189
209
  if (limit > 32)
190
210
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
211
+ if (model.ownerCache)
212
+ out.push(` params.owned = NULL;`);
191
213
  if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?(_rec)?\(/.test(b)))
192
214
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
193
215
  const fallback = model.instructions.find((ix) => ix.fallback);
@@ -216,3 +238,10 @@ export function emitProgram(analysis, opts = {}) {
216
238
  out.push(`}`);
217
239
  return out.join("\n") + "\n";
218
240
  }
241
+ /** The views whose owner checks share the cache (see ProgramModel.ownerCache). */
242
+ const NATIVE_VIEWS = new Set(["loadRaw", "loadRawMut", "loadRawAt", "loadRawMutAt", "rawArrayAt", "rawArrayMutAt", "rbTreeAt", "rbTreeMutAt"]);
243
+ /** Whether any function of the program calls one of the native views (by name: a false positive only costs a store). */
244
+ function makesNativeViews(model) {
245
+ const calls = (n) => (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && NATIVE_VIEWS.has(n.expression.text)) || !!ts.forEachChild(n, calls);
246
+ return [...model.instructions, ...model.helpers.values(), ...model.generics.values()].some((f) => calls(f.node));
247
+ }
@@ -0,0 +1,7 @@
1
+ import { type ProgramModel } from "../model.js";
2
+ /**
3
+ * The C functions of each RedBlackTree instance (`rbTreeAt<K, V>(…, compare?)`): its key order, and lib-sokoban 0.3's
4
+ * get_addr, _insert and _remove over runtime/typesol_rt.h's structural functions (ts_rbt_*), with the node stride a
5
+ * constant. Each returns SUCCESS or the error a comparator helper failed with; results go through `out`.
6
+ */
7
+ export declare function emitRbTrees(model: ProgramModel): string[];