@typesol/cli 0.41.0 → 0.43.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 (62) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -7
  3. package/dist/compiler/analyze.js +484 -13
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +65 -7
  9. package/dist/compiler/emit/base.js +91 -7
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +169 -2
  13. package/dist/compiler/emit/calls.js +1170 -81
  14. package/dist/compiler/emit/cpi-core.d.ts +28 -5
  15. package/dist/compiler/emit/cpi-core.js +238 -12
  16. package/dist/compiler/emit/cpi.js +16 -16
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +89 -9
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +37 -3
  24. package/dist/compiler/emit/rbtree.d.ts +7 -0
  25. package/dist/compiler/emit/rbtree.js +142 -0
  26. package/dist/compiler/emit/shared.d.ts +43 -1
  27. package/dist/compiler/emit/shared.js +18 -2
  28. package/dist/compiler/emit/statements.d.ts +58 -1
  29. package/dist/compiler/emit/statements.js +549 -22
  30. package/dist/compiler/emit/storage.d.ts +48 -1
  31. package/dist/compiler/emit/storage.js +220 -63
  32. package/dist/compiler/emit/token.d.ts +11 -8
  33. package/dist/compiler/emit/token.js +233 -104
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/hints.js +6 -0
  37. package/dist/compiler/idl.js +2 -1
  38. package/dist/compiler/model.d.ts +84 -4
  39. package/dist/compiler/model.js +19 -0
  40. package/dist/compiler/toolchain.d.ts +15 -0
  41. package/dist/compiler/toolchain.js +146 -11
  42. package/dist/testing-stake.d.ts +216 -0
  43. package/dist/testing-stake.js +526 -0
  44. package/dist/testing.d.ts +1 -0
  45. package/dist/testing.js +1 -0
  46. package/docs/architecture.md +9 -2
  47. package/docs/case-study-phoenix.md +226 -0
  48. package/docs/case-study-spl-stake-pool.md +122 -0
  49. package/docs/errors.md +1 -1
  50. package/docs/language.md +244 -20
  51. package/docs/migrate-from-anchor.md +1 -0
  52. package/docs/runtime.md +1 -1
  53. package/docs/security-model.md +4 -0
  54. package/docs/stability.md +33 -1
  55. package/docs/test-your-program.md +47 -0
  56. package/docs/testing.md +19 -0
  57. package/docs/troubleshooting.md +5 -2
  58. package/lib/typesol.d.ts +462 -44
  59. package/llms-full.txt +338 -26
  60. package/llms.txt +1 -1
  61. package/package.json +2 -2
  62. package/runtime/typesol_rt.h +476 -0
@@ -1,9 +1,9 @@
1
1
  import ts from "typescript";
2
2
  import { type AccountParam, type IdlSeed } from "../model.js";
3
- import { type Value } 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.
@@ -27,7 +27,11 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
27
27
  to: string;
28
28
  asPassed?: boolean;
29
29
  }): void;
30
- protected signerSeeds(node: ts.Expression | undefined, authority: AccountParam, at: ts.Node): {
30
+ /**
31
+ * The seeds a CPI is signed with, or none: then a declared authority must be a Signer. A remaining account (a
32
+ * CpiAcct without `param`) is left to the runtime, which refuses a signer meta for an account that did not sign.
33
+ */
34
+ protected signerSeeds(node: ts.Expression | undefined, authority: AccountParam | CpiAcct, at: ts.Node): {
31
35
  name: string;
32
36
  count: number | string;
33
37
  };
@@ -50,11 +54,13 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
50
54
  protected keyOf(n: ts.Expression): ts.Expression;
51
55
  /**
52
56
  * `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
53
- * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
57
+ * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account, and
58
+ * `base`, the index of that account among the instruction's (a helper's RemainingAccounts parameter carries it).
54
59
  */
55
60
  protected remainingRange(node: ts.Expression): {
56
61
  from: string;
57
62
  to: string;
63
+ base: string;
58
64
  } | undefined;
59
65
  /**
60
66
  * A byte buffer written front to back. Its C declaration is patched in afterwards so it is
@@ -75,4 +81,21 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
75
81
  protected nestedStructs(name: string): Set<string>;
76
82
  /** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
77
83
  protected fixedLayoutStructs(): Set<string>;
84
+ /**
85
+ * Byte builders on a `FixedVec<u8, N>` (a local list or one in account data), for a native program's hand-built byte
86
+ * strings (Phoenix's event batches: `[15] ‖ Borsh(header) ‖ events`, a u16 count patched in, truncated back to the
87
+ * header after each flush): `pushLE` (an integer at its width), `pushKey` (32 bytes), `pushBorsh` (a value's Borsh
88
+ * encoding, the codecs invoke, events and storeBorsh use), `setLE(offset, v)` (overwrite within the length) and
89
+ * `truncate(n)`. Every write is bounds-checked (5104) and the length moves only once all of it fit, so a failed call
90
+ * appends nothing.
91
+ */
92
+ protected byteListMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
93
+ /**
94
+ * `pushBorsh(value)`: lower the value now and return the writer of its Borsh bytes. Structs (a place, or an object
95
+ * literal given its type: `pushBorsh<Header>({ … })`) are their fixed layout when that is their Borsh form, else go
96
+ * through the struct's Borsh encoder (storeBorsh's); data enums are a tag and the variant's fields, FixedArrays their
97
+ * elements, lists a u32 count and their elements, and integers, booleans, Pubkeys, strings and Options as in invoke
98
+ * data.
99
+ */
100
+ private borshPiece;
78
101
  }
