@typesol/cli 0.38.0 → 0.39.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 (52) hide show
  1. package/CHANGELOG.md +327 -2
  2. package/README.md +29 -15
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +6 -11
  5. package/dist/compiler/analyze.js +323 -31
  6. package/dist/compiler/emit/alias.js +3 -2
  7. package/dist/compiler/emit/base.d.ts +5 -0
  8. package/dist/compiler/emit/base.js +2 -0
  9. package/dist/compiler/emit/borsh.js +63 -2
  10. package/dist/compiler/emit/calls.d.ts +9 -1
  11. package/dist/compiler/emit/calls.js +147 -18
  12. package/dist/compiler/emit/cpi-core.js +17 -5
  13. package/dist/compiler/emit/cpi.js +81 -27
  14. package/dist/compiler/emit/create.d.ts +7 -0
  15. package/dist/compiler/emit/create.js +27 -0
  16. package/dist/compiler/emit/expressions.js +7 -4
  17. package/dist/compiler/emit/function.d.ts +7 -0
  18. package/dist/compiler/emit/function.js +164 -29
  19. package/dist/compiler/emit/program.js +15 -2
  20. package/dist/compiler/emit/shared.d.ts +5 -5
  21. package/dist/compiler/emit/shared.js +5 -0
  22. package/dist/compiler/emit/statements.d.ts +8 -0
  23. package/dist/compiler/emit/statements.js +93 -6
  24. package/dist/compiler/emit/storage.d.ts +10 -1
  25. package/dist/compiler/emit/storage.js +50 -11
  26. package/dist/compiler/idl.d.ts +1 -1
  27. package/dist/compiler/idl.js +42 -11
  28. package/dist/compiler/model.d.ts +47 -10
  29. package/dist/compiler/model.js +14 -4
  30. package/dist/testing.js +8 -0
  31. package/dist/tools/clientgen.js +10 -1
  32. package/dist/tools/portgen.d.ts +6 -0
  33. package/dist/tools/portgen.js +68 -17
  34. package/docs/architecture.md +5 -4
  35. package/docs/audit.md +31 -19
  36. package/docs/case-study-escrow.md +5 -5
  37. package/docs/case-study-jito-mev.md +9 -5
  38. package/docs/case-study-marginfi.md +797 -0
  39. package/docs/case-study-multisig.md +3 -3
  40. package/docs/case-study-raydium-clmm.md +44 -33
  41. package/docs/case-study-raydium-cp-swap.md +3 -3
  42. package/docs/cli.md +5 -5
  43. package/docs/client.md +1 -1
  44. package/docs/errors.md +13 -5
  45. package/docs/language.md +38 -25
  46. package/docs/migrate-from-anchor.md +4 -1
  47. package/docs/runtime.md +1 -1
  48. package/docs/security-model.md +2 -1
  49. package/docs/testing.md +33 -1
  50. package/lib/typesol.d.ts +46 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { snakeCase, argIdlName } from "../analyze.js";
2
+ import { snakeCase, argIdlName, fieldIdlName } from "../analyze.js";
3
3
  import { decodeAddress } from "../../keys.js";
4
4
  import { INT_INFO, isScalar, isWritable, scalarSize, typeName, } from "../model.js";
5
5
  import { borshIdentical, borshMinSize } from "./borsh.js";