@@ -1,10 +1,11 @@
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.
@@ -132,7 +133,7 @@ export class CpiCoreEmitter extends CallEmitter {
132
133
  const k = this.model.constants.get(el.text);
133
134
  if (k && typeof k.value === "string")
134
135
  return { kind: "const", value: [...Buffer.from(k.value, "utf8")] };
135
- if (k && typeof k.value === "object")
136
+ if (k && typeof k.value === "object" && k.value !== null)
136
137
  return { kind: "const", value: k.value.pubkey };
137
138
  if (k && typeof k.value === "bigint") {
138
139
  // Little-endian two's complement in the constant's width (16 bytes for u128/i128), as the program hashes it.
@@ -178,9 +179,14 @@ export class CpiCoreEmitter extends CallEmitter {
178
179
  this.line(`for (uint64_t ${i} = ${n} + ${tail.from}; ${i} < ${n} + ${tail.to}; ${i}++) ${m}[${cnt}++] = (SolAccountMeta){&params->ka[${i}]->key, ${tail.asPassed ? `params->ka[${i}]->is_writable` : 0}, 0};`);
179
180
  this.line(`TS_TRY(ts_cpi(params, ${program}, ${buf}, ${len}, ${m}, ${cnt}, ${seeds.name}, ${seeds.count}));`);
180
181
  }
182
+ /**
183
+ * The seeds a CPI is signed with, or none: then a declared authority must be a Signer. A remaining account (a
184
+ * CpiAcct without `param`) is left to the runtime, which refuses a signer meta for an account that did not sign.
185
+ */
181
186
  signerSeeds(node, authority, at) {
182
187
  if (!node) {
183
- if (authority.kind.kind !== "signer")
188
+ const declared = "c" in authority ? authority.param : authority;
189
+ if (declared && declared.kind.kind !== "signer")
184
190
  this.fail(at, "the authority must be a Signer, or pass signerSeeds for a PDA authority");
185
191
  return { name: "NULL", count: 0 };
186
192
  }
@@ -236,18 +242,18 @@ export class CpiCoreEmitter extends CallEmitter {
236
242
  }
237
243
  /**
238
244
  * `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
239
- * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
245
+ * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account, and
246
+ * `base`, the index of that account among the instruction's (a helper's RemainingAccounts parameter carries it).
240
247
  */
241
248
  remainingRange(node) {
242
249
  const sliced = ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "slice";
243
250
  if (!this.isRemaining(node) && !(sliced && this.isRemaining(node.expression.expression)))
244
251
  return undefined;
245
- if (!this.ix)
246
- this.fail(node, "pass the remaining accounts to a CPI from the instruction; a helper reads them one at a time with .get(i)");
247
- const n = this.ix.accounts.length;
252
+ // In a helper: the RemainingAccounts parameter (remainingBase refuses remainingAccounts() there, with a hint).
253
+ const n = this.ix ? this.ix.accounts.length : this.remainingBase(sliced ? node.expression.expression : node);
248
254
  const count = `(params->ka_num - ${n})`;
249
255
  if (this.isRemaining(node))
250
- return { from: "0", to: count };
256
+ return { from: "0", to: count, base: String(n) };
251
257
  if (!ts.isCallExpression(node))
252
258
  return undefined;
253
259
  if (node.arguments.length < 1 || node.arguments.length > 2)
@@ -256,7 +262,7 @@ export class CpiCoreEmitter extends CallEmitter {
256
262
  const from = this.index(node.arguments[0], `${count} + 1`);
257
263
  const to = node.arguments[1] ? this.index(node.arguments[1], `${count} + 1`) : count;
258
264
  this.line(`if (${from} > ${to}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: remaining accounts slice out of range");`);
259
- return { from, to };
265
+ return { from, to, base: String(n) };
260
266
  }
261
267
  /**
262
268
  * A byte buffer written front to back. Its C declaration is patched in afterwards so it is
@@ -402,4 +408,224 @@ export class CpiCoreEmitter extends CallEmitter {
402
408
  visit({ kind: "struct", name });
403
409
  return out;
404
410
  }
411
+ /**
412
+ * Byte builders on a `FixedVec<u8, N>` (a local list or one in account data), for a native program's hand-built byte
413
+ * strings (Phoenix's event batches: `[15] ‖ Borsh(header) ‖ events`, a u16 count patched in, truncated back to the
414
+ * header after each flush): `pushLE` (an integer at its width), `pushKey` (32 bytes), `pushBorsh` (a value's Borsh
415
+ * encoding, the codecs invoke, events and storeBorsh use), `setLE(offset, v)` (overwrite within the length) and
416
+ * `truncate(n)`. Every write is bounds-checked (5104) and the length moves only once all of it fit, so a failed call
417
+ * appends nothing.
418
+ */
419
+ byteListMethod(node, method, v) {
420
+ const args = node.arguments;
421
+ const info = v.vec;
422
+ const vt = v.type;
423
+ if (info.cap === undefined || info.heap || info.big !== undefined || vt.elem.kind !== "int" || vt.elem.name !== "u8")
424
+ this.fail(node.expression, `${method}() builds bytes in a FixedVec<u8, N> (a local list, or one in account data)`);
425
+ if (!v.writable)
426
+ this.fail(node, this.readOnly(v));
427
+ const cap = info.cap;
428
+ const bytes = `((uint8_t *)${info.items})`;
429
+ const count = vecCount(info);
430
+ /** An integer at a width: the type argument's, or the value's own (a bare literal has none). */
431
+ const intValue = (valueNode, fn) => {
432
+ const targ = node.typeArguments?.[0];
433
+ const t = targ ? resolveScalarType(targ, this.scope) : undefined;
434
+ if (targ && (!t || t.kind !== "int"))
435
+ this.fail(targ, `${fn}<T>: T is an integer type (u8 … u128, i8 … i128)`);
436
+ const val = t ? this.expect(this.expr(valueNode, t), t, valueNode) : this.expr(valueNode);
437
+ if (val.literal !== undefined)
438
+ this.fail(valueNode, `${fn} needs the integer's width: ${fn}<u16>(…) or ${fn}(u16(…))`);
439
+ if (val.type.kind !== "int")
440
+ this.fail(valueNode, `${fn} takes an integer (u8 … u128, i8 … i128)${val.type.kind === "pubkey" ? "; a Pubkey is pushKey(key)" : ""}`);
441
+ if (val.type.name === "u256")
442
+ this.fail(valueNode, "u256 is for computation: convert to u128 (or smaller) first");
443
+ return val;
444
+ };
445
+ switch (method) {
446
+ case "truncate": {
447
+ // Vec::truncate, but a length past the current one fails (Rust's `drain(n..)` panics there) instead of doing nothing.
448
+ if (args.length !== 1)
449
+ this.fail(node, "truncate(length) takes the new length");
450
+ const k = this.expect(this.expr(args[0], U64), U64, args[0]);
451
+ const n = this.tmp("n");
452
+ this.line(`uint64_t ${n} = ${k.c};`);
453
+ this.line(`if (${n} > ${count}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: truncate() past the FixedVec's length");`);
454
+ this.line(`${info.len} = (uint32_t)${n};`);
455
+ return undefined;
456
+ }
457
+ case "setLE": {
458
+ // `data[off..off + size].copy_from_slice(&v.to_le_bytes())`: within the length, as Rust's slice indexing.
459
+ if (args.length !== 2)
460
+ this.fail(node, "setLE(offset, value) takes a byte offset and an integer");
461
+ const off = this.expect(this.expr(args[0], U64), U64, args[0]);
462
+ const o = this.tmp("off");
463
+ this.line(`uint64_t ${o} = ${off.c};`);
464
+ const val = intValue(args[1], "setLE");
465
+ const size = scalarSize(val.type);
466
+ const ct = scalarStorageC(val.type);
467
+ const w = this.tmp("le");
468
+ this.line(`${ct} ${w} = (${ct})(${val.c});`);
469
+ this.line(`if (${o} > ${count} || ${count} - ${o} < ${size}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: setLE() past the FixedVec's length");`);
470
+ this.line(`ts_memcpy(${bytes} + ${o}, &${w}, ${size});`);
471
+ return undefined;
472
+ }
473
+ }
474
+ if (args.length !== 1)
475
+ this.fail(node, `${method}(value) takes one value`);
476
+ const arg = args[0];
477
+ // The value first (as JS evaluates the argument before the call runs), then its bytes after the current length.
478
+ let write;
479
+ if (method === "pushLE") {
480
+ const val = intValue(arg, "pushLE");
481
+ const ct = scalarStorageC(val.type);
482
+ const w = this.tmp("le");
483
+ this.line(`${ct} ${w} = (${ct})(${val.c});`);
484
+ write = (put) => put(`&${w}`, String(scalarSize(val.type)));
485
+ }
486
+ else if (method === "pushKey") {
487
+ if (node.typeArguments?.length)
488
+ this.fail(node, "pushKey(key) takes no type argument");
489
+ const k = this.expect(this.expr(arg, PUBKEY), PUBKEY, arg);
490
+ const t = this.tmp("key");
491
+ this.line(`SolPubkey ${t} = *(${k.c});`);
492
+ write = (put) => put(`&${t}`, "32");
493
+ }
494
+ else
495
+ write = this.borshPiece(node, arg);
496
+ const at = this.tmp("at");
497
+ this.line(`uint64_t ${at} = ${count};`);
498
+ write((src, n) => {
499
+ this.line(`if (${n} > ${cap} - ${at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: ${method}() past the FixedVec's room");`);
500
+ this.line(`ts_memcpy(${bytes} + ${at}, ${src}, ${n});`);
501
+ this.line(`${at} += ${n};`);
502
+ }, { dst: bytes, cap: String(cap), at });
503
+ this.line(`${info.len} = (uint32_t)${at};`);
504
+ return undefined;
505
+ }
506
+ /**
507
+ * `pushBorsh(value)`: lower the value now and return the writer of its Borsh bytes. Structs (a place, or an object
508
+ * literal given its type: `pushBorsh<Header>({ … })`) are their fixed layout when that is their Borsh form, else go
509
+ * through the struct's Borsh encoder (storeBorsh's); data enums are a tag and the variant's fields, FixedArrays their
510
+ * elements, lists a u32 count and their elements, and integers, booleans, Pubkeys, strings and Options as in invoke
511
+ * data.
512
+ */
513
+ borshPiece(node, arg) {
514
+ const targ = node.typeArguments?.[0];
515
+ let r;
516
+ if (ts.isObjectLiteralExpression(arg)) {
517
+ const name = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? targ.typeName.text : undefined;
518
+ const type = name && this.model.structs.get(name)?.size !== undefined
519
+ ? { kind: "struct", name }
520
+ : name && this.model.dataEnums.has(name)
521
+ ? { kind: "dataEnum", name }
522
+ : undefined;
523
+ if (!type)
524
+ 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");
525
+ // A data enum literal of a fixed-size variant: the tag and the variant's fields (packed, their Borsh form) in a
526
+ // temporary of exactly those bytes, then one room check and one copy. Not the whole enum zeroed, filled and
527
+ // copied, then written as a tag and a switch on it.
528
+ if (type.kind === "dataEnum") {
529
+ const lit = this.dataEnumLiteral(type.name, arg);
530
+ const size = 1 + lit.variant.fields.reduce((n, f) => n + this.fieldBytes(f.type), 0);
531
+ // Integers, booleans, enums and Pubkeys: each field's value in a local of its own (in source order), then one
532
+ // room check and a store of each at its offset, as pushLE would write them one by one.
533
+ if (lit.variant.fields.every((f) => isScalar(f.type))) {
534
+ const locals = new Map(lit.variant.fields.map((f) => [f.name, this.tmp("bf")]));
535
+ for (const f of lit.variant.fields)
536
+ this.line(`${fieldC(f.type)} ${locals.get(f.name)};`);
537
+ lit.writeFields((field) => locals.get(field));
538
+ return (_put, room) => {
539
+ this.line(`if (${size} > ${room.cap} - ${room.at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushBorsh() past the FixedVec's room");`);
540
+ this.line(`${room.dst}[${room.at}] = ${lit.vi};`);
541
+ let off = 1;
542
+ for (const f of lit.variant.fields) {
543
+ const n = this.fieldBytes(f.type);
544
+ this.line(`ts_memcpy(${room.dst} + ${room.at} + ${off}, &${locals.get(f.name)}, ${n});`);
545
+ off += n;
546
+ }
547
+ this.line(`${room.at} += ${size};`);
548
+ };
549
+ }
550
+ if (lit.variant.fields.every((f) => borshIdentical(f.type, this.model))) {
551
+ const t = this.tmp("bv");
552
+ this.line(`struct __attribute__((packed)) { uint8_t tag; TSV_${lit.e.name}__${lit.variant.name} v; } ${t};`);
553
+ this.line(`${t}.tag = ${lit.vi};`);
554
+ lit.writeFields(`${t}.v`);
555
+ return (put) => put(`&${t}`, String(size));
556
+ }
557
+ }
558
+ const t = this.tmp("bv");
559
+ this.line(`${fieldC(type)} ${t};`);
560
+ if (type.kind === "struct")
561
+ this.line(`ts_memzero(&${t}, sizeof(${t}));`);
562
+ this.writeAggregate({ lv: t, type, writable: true }, arg, true);
563
+ r = { lv: t, type, writable: true };
564
+ }
565
+ else if (targ)
566
+ this.fail(targ, "pushBorsh<T> takes a type only for an object literal; the value's own type is used otherwise");
567
+ const kind = r?.type.kind ?? this.peekKind(arg);
568
+ if (kind === "struct" || kind === "array" || kind === "dataEnum") {
569
+ r ??= this.ref(arg);
570
+ const place = r;
571
+ if (place.type.kind === "dataEnum") {
572
+ const name = place.type.name;
573
+ const e = this.model.dataEnums.get(name);
574
+ // Fixed-size payloads are packed in the variant's C struct as Borsh lays them out: the tag, then one copy.
575
+ if (e.variants.every((v) => v.fields.every((f) => borshIdentical(f.type, this.model))))
576
+ return (put) => {
577
+ put(`&${place.lv}.tag`, "1");
578
+ if (e.variants.every((v) => !v.fields.length))
579
+ return;
580
+ this.line(`switch (${place.lv}.tag) {`);
581
+ e.variants.forEach((v, i) => {
582
+ const size = v.fields.reduce((n, f) => n + this.fieldBytes(f.type), 0);
583
+ if (!size)
584
+ return;
585
+ this.line(`case ${i}: {`);
586
+ put(`&${place.lv}.v.${v.name}`, String(size));
587
+ this.line(`break; }`);
588
+ });
589
+ this.line(`}`);
590
+ };
591
+ return (put) => this.serializeDataEnumLv(place.lv, name, (src, n) => put(src, n));
592
+ }
593
+ if (borshIdentical(place.type, this.model)) {
594
+ const n = this.fieldBytes(place.type);
595
+ return (put) => put(`&${place.lv}`, String(n));
596
+ }
597
+ if (place.type.kind === "array")
598
+ this.fail(arg, `${typeName(place.type)} has no Borsh form of its own here (its elements hold Options, data enums or text)`);
599
+ const s = this.model.structs.get(place.type.name);
600
+ const why = borshNativeStructUnsupported(s, this.model);
601
+ if (why)
602
+ this.fail(arg, `pushBorsh cannot encode ${s.name}: ${why}`);
603
+ this.model.borshNative.add(s.name);
604
+ return (_put, room) => {
605
+ // The encoder writes into the room left and reports how much it wrote; the length moves only afterwards.
606
+ const w = this.tmp("bw");
607
+ this.line(`uint64_t ${w} = 0;`);
608
+ 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");`);
609
+ this.line(`${room.at} += ${w};`);
610
+ };
611
+ }
612
+ const list = kind === "vec" ? this.listSpan(arg) : undefined;
613
+ if (list) {
614
+ // A Borsh Vec: the count as u32, then the elements (their fixed layout is their Borsh form).
615
+ if (!borshIdentical(list.elem, this.model))
616
+ this.fail(arg, `a list of ${typeName(list.elem)} has no Borsh form of its own here`);
617
+ const size = this.fieldBytes(list.elem);
618
+ const c = this.tmp("vn");
619
+ this.line(`uint32_t ${c} = (uint32_t)${list.count};`);
620
+ return (put) => {
621
+ put(`&${c}`, "4");
622
+ put(`(const uint8_t *)${list.items}`, `(uint64_t)${c} * ${size}`);
623
+ };
624
+ }
625
+ const val = this.expr(arg);
626
+ if (val.literal !== undefined)
627
+ this.fail(arg, "pushBorsh needs the integer's width: pushLE<u16>(…), pushBorsh(u16(…))");
628
+ // serialize() emits its temporaries between the pieces; collect them and replay into the writer.
629
+ return (put) => this.serialize(val, arg, (src, n) => put(src, n));
630
+ }
405
631
  }
@@ -196,22 +196,13 @@ export class CpiEmitter extends MetaplexEmitter {
196
196
  */
197
197
  invokeInstruction(node) {
198
198
  const a = node.arguments;
199
- if (!this.ix)
200
- this.fail(node, "invokeInstruction is only available in instructions (it passes remaining accounts)");
201
199
  if (a.length !== 4 && a.length !== 5)
202
200
  this.fail(node, "invokeInstruction(programId, accounts, data, infos, signerSeeds?) takes 4 or 5 arguments");
203
201
  const program = this.expect(this.expr(a[0], PUBKEY), PUBKEY, a[0]);
204
202
  const programKey = this.tmp("dprog");
205
203
  this.line(`SolPubkey ${programKey} = *(${program.c});`);
206
- const list = (e, what) => {
207
- const l = ts.isIdentifier(e) ? this.lookup(e.text) : undefined;
208
- if (l?.type.kind === "vecArg")
209
- return { items: `${l.c}.ptr`, count: `((uint64_t)${l.c}.len)`, elem: l.type.elem };
210
- const r = this.ref(e);
211
- if (r?.vec && r.type.kind === "vec")
212
- return { items: `${r.vec.items}`, count: vecCount(r.vec), elem: r.type.elem };
213
- this.fail(e, `${what}: a Vec or FixedVec (account data, an argument or a local list)`);
214
- };
204
+ // A Vec, FixedVec or FixedArray (account data, an argument or a local list), the instruction data or a slice of it.
205
+ const list = (e, what) => this.listSpan(e) ?? this.fail(e, `${what}: a Vec or FixedVec (account data, an argument or a local list)`);
215
206
  const metas = list(a[1], "the accounts");
216
207
  const elem = metas.elem;
217
208
  const st = elem.kind === "struct" ? this.model.structs.get(elem.name) : undefined;
@@ -221,7 +212,9 @@ export class CpiEmitter extends MetaplexEmitter {
221
212
  const data = list(a[2], "the data");
222
213
  if (data.elem.kind !== "int" || data.elem.name !== "u8")
223
214
  this.fail(a[2], "the data is a list of u8");
224
- const range = this.remainingRange(a[3]) ?? this.fail(a[3], "pass the accounts the CPI may use: remainingAccounts() or rest.slice(a, b)");
215
+ // In a helper: its RemainingAccounts parameter (or a slice of it).
216
+ const range = this.remainingRange(a[3]) ??
217
+ this.fail(a[3], "pass the accounts the CPI may use: remainingAccounts() or rest.slice(a, b) (in a helper, its RemainingAccounts parameter)");
225
218
  const multi = a.length === 5 ? this.signerSets(a[4]) : undefined;
226
219
  const seeds = a.length === 5 && !multi ? this.signingSeeds(a[4]) : undefined;
227
220
  const n = this.tmp("dn");
@@ -236,12 +229,13 @@ export class CpiEmitter extends MetaplexEmitter {
236
229
  this.line(` ${m}[${i}] = (SolAccountMeta){(SolPubkey *)&e->pubkey, e->isWritable != 0, e->isSigner != 0};`);
237
230
  this.line(`}`);
238
231
  // Every account offered goes along as an AccountInfo (ts_invoke's scratch holds TS_MAX_ACCOUNTS of them).
239
- const base = this.ix.accounts.length;
232
+ const base = range.base;
240
233
  this.line(`uint64_t ${k} = 0;`);
241
234
  this.line(`TS_INFOS_RESERVE(params, (${range.to}) - (${range.from}));`);
242
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}++]);`);
243
236
  const ixName = this.tmp("cpi");
244
237
  this.line(`SolInstruction ${ixName} = {&${programKey}, ${m}, ${n}, (uint8_t *)${data.items}, ${data.count}};`);
238
+ this.forgetOwners();
245
239
  if (multi)
246
240
  this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, ${multi.ptr}, ${multi.count}));`);
247
241
  else if (seeds) {
@@ -332,8 +326,13 @@ export class CpiEmitter extends MetaplexEmitter {
332
326
  const ft = f.type;
333
327
  const t = this.tmp("evv");
334
328
  this.line(`${fixedVecC(ft)} ${t};`);
335
- this.line(`ts_memzero(&${t}, sizeof(${t}));`);
336
- 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
+ }
337
336
  const n = this.fieldBytes(ft);
338
337
  return (put) => put(`&${t}`, String(n), n);
339
338
  }
@@ -438,7 +437,8 @@ export class CpiEmitter extends MetaplexEmitter {
438
437
  const b = this.tmp("evb");
439
438
  const w = this.tmp("evw");
440
439
  // One pair of heap buffers per emit site, taken on first use: an emit in a loop does not take new heap each pass.
441
- this.hoisted.push(` TSS_${s.name} *${t} = NULL;`, ` uint8_t *${b} = NULL;`);
440
+ this.hoistLazy(t, (n) => `TSS_${s.name} *${n}`);
441
+ this.hoistLazy(b, (n) => `uint8_t *${n}`);
442
442
  this.line(`if (${t} == NULL) TS_TRY(ts_alloc(sizeof(TSS_${s.name}), (uint8_t **)&${t}));`);
443
443
  this.writeAggregate({ lv: `(*${t})`, type: { kind: "struct", name: s.name }, writable: true }, obj);
444
444
  // Borsh never takes more than the fixed layout (a String/Vec is 4 + used bytes, an Option 1 + payload).
@@ -1,6 +1,6 @@
1
1
  import ts from "typescript";
2
2
  import { type AccountParam } from "../model.js";
3
- import { type Value } from "./shared.js";
3
+ import { type Value, type CpiProgram } from "./shared.js";
4
4
  import { CpiCoreEmitter } from "./cpi-core.js";
5
5
  /** Creating accounts: `create` / `createIfNeeded` of program accounts, mints, token accounts and ATAs (with Token-2022 mint extensions), System transfers and createAccount. */
6
6
  export declare abstract class CreateEmitter extends CpiCoreEmitter {
@@ -35,7 +35,7 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
35
35
  protected createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
36
36
  protected systemTransfer(node: ts.CallExpression): undefined;
37
37
  /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
38
- protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
38
+ protected createAccount(node: ts.CallExpression, system: CpiProgram): undefined;
39
39
  /**
40
40
  * systemProgram.createPda(payer, account, space, owner, seeds): Anchor's `init` with `seeds`, `space` and `owner = …`
41
41
  * on an `UncheckedAccount` — the PDA of this program for `seeds` (2006 otherwise), created owned by `owner`, or over
@@ -44,5 +44,5 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
44
44
  */
45
45
  protected createPda(node: ts.CallExpression): Value;
46
46
  /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
47
- protected allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
47
+ protected allocateOrAssign(node: ts.CallExpression, system: CpiProgram, method: "allocate" | "assign"): undefined;
48
48
  }
@@ -519,21 +519,23 @@ export class CreateEmitter extends CpiCoreEmitter {
519
519
  if (a.length !== 3 && a.length !== 4)
520
520
  this.fail(node, "transfer(from, to, lamports, signerSeeds?)");
521
521
  const [fromN, toN, amtN] = a;
522
- const from = this.accountParam(fromN, "transfer's source");
523
- if (a.length === 3 && (from.kind.kind !== "signer" || !from.kind.mut))
522
+ // Declared accounts are checked here; remaining accounts by the runtime (writable, and the source signed).
523
+ const from = this.cpiAccount(fromN, "transfer's source");
524
+ const fp = from.param;
525
+ if (fp && a.length === 3 && (fp.kind.kind !== "signer" || !fp.kind.mut))
524
526
  this.fail(fromN, "the source must be a Mut<Signer>, or a Mut<AccountInfo> PDA of this program with signerSeeds");
525
- if (a.length === 4 && !isWritable(from.kind))
527
+ if (fp && a.length === 4 && !isWritable(fp.kind))
526
528
  this.fail(fromN, "the source must be writable (Mut<...>)");
527
- const to = this.accountParam(toN, "transfer's destination");
528
- if (!isWritable(to.kind))
529
+ const to = this.cpiAccount(toN, "transfer's destination");
530
+ if (to.param && !isWritable(to.param.kind))
529
531
  this.fail(toN, "the destination must be writable (Mut<...>)");
530
532
  const amt = this.expect(this.expr(amtN, U64), U64, amtN);
531
533
  if (a.length === 3)
532
- this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
534
+ this.line(`TS_TRY(ts_system_transfer(params, ${from.c}, ${to.c}, ${amt.c}));`);
533
535
  else {
534
536
  // A system-owned PDA of this program (a SOL vault) pays.
535
537
  const s = this.signingSeeds(a[3]);
536
- this.line(`TS_TRY(ts_system_transfer_signed(params, a_${from.name}, a_${to.name}, ${amt.c}, ${s.name}, ${s.count}));`);
538
+ this.line(`TS_TRY(ts_system_transfer_signed(params, ${from.c}, ${to.c}, ${amt.c}, ${s.name}, ${s.count}));`);
537
539
  }
538
540
  return undefined;
539
541
  }
@@ -542,13 +544,15 @@ export class CreateEmitter extends CpiCoreEmitter {
542
544
  const a = node.arguments;
543
545
  if (a.length !== 5 && a.length !== 6)
544
546
  this.fail(node, "createAccount(payer, account, lamports, space, owner, signerSeeds?)");
545
- const payer = this.accountParam(a[0], "the payer");
546
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
547
+ const payer = this.cpiAccount(a[0], "the payer");
548
+ const pp = payer.param;
549
+ if (pp && (pp.kind.kind !== "signer" || !pp.kind.mut))
547
550
  this.fail(a[0], "the payer must be a Mut<Signer>");
548
- const acct = this.accountParam(a[1], "the new account");
549
- if (!isWritable(acct.kind))
551
+ const acct = this.cpiAccount(a[1], "the new account");
552
+ const ap = acct.param;
553
+ if (ap && !isWritable(ap.kind))
550
554
  this.fail(a[1], "the new account must be writable (Mut<Signer> or Mut<AccountInfo>)");
551
- if (acct.kind.kind !== "signer" && a.length !== 6)
555
+ if (ap && ap.kind.kind !== "signer" && a.length !== 6)
552
556
  this.fail(a[1], "the new account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
553
557
  const { buf, len, put, finish } = this.byteBuffer("sys", 52, "TS_ERR_INSTRUCTION_DATA", "system instruction");
554
558
  const tag = this.tmp("tag");
@@ -559,9 +563,9 @@ export class CreateEmitter extends CpiCoreEmitter {
559
563
  this.serialize(this.expect(this.expr(a[4], PUBKEY), PUBKEY, a[4]), a[4], put);
560
564
  finish(node);
561
565
  const seeds = a.length === 6 ? this.signingSeeds(a[5]) : { name: "NULL", count: 0 };
562
- this.cpi(`a_${system.name}`, [
563
- [`a_${payer.name}`, true, true],
564
- [`a_${acct.name}`, true, true],
566
+ this.cpi(system.c, [
567
+ [payer.c, true, true],
568
+ [acct.c, true, true],
565
569
  ], buf, len, seeds);
566
570
  return undefined;
567
571
  }
@@ -575,21 +579,24 @@ export class CreateEmitter extends CpiCoreEmitter {
575
579
  const a = node.arguments;
576
580
  if (a.length !== 5)
577
581
  this.fail(node, "createPda(payer, account, space, owner, seeds)");
578
- const payer = this.accountParam(a[0], "the payer");
579
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
582
+ const payer = this.cpiAccount(a[0], "the payer");
583
+ const pp = payer.param;
584
+ if (pp && (pp.kind.kind !== "signer" || !pp.kind.mut))
580
585
  this.fail(a[0], "the payer must be a Mut<Signer>");
581
- const acct = this.accountParam(a[1], "the new account");
582
- if (acct.kind.kind !== "info" || !isWritable(acct.kind))
586
+ const acct = this.cpiAccount(a[1], "the new account");
587
+ const ap = acct.param;
588
+ if (ap && (ap.kind.kind !== "info" || !isWritable(ap.kind)))
583
589
  this.fail(a[1], "the new account must be a Mut<AccountInfo>");
584
590
  const space = this.tmp("space");
585
591
  this.line(`uint64_t ${space} = ${this.expect(this.expr(a[2], U64), U64, a[2]).c};`);
586
592
  const owner = this.tmp("owner");
587
593
  this.line(`SolPubkey ${owner} = *(${this.expect(this.expr(a[3], PUBKEY), PUBKEY, a[3]).c});`);
588
594
  const seeds = this.seeds(a[4], 1);
589
- this.recordPda(acct, seeds.idl);
595
+ if (ap)
596
+ this.recordPda(ap, seeds.idl);
590
597
  const b = this.tmp("bump");
591
598
  this.line(`uint8_t ${b};`);
592
- this.line(`TS_TRY(ts_create_pda_owned(params, a_${payer.name}, a_${acct.name}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));`);
599
+ this.line(`TS_TRY(ts_create_pda_owned(params, ${payer.c}, ${acct.c}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));`);
593
600
  return { c: b, type: U8 };
594
601
  }
595
602
  /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
@@ -597,10 +604,11 @@ export class CreateEmitter extends CpiCoreEmitter {
597
604
  const a = node.arguments;
598
605
  if (a.length !== 2 && a.length !== 3)
599
606
  this.fail(node, `${method}(account, ${method === "allocate" ? "space" : "owner"}, signerSeeds?)`);
600
- const acct = this.accountParam(a[0], "the account");
601
- if (!isWritable(acct.kind))
607
+ const acct = this.cpiAccount(a[0], "the account");
608
+ const ap = acct.param;
609
+ if (ap && !isWritable(ap.kind))
602
610
  this.fail(a[0], `the account must be writable (Mut<Signer> or Mut<AccountInfo>)`);
603
- if (acct.kind.kind !== "signer" && a.length !== 3)
611
+ if (ap && ap.kind.kind !== "signer" && a.length !== 3)
604
612
  this.fail(a[0], "the account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
605
613
  const { buf, len, put, finish } = this.byteBuffer("sys", 36, "TS_ERR_INSTRUCTION_DATA", "system instruction");
606
614
  const tag = this.tmp("tag");
@@ -612,7 +620,7 @@ export class CreateEmitter extends CpiCoreEmitter {
612
620
  this.serialize(this.expect(this.expr(a[1], PUBKEY), PUBKEY, a[1]), a[1], put);
613
621
  finish(node);
614
622
  const seeds = a.length === 3 ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
615
- this.cpi(`a_${system.name}`, [[`a_${acct.name}`, true, true]], buf, len, seeds);
623
+ this.cpi(system.c, [[acct.c, true, true]], buf, len, seeds);
616
624
  return undefined;
617
625
  }
618
626
  }