@@ -16,7 +16,7 @@ export class FunctionEmitter extends StatementEmitter {
16
16
  this.line(`(void)params;`);
17
17
  for (const p of h.params)
18
18
  if (p.account && p.account.kind === "account" && p.account.struct.layout !== "borsh")
19
- this.line(`TSS_${p.account.struct.name} *d_${p.name} = (TSS_${p.account.struct.name} *)(a_${p.name}->data + 8);`);
19
+ this.line(`TSS_${p.account.struct.name} *d_${p.name} = (TSS_${p.account.struct.name} *)(a_${p.name}->data + ${p.account.struct.accountDiscriminator.length});`);
20
20
  for (const stmt of h.statements)
21
21
  this.reporter.guard(() => this.statement(stmt));
22
22
  // A helper with a result must return one; falling off the end would leave it unset.
@@ -54,8 +54,22 @@ export class FunctionEmitter extends StatementEmitter {
54
54
  if (a.constraints.signed)
55
55
  head.push(` if (!${v}->is_signer) ${this.checkFail(a, "signer", "TS_ERR_CONSTRAINT_SIGNER", `${a.name} must sign`)};`);
56
56
  // A @layout borsh account only has to hold its smallest Borsh form (unpacking checks the rest).
57
- if (k.kind === "account")
58
- head.push(` TS_TRY(ts_check_program_account(${v}, params->program_id, TS_DISC_${k.struct.name}, ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : emptySizeC(k.struct)}));`);
57
+ // A zero-copy (bytemuck) struct is checked as Anchor's AccountLoader checks it.
58
+ // Owner<Account<T>, "…">: another program's account (Anchor's Account / AccountLoader of a declare_program! type),
59
+ // checked against that program as owner (3007), in place of this program.
60
+ if (k.kind === "account") {
61
+ const owner = a.constraints.owner ? `&co_${a.name}` : "params->program_id";
62
+ if (a.constraints.owner)
63
+ head.push(` static const SolPubkey co_${a.name} = {${cBytes(a.constraints.owner.bytes)}};`);
64
+ const n = k.struct.accountDiscriminator.length;
65
+ // A shorter discriminator (another program's zero-copy account): AccountLoader's checks with its length.
66
+ if (n !== 8)
67
+ head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
68
+ else
69
+ head.push(k.struct.idlMeta?.serialization?.startsWith("bytemuck")
70
+ ? ` TS_TRY(ts_check_loader_account(${v}, ${owner}, TS_DISC_${k.struct.name}, ${emptySizeC(k.struct)}));`
71
+ : ` TS_TRY(ts_check_program_account(${v}, ${owner}, TS_DISC_${k.struct.name}, ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : emptySizeC(k.struct)}));`);
72
+ }
59
73
  // A token account created by this instruction is checked where it is created (create/createIfNeeded).
60
74
  if (k.kind === "token" && !k.init)
61
75
  head.push(` TS_TRY(ts_check_token_account(${v}));`);
@@ -66,7 +80,9 @@ export class FunctionEmitter extends StatementEmitter {
66
80
  head.push(` if (!ts_key_eq(&${v}->owner, &TS_SYSTEM_PROGRAM_ID)) TS_FAIL(TS_ERR_NOT_SYSTEM_OWNED, "TypeSOL: ${a.name} must be owned by the System Program");`);
67
81
  if (k.kind === "system")
68
82
  head.push(` TS_TRY(ts_check_address(${v}, &TS_SYSTEM_PROGRAM_ID));`);
69
- if (k.kind === "instructionsSysvar")
83
+ // Address<InstructionsSysvar, "Sysvar1nstructions…"> leaves the address to that constraint (2012, in Anchor's
84
+ // constraint order), as Anchor's `#[account(address = sysvar::instructions::ID)]` on an UncheckedAccount.
85
+ if (k.kind === "instructionsSysvar" && !a.constraints.address)
70
86
  head.push(` TS_TRY(ts_check_address(${v}, &TS_INSTRUCTIONS_SYSVAR_ID));`);
71
87
  if (k.kind === "eventAuthority")
72
88
  head.push(` uint8_t eb_${a.name};`, ` TS_TRY(ts_check_event_authority(${v}, params->program_id, &eb_${a.name}));`);
@@ -129,7 +145,7 @@ export class FunctionEmitter extends StatementEmitter {
129
145
  head.push(` TS_TRY(ts_unpack_${S}(${v}->data + 8, ${v}->data_len - 8, d_${a.name}, NULL));`);
130
146
  }
131
147
  else if (k.kind === "account" || k.kind === "init" || k.kind === "zeroed" || k.kind === "initIfNeeded") {
132
- head.push(` TSS_${k.struct.name} *d_${a.name} = (TSS_${k.struct.name} *)(${v}->data + 8);`);
148
+ head.push(` TSS_${k.struct.name} *d_${a.name} = (TSS_${k.struct.name} *)(${v}->data + ${k.struct.accountDiscriminator.length});`);
133
149
  if (k.struct.vec) {
134
150
  head.push(` uint64_t entry_${a.name} = ${v}->data_len;`, ` (void)entry_${a.name};`);
135
151
  if (k.kind === "account")
@@ -140,7 +156,10 @@ export class FunctionEmitter extends StatementEmitter {
140
156
  const reallocated = (() => {
141
157
  let found = false;
142
158
  const visit = (nd) => {
143
- if (ts.isCallExpression(nd) && this.exportName(nd.expression) === "realloc" && nd.arguments[0] && this.accountAt(nd.arguments[0]) === a)
159
+ if (ts.isCallExpression(nd) &&
160
+ ["realloc", "resizeAccount"].includes(this.exportName(nd.expression) ?? "") &&
161
+ nd.arguments[0] &&
162
+ this.accountAt(nd.arguments[0]) === a)
144
163
  found = true;
145
164
  ts.forEachChild(nd, visit);
146
165
  };
@@ -175,8 +194,9 @@ export class FunctionEmitter extends StatementEmitter {
175
194
  // so two parameters name the same account exactly when their pointers are equal.
176
195
  const writable = ix.accounts.filter((a) => isWritable(a.kind));
177
196
  // Dup<…> (Anchor's `dup`) lifts the check for a pair when both accounts are read and written in place: not created
178
- // here, not closed or a close destination, not a @layout borsh heap copy (a lost update when packed back).
179
- const closing = new Set(ix.accounts.flatMap((a) => (a.constraints.closeTo ? [a.name, a.constraints.closeTo] : [])));
197
+ // here, not closed, not a @layout borsh heap copy (a lost update when packed back). A close destination is in place:
198
+ // a duplicate shares its record, so the rent lands in both views.
199
+ const closing = new Set(ix.accounts.flatMap((a) => (a.constraints.closeTo ? [a.name] : [])));
180
200
  const inPlace = (a) => {
181
201
  const k = a.kind;
182
202
  if (closing.has(a.name))
@@ -189,7 +209,7 @@ export class FunctionEmitter extends StatementEmitter {
189
209
  };
190
210
  for (const a of writable)
191
211
  if (a.constraints.dup && !inPlace(a))
192
- this.reporter.fail(a.node, "Dup<…> is for accounts read and written in place: not created, closed, a close destination or @layout borsh");
212
+ this.reporter.fail(a.node, "Dup<…> is for accounts read and written in place: not created, closed or @layout borsh");
193
213
  for (const a of ix.accounts)
194
214
  if (a.constraints.dup && !isWritable(a.kind))
195
215
  this.reporter.fail(a.node, "Dup<…> lets a writable account alias another; this one is not writable");
@@ -253,6 +273,19 @@ export class FunctionEmitter extends StatementEmitter {
253
273
  }
254
274
  head.push(` }`);
255
275
  }
276
+ else if (a.type.kind === "optionArg") {
277
+ // Borsh Option of a fixed-size struct: one tag byte, then the struct's bytes only when Some.
278
+ const inner = a.type.option.inner;
279
+ const size = this.fieldBytes(inner);
280
+ need("1");
281
+ head.push(` ${optC(a.type.option.inner)} arg_${a.name} = {0};`, ` uint8_t arg_${a.name}__tag = *(${at});`, ` off += 1;`);
282
+ head.push(` if (arg_${a.name}__tag > 1) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: invalid option argument");`);
283
+ head.push(` if (arg_${a.name}__tag == 1) {`);
284
+ head.push(` if (params->data_len < off + ${size}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: instruction data too short");`);
285
+ head.push(` arg_${a.name}.some = 1;`, ` ts_memcpy(&arg_${a.name}.v, ${at}, ${size});`, ` off += ${size};`);
286
+ head.push(...this.validation(`arg_${a.name}.v`, inner, " "));
287
+ head.push(` }`);
288
+ }
256
289
  else if (a.type.kind === "vecArg" && a.type.elem.kind === "string") {
257
290
  // Borsh Vec<String>: u32 count, then each string's u32 length and UTF-8 bytes. Kept as views of the
258
291
  // instruction data in a heap array of TS_Str (each string at least 4 bytes, so the count is bounded first).
@@ -267,8 +300,18 @@ export class FunctionEmitter extends StatementEmitter {
267
300
  else if (a.type.kind === "vecArg") {
268
301
  const elem = a.type.elem;
269
302
  const size = this.fieldBytes(elem);
303
+ if (a.type.optional) {
304
+ // Borsh Option<Vec<T>>: a tag byte, then the Vec when Some. None is an empty view with a NULL pointer.
305
+ need("1");
306
+ head.push(` TS_VecArg arg_${a.name};`, ` arg_${a.name}.ptr = NULL;`, ` arg_${a.name}.len = 0;`);
307
+ head.push(` uint8_t arg_${a.name}__tag = *(${at});`, ` off += 1;`);
308
+ head.push(` if (arg_${a.name}__tag > 1) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: invalid option argument");`);
309
+ head.push(` if (arg_${a.name}__tag == 1) {`);
310
+ }
311
+ else
312
+ head.push(` TS_VecArg arg_${a.name};`);
270
313
  need("4");
271
- head.push(` TS_VecArg arg_${a.name};`, ` arg_${a.name}.len = (uint32_t)ts_read_le(${at}, 4);`, ` off += 4;`);
314
+ head.push(` arg_${a.name}.len = (uint32_t)ts_read_le(${at}, 4);`, ` off += 4;`);
272
315
  if (a.type.cap !== undefined)
273
316
  head.push(` if (arg_${a.name}.len > ${a.type.cap}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: more elements than the FixedVec argument holds");`);
274
317
  need(`(uint64_t)arg_${a.name}.len * ${size}`);
@@ -276,12 +319,19 @@ export class FunctionEmitter extends StatementEmitter {
276
319
  // Struct elements are read in place, so check them all now; scalars are checked when read.
277
320
  if (!isScalar(elem)) {
278
321
  const i = `vi_${a.name}`;
279
- const checks = this.validation(`((${fieldC(elem)} *)arg_${a.name}.ptr)[${i}]`, elem, " ");
322
+ // An array element (Vec<[u8; 32]>) is addressed by its byte offset; it is checked through its first element.
323
+ const lv = elem.kind === "array"
324
+ ? `(*(${storageDecl(elem, "(*)")})(arg_${a.name}.ptr + (uint64_t)${i} * ${size}))`
325
+ : `((${fieldC(elem)} *)arg_${a.name}.ptr)[${i}]`;
326
+ const checks = this.validation(lv, elem, " ");
280
327
  if (checks.length)
281
328
  head.push(` for (uint64_t ${i} = 0; ${i} < arg_${a.name}.len; ${i}++) {`, ...checks, ` }`);
282
329
  }
330
+ if (a.type.optional)
331
+ head.push(` }`);
283
332
  }
284
- else if (a.type.kind === "structRef" && this.model.structs.get(a.type.struct).layout === "borsh") {
333
+ else if (a.type.kind === "structRef" &&
334
+ (this.model.structs.get(a.type.struct).layout === "borsh" || this.model.structs.get(a.type.struct).wire === "borsh")) {
285
335
  // A @layout borsh struct: Borsh-decoded into its fixed-layout struct, as its accounts are.
286
336
  const S = a.type.struct;
287
337
  const v = `arg_${a.name}`;
@@ -368,8 +418,15 @@ export class FunctionEmitter extends StatementEmitter {
368
418
  this.scopes = [new Map()];
369
419
  const raw = this.rawConstraints(ix);
370
420
  const grouped = ix.accounts.filter((a) => a.group);
371
- if (!grouped.length)
421
+ const body = ix.node.body.statements.slice(raw.count);
422
+ // Anchor creates `init` accounts before it checks the other accounts' constraints: the create calls the body starts
423
+ // with run first, then the constraints (a transaction breaking both gets Anchor's code).
424
+ const creates = grouped.length ? 0 : this.leadingCreates(ix, body);
425
+ if (!grouped.length && !creates)
372
426
  head.push(...this.constraintChecks(ix, raw.lines));
427
+ else if (!grouped.length) {
428
+ // Emitted with the body, after the creates (below).
429
+ }
373
430
  else {
374
431
  // With account groups, Anchor's order: the arguments first, then each account in order, a group's constraints
375
432
  // right after its accounts (a composite's try_accounts runs its own constraints), the others last.
@@ -397,8 +454,13 @@ export class FunctionEmitter extends StatementEmitter {
397
454
  if (this.profile)
398
455
  for (let i = 0; i < 2; i++)
399
456
  (this.line(`sol_log("ts:~");`), this.line(`sol_log_compute_units();`));
400
- for (const stmt of ix.node.body.statements.slice(raw.count))
457
+ body.forEach((stmt, i) => {
458
+ if (creates && i === creates)
459
+ this.lines.push(...this.constraintChecks(ix, raw.lines));
401
460
  this.reporter.guard(() => this.statement(stmt, true));
461
+ });
462
+ if (creates && creates === body.length)
463
+ this.lines.push(...this.constraintChecks(ix, raw.lines));
402
464
  for (const name of this.pendingInit) {
403
465
  const k = this.accounts.get(name).kind;
404
466
  const a = this.accounts.get(name);
@@ -418,7 +480,50 @@ export class FunctionEmitter extends StatementEmitter {
418
480
  const end = ix.returns
419
481
  ? [` TS_FAIL(TS_ERR_NO_RETURN, "TypeSOL: ${ix.name} ended without returning a value");`]
420
482
  : [...this.epilogue().map((l) => ` ${l}`), ` return SUCCESS;`];
421
- return [...head, ...this.hoisted, ...this.lines, ...end, `}`].join("\n");
483
+ // The Clock cache is declared first: a constraint (in the head) may read the Clock before the body does.
484
+ const clock = this.hoisted.filter((l) => l.includes("ts_clk_ok"));
485
+ const hoisted = this.hoisted.filter((l) => !clock.includes(l));
486
+ return [head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
487
+ }
488
+ /**
489
+ * How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
490
+ * (`acct.create(…)`, `acct.createIfNeeded(…)`, `systemProgram.createPda(…)`, alone, as a const's value or assigned). 0 when none do, or when one reads a
491
+ * bump the constraint checks find (`acct.pdaBump` of a Seeds account), which must run first.
492
+ */
493
+ leadingCreates(ix, body) {
494
+ const isInit = (e) => {
495
+ const a = ts.isIdentifier(e) ? ix.accounts.find((x) => x.name === e.text) : undefined;
496
+ return !!a && (a.kind.kind === "init" || a.kind.kind === "initIfNeeded" || ((a.kind.kind === "token" || a.kind.kind === "mint") && !!a.kind.init));
497
+ };
498
+ const isSystem = (e) => ts.isIdentifier(e) && ix.accounts.find((x) => x.name === e.text)?.kind.kind === "system";
499
+ const createCall = (e) => !!e &&
500
+ ts.isCallExpression(e) &&
501
+ ts.isPropertyAccessExpression(e.expression) &&
502
+ (((e.expression.name.text === "create" || e.expression.name.text === "createIfNeeded") && isInit(e.expression.expression)) ||
503
+ (e.expression.name.text === "createPda" && isSystem(e.expression.expression)));
504
+ let n = 0;
505
+ for (const stmt of body) {
506
+ const e = ts.isExpressionStatement(stmt)
507
+ ? ts.isBinaryExpression(stmt.expression) && stmt.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken
508
+ ? stmt.expression.right
509
+ : stmt.expression
510
+ : ts.isVariableStatement(stmt) && stmt.declarationList.declarations.length === 1
511
+ ? stmt.declarationList.declarations[0].initializer
512
+ : undefined;
513
+ if (!createCall(e))
514
+ break;
515
+ let readsBump = false;
516
+ const visit = (x) => {
517
+ if (ts.isPropertyAccessExpression(x) && x.name.text === "pdaBump")
518
+ readsBump = true;
519
+ ts.forEachChild(x, visit);
520
+ };
521
+ visit(stmt);
522
+ if (readsBump)
523
+ return 0;
524
+ n++;
525
+ }
526
+ return n;
422
527
  }
423
528
  /** CloseTo<…> accounts are closed when the instruction succeeds, at every return. */
424
529
  epilogue() {
@@ -484,7 +589,11 @@ export class FunctionEmitter extends StatementEmitter {
484
589
  const c = this.expect(this.expr(cond, BOOL), BOOL, cond);
485
590
  const err = error ? this.errorRef(error) : { code: 2003, name: "ConstraintRaw", msg: "ConstraintRaw" };
486
591
  this.line(`if (!${c.c}) TS_FAIL(${err.code}, ${cString(`Error ${err.code} ${err.name}: ${err.msg} (${this.location(call)})`)});`);
487
- const emitted = [...this.hoisted.splice(hoistMark), ...this.lines.splice(mark)];
592
+ // The instruction's Clock cache stays declared at its top: the body may read the Clock too.
593
+ const hoisted = this.hoisted.splice(hoistMark);
594
+ const clock = hoisted.filter((l) => l.includes("ts_clk_ok"));
595
+ this.hoisted.push(...clock);
596
+ const emitted = [...hoisted.filter((l) => !clock.includes(l)), ...this.lines.splice(mark)];
488
597
  lines.set(a.name, [...(lines.get(a.name) ?? []), ...emitted]);
489
598
  });
490
599
  }
@@ -537,8 +646,12 @@ export class FunctionEmitter extends StatementEmitter {
537
646
  }
538
647
  if (k === "account")
539
648
  out.push(...hasOne);
540
- out.push(...(raw.get(a.name) ?? []));
541
- if (c.owner) {
649
+ // constraint(…) lines: Anchor evaluates the expression as written, so another optional account it mentions
650
+ // (`x === null`, or `x!`, which fails when it is missing) does not skip it; only this account being optional does.
651
+ const rawLines = raw.get(a.name) ?? [];
652
+ const rawAt = out.length - start;
653
+ out.push(...rawLines);
654
+ if (c.owner && k !== "account") {
542
655
  out.push(` static const SolPubkey co_${a.name} = {${cBytes(c.owner.bytes)}};`);
543
656
  out.push(` if (!ts_key_eq(&a_${a.name}->owner, &co_${a.name})) ${this.checkFail(a, "owner", "TS_ERR_CONSTRAINT_OWNER", `${a.name} is not owned by the expected program`)};`);
544
657
  }
@@ -550,13 +663,20 @@ export class FunctionEmitter extends StatementEmitter {
550
663
  }
551
664
  if (k !== "account")
552
665
  out.push(...hasOne);
553
- // Constraints run only when every optional account they mention was passed.
666
+ // The declared constraints run only when every optional account they mention was passed.
554
667
  const lines = out.splice(start);
555
- const optional = this.optionalIn(lines.join("\n"));
556
- if (optional.length && lines.length)
557
- out.push(` if (${optional.map((n) => `a_${n} != NULL`).join(" && ")}) {`, ...lines.map((l) => ` ${l}`), ` }`);
558
- else
559
- out.push(...lines);
668
+ const guard = (part, optional) => {
669
+ if (optional.length && part.length)
670
+ out.push(` if (${optional.map((n) => `a_${n} != NULL`).join(" && ")}) {`, ...part.map((l) => ` ${l}`), ` }`);
671
+ else
672
+ out.push(...part);
673
+ };
674
+ const before = lines.slice(0, rawAt);
675
+ const after = lines.slice(rawAt + rawLines.length);
676
+ const declared = this.optionalIn([...before, ...after].join("\n"));
677
+ guard(before, declared);
678
+ guard(rawLines, a.optional ? [a.name] : []);
679
+ guard(after, declared);
560
680
  }
561
681
  return [...bumpDecls, ...out];
562
682
  }
@@ -566,13 +686,28 @@ export class FunctionEmitter extends StatementEmitter {
566
686
  const c = a.constraints;
567
687
  const k = a.kind.kind;
568
688
  const ata = c.ata;
689
+ // The owner: an account parameter's key, or "@acct.field", a Pubkey field of a struct account parameter (its data
690
+ // was checked in the head). Anchor's IDL cannot see through `acct.load()?.field` and records the account, as here.
691
+ let ownerKey = `&a_${ata.owner}->key`;
692
+ let ownerName = ata.owner;
693
+ if (ata.owner.startsWith("@")) {
694
+ const [acct, field, ...rest] = ata.owner.slice(1).split(".");
695
+ const o = ix.accounts.find((x) => x.name === acct);
696
+ if (!o || o.kind.kind !== "account" || !field || rest.length)
697
+ this.reporter.fail(a.node, `Ata<…>: "${ata.owner}" must name a Pubkey field of a struct account parameter ("@config.wallet")`);
698
+ const f = o.kind.struct.fields.find((x) => x.name === field);
699
+ if (!f || f.type.kind !== "pubkey")
700
+ this.reporter.fail(a.node, `Ata<…>: ${o.kind.struct.name} has no Pubkey field "${field}"`);
701
+ ownerKey = `&d_${acct}->${field}`;
702
+ ownerName = acct;
703
+ }
569
704
  // With two token programs the address depends on which the mint uses: no IDL derivation, and an Ata<AccountInfo>
570
705
  // (derived here) is refused.
571
706
  const tps = ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
572
707
  const tp = tps.length === 1 ? tps[0] : undefined;
573
708
  if (tp && !ix.pdas.has(a.name)) {
574
709
  ix.pdas.set(a.name, [
575
- { kind: "account", path: snakeCase(ata.owner) },
710
+ { kind: "account", path: snakeCase(ownerName) },
576
711
  { kind: "account", path: snakeCase(tp.name) },
577
712
  { kind: "account", path: snakeCase(ata.mint) },
578
713
  ]);
@@ -584,7 +719,7 @@ export class FunctionEmitter extends StatementEmitter {
584
719
  return out;
585
720
  // The address alone is not enough: legacy SPL Token lets an ATA's owner be reassigned.
586
721
  if (k === "token")
587
- out.push(` if (!ts_key_eq(ts_token_owner(a_${a.name}), &a_${ata.owner}->key)) TS_FAIL(TS_ERR_TOKEN_OWNER, "TypeSOL: ${a.name} is not owned by ${ata.owner}");`);
722
+ out.push(` if (!ts_key_eq(ts_token_owner(a_${a.name}), ${ownerKey})) TS_FAIL(TS_ERR_TOKEN_OWNER, "TypeSOL: ${a.name} is not owned by ${ata.owner}");`);
588
723
  // The token program is the account's owner; an AccountInfo not created yet takes the instruction's token program.
589
724
  let program = `&a_${a.name}->owner`;
590
725
  if (k !== "token") {
@@ -595,7 +730,7 @@ export class FunctionEmitter extends StatementEmitter {
595
730
  program = `&a_${tp.name}->key`;
596
731
  }
597
732
  out.push(` { SolPubkey ata_${a.name};`);
598
- out.push(` TS_TRY(ts_ata_address(&a_${ata.owner}->key, &a_${ata.mint}->key, ${program}, &ata_${a.name}));`);
733
+ out.push(` TS_TRY(ts_ata_address(${ownerKey}, &a_${ata.mint}->key, ${program}, &ata_${a.name}));`);
599
734
  out.push(` if (!ts_key_eq(&ata_${a.name}, &a_${a.name}->key)) TS_FAIL(TS_ERR_ASSOCIATED, "TypeSOL: ${a.name} is not the associated token account of ${ata.owner} and ${ata.mint}"); }`);
600
735
  if (k === "token")
601
736
  out.push(` if (!ts_key_eq(ts_token_mint(a_${a.name}), &a_${ata.mint}->key)) TS_FAIL(TS_ERR_TOKEN_MINT, "TypeSOL: ${a.name} is not a token account of ${ata.mint}");`);
@@ -644,7 +779,7 @@ export class FunctionEmitter extends StatementEmitter {
644
779
  parts.push(`{(const uint8_t *)&d_${owner}->${field}, ${scalarSize(t)}}`);
645
780
  else
646
781
  this.reporter.fail(a.node, `Seeds: field "${ref}" of type ${typeName(t)} cannot be a seed (use a Pubkey, an integer or a unit enum)`);
647
- idl.push({ kind: "account", path: `${snakeCase(owner)}.${snakeCase(field)}`, account: st.name });
782
+ idl.push({ kind: "account", path: `${snakeCase(owner)}.${fieldIdlName(field)}`, account: st.name });
648
783
  continue;
649
784
  }
650
785
  const acct = ref ? ix.accounts.find((o) => o.name === ref) : undefined;
@@ -49,7 +49,7 @@ export function emitProgram(analysis, opts = {}) {
49
49
  }
50
50
  out.push(`#include "typesol_rt.h"`, "");
51
51
  for (const inner of model.options.values())
52
- if (inner.kind !== "struct")
52
+ if (inner.kind !== "struct" && inner.kind !== "array")
53
53
  out.push(`typedef struct __attribute__((packed)) {`, ` uint8_t some;`, ` ${scalarStorageC(inner)} v;`, `} ${optC(inner)};`, "");
54
54
  for (const cap of [...model.fstrings].sort((a, b) => a - b))
55
55
  out.push(`typedef struct __attribute__((packed)) {`, ` uint32_t len;`, ` uint8_t bytes[${cap}];`, `} TS_FStr${cap};`, "");
@@ -76,6 +76,15 @@ export function emitProgram(analysis, opts = {}) {
76
76
  emitted.add(name);
77
77
  out.push(`typedef struct __attribute__((packed)) {`, ` uint32_t len;`, ` uint32_t cap;`, ` ${storageDecl(t.elem, `*items`)};`, `} ${name};`, "");
78
78
  }
79
+ if (t.kind === "option" && t.inner.kind === "array") {
80
+ const inner = t.inner;
81
+ const key = `opt:${optC(inner)}`;
82
+ if (emitted.has(key))
83
+ return;
84
+ deps(inner.elem);
85
+ emitted.add(key);
86
+ out.push(`typedef struct __attribute__((packed)) {`, ` uint8_t some;`, ` ${storageDecl(inner.elem, `v[${inner.len}]`)};`, `} ${optC(inner)};`, "");
87
+ }
79
88
  if (t.kind === "option" && t.inner.kind === "struct") {
80
89
  const key = `opt:${t.inner.name}`;
81
90
  if (emitted.has(key))
@@ -132,6 +141,10 @@ export function emitProgram(analysis, opts = {}) {
132
141
  };
133
142
  for (const s of model.structs.values())
134
143
  emitStruct(s);
144
+ for (const ix of model.instructions)
145
+ for (const a of ix.args)
146
+ if (a.type.kind === "optionArg")
147
+ deps(a.type.option);
135
148
  for (const e of model.dataEnums.values())
136
149
  deps({ kind: "dataEnum", name: e.name });
137
150
  for (const t of model.localVecs.values())
@@ -158,7 +171,7 @@ export function emitProgram(analysis, opts = {}) {
158
171
  // Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
159
172
  if (limit > 32)
160
173
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
161
- if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?\(/.test(b)))
174
+ if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?(_rec)?\(/.test(b)))
162
175
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
163
176
  const fallback = model.instructions.find((ix) => ix.fallback);
164
177
  const dispatched = model.instructions.filter((ix) => !ix.fallback);
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { type AccountParam, type FieldType, type ProgramModel, type Helper, type IntName, type ParamKind, type ScalarType, type StructDef, type ValueType } from "../model.js";
2
+ import { type OptionInner, type AccountParam, type FieldType, type ProgramModel, type Helper, type IntName, type ParamKind, type ScalarType, type StructDef, type ValueType } from "../model.js";
3
3
  /** Maximum accounts the generated entrypoint deserializes. */
4
4
  export declare const MAX_ACCOUNTS = 32;
5
5
  /** The most accounts one instruction takes: 32, or what the program declares with `const MAX_ACCOUNTS = …n` (33–255). */
@@ -11,6 +11,7 @@ export declare const MAX_EVENT = 1024;
11
11
  /** The Associated Token Account program (ATokenGP…), for IDL PDA descriptions. */
12
12
  export declare const ATA_PROGRAM_BYTES: number[];
13
13
  export declare const U64: ScalarType;
14
+ export declare const U32: ScalarType;
14
15
  export declare const U8: ScalarType;
15
16
  export declare const I64: ScalarType;
16
17
  export declare const I32: ScalarType;
@@ -89,6 +90,8 @@ export interface Local {
89
90
  struct: string;
90
91
  mut: boolean;
91
92
  };
93
+ /** A struct value this function holds itself (a literal, or what a helper returned): never account data. */
94
+ owned?: boolean;
92
95
  }
93
96
  /** A closure and the scopes it was declared in (its free names resolve there, wherever it is called). */
94
97
  export interface Closure {
@@ -117,10 +120,7 @@ export declare function intLiteral(value: bigint, name: IntName): string;
117
120
  export declare function scalarC(t: ScalarType): string;
118
121
  /** C type of a scalar as stored in account data (bool and enums are one byte). */
119
122
  export declare function scalarStorageC(t: ScalarType): string;
120
- export declare const optC: (inner: ScalarType | {
121
- kind: "struct";
122
- name: string;
123
- }) => string;
123
+ export declare const optC: (inner: OptionInner) => string;
124
124
  /** C type of any value held in a local. */
125
125
  export declare function valueC(t: ValueType): string;
126
126
  /** C type of one fixed-size element (struct, string, option, enum or scalar) as laid out in data. */
@@ -16,6 +16,7 @@ export const ATA_PROGRAM_BYTES = [
16
16
  140, 151, 37, 143, 78, 36, 137, 241, 187, 61, 16, 41, 20, 142, 13, 131, 11, 90, 19, 153, 218, 255, 16, 132, 4, 142, 123, 216, 219, 233, 248, 89,
17
17
  ];
18
18
  export const U64 = { kind: "int", name: "u64" };
19
+ export const U32 = { kind: "int", name: "u32" };
19
20
  export const U8 = { kind: "int", name: "u8" };
20
21
  export const I64 = { kind: "int", name: "i64" };
21
22
  export const I32 = { kind: "int", name: "i32" };
@@ -79,6 +80,7 @@ export function valueC(t) {
79
80
  return `TSE_${t.name} *`;
80
81
  case "remaining":
81
82
  case "arrayArg":
83
+ case "optionArg":
82
84
  case "signerSeeds":
83
85
  throw new Error(`unreachable: ${t.kind} is not held in a C value`);
84
86
  default:
@@ -207,6 +209,9 @@ export function helperSignature(h) {
207
209
  }
208
210
  else if (p.type.kind === "signerSeeds")
209
211
  params.push(`const SolSignerSeed *p_${p.name}`, `int p_${p.name}__n`);
212
+ // The remaining accounts: the index of the first one among the instruction's accounts.
213
+ else if (p.type.kind === "remaining")
214
+ params.push(`uint64_t p_${p.name}`);
210
215
  else if (p.type.kind === "pubkey")
211
216
  params.push(`SolPubkey p_${p.name}`); // by value: a copy taken at the call
212
217
  else if (p.type.kind === "arrayArg")
@@ -42,6 +42,7 @@ export declare abstract class StatementEmitter extends CpiEmitter {
42
42
  ci: string;
43
43
  next?: string;
44
44
  alwaysNext?: boolean;
45
+ atNext?: () => void;
45
46
  }, body: (element: ts.Expression, index: ts.Expression) => void): void;
46
47
  /**
47
48
  * `const ys = xs.map(…)` / `xs.filter(…)`: the chain's elements in a local FixedVec, as big as the list it starts
@@ -81,6 +82,13 @@ export declare abstract class StatementEmitter extends CpiEmitter {
81
82
  protected closureResult(value: Value, at: ts.Expression, frame: (typeof this.inlineFrames)[number]): void;
82
83
  /** `do { … } while (cond)`: the body once, then the test; `continue` goes to the test. */
83
84
  protected doLoop(stmt: ts.DoStatement): void;
85
+ /**
86
+ * The loadAccountMut calls of a loop body whose views end with the iteration: `const v = loadAccountMut<T>(…)` in the
87
+ * body (not in a loop nested in it, which handles its own), with `v` never assigned or copied to a name, returned, put in
88
+ * an object, or used in a function written in the body (other than a const closure of the body that stays in it). Their claims are recorded (declared here) and dropped at each iteration's end, so a
89
+ * later iteration may load the same account again: the earlier view is out of scope by then. Returns the release.
90
+ */
91
+ protected iterationClaims(body: ts.Statement): () => void;
84
92
  protected body(stmt: ts.Statement): void;
85
93
  protected variable(list: ts.VariableDeclarationList, topLevel?: boolean): void;
86
94
  /**