@typesol/cli 0.31.0 → 0.33.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 (40) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +10 -9
  3. package/dist/cli.js +50 -5
  4. package/dist/compiler/analyze.js +187 -42
  5. package/dist/compiler/emit/alias.js +5 -1
  6. package/dist/compiler/emit/base.d.ts +5 -0
  7. package/dist/compiler/emit/base.js +24 -6
  8. package/dist/compiler/emit/calls.d.ts +5 -1
  9. package/dist/compiler/emit/calls.js +109 -15
  10. package/dist/compiler/emit/cpi-core.d.ts +8 -0
  11. package/dist/compiler/emit/cpi-core.js +17 -2
  12. package/dist/compiler/emit/cpi.js +10 -4
  13. package/dist/compiler/emit/create.d.ts +2 -0
  14. package/dist/compiler/emit/create.js +56 -13
  15. package/dist/compiler/emit/expressions.js +16 -6
  16. package/dist/compiler/emit/function.d.ts +3 -1
  17. package/dist/compiler/emit/function.js +21 -12
  18. package/dist/compiler/emit/statements.js +53 -3
  19. package/dist/compiler/emit/storage.js +8 -8
  20. package/dist/compiler/emit/token.js +43 -0
  21. package/dist/compiler/idl.js +47 -6
  22. package/dist/compiler/model.d.ts +19 -1
  23. package/dist/templates.js +13 -36
  24. package/dist/testing.d.ts +30 -0
  25. package/dist/testing.js +85 -3
  26. package/dist/workspace.d.ts +16 -1
  27. package/dist/workspace.js +49 -5
  28. package/docs/audit.md +1 -1
  29. package/docs/case-study-escrow.md +3 -3
  30. package/docs/case-study-multisig.md +3 -3
  31. package/docs/case-study-raydium-cp-swap.md +51 -21
  32. package/docs/cli.md +5 -3
  33. package/docs/errors.md +3 -1
  34. package/docs/language.md +17 -5
  35. package/docs/migrate-from-anchor.md +6 -0
  36. package/docs/test-your-program.md +12 -3
  37. package/docs/testing.md +1 -1
  38. package/lib/typesol.d.ts +51 -15
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -7
@@ -349,22 +349,40 @@ export class EmitterBase {
349
349
  if (!ts.isPropertyAccessExpression(node) || !ts.isNonNullExpression(node.expression))
350
350
  return undefined;
351
351
  const inner = node.expression.expression;
352
- if (!ts.isIdentifier(inner) || !this.accounts.get(inner.text)?.optional)
352
+ if (!this.accountAt(inner)?.optional)
353
353
  return undefined;
354
354
  const plain = ts.factory.createPropertyAccessExpression(inner, node.name);
355
355
  ts.setTextRange(plain, node);
356
356
  plain.parent = node.parent;
357
357
  return plain;
358
358
  }
359
+ /** The account an expression names: a parameter (`vault`) or a field of an account group (`pool.vault`). */
360
+ accountAt(node) {
361
+ if (ts.isIdentifier(node))
362
+ return this.accounts.get(node.text);
363
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && this.isGroup(node.expression.text))
364
+ return this.accounts.get(`${node.expression.text}__${node.name.text}`);
365
+ return undefined;
366
+ }
367
+ /** An account group parameter's name. */
368
+ isGroup(name) {
369
+ for (const a of this.accounts.values())
370
+ if (a.group?.param === name)
371
+ return true;
372
+ return false;
373
+ }
359
374
  accountParam(node, what) {
360
375
  // `acct!` on an optional account: the account (its use checks it was passed).
361
- if (ts.isNonNullExpression(node) && ts.isIdentifier(node.expression) && this.accounts.get(node.expression.text)?.optional)
376
+ if (ts.isNonNullExpression(node) && this.accountAt(node.expression)?.optional)
362
377
  return this.accountParam(node.expression, what);
363
- if (!ts.isIdentifier(node))
364
- this.fail(node, `${what} must be an account parameter`);
365
- const a = this.accounts.get(node.text);
366
- if (!a)
378
+ const a = this.accountAt(node);
379
+ if (!a) {
380
+ if (ts.isIdentifier(node) && this.isGroup(node.text))
381
+ this.fail(node, `${what} must be an account; "${node.text}" is a group of accounts: pass one of its fields (${node.text}.…)`);
382
+ if (!ts.isIdentifier(node))
383
+ this.fail(node, `${what} must be an account parameter`);
367
384
  this.fail(node, `${what} must be an account parameter, "${node.text}" is not one`);
385
+ }
368
386
  this.assertUsable(a, node);
369
387
  return a;
370
388
  }
@@ -1,9 +1,11 @@
1
1
  import ts from "typescript";
2
- import { type AccountParam, type ErrorDef, type FieldType, type Helper } from "../model.js";
2
+ import { type AccountParam, type ErrorDef, type FieldType, type Helper, type StructDef } from "../model.js";
3
3
  import { type Value, type Ref, type Closure } from "./shared.js";
4
4
  import { ExpressionEmitter } from "./expressions.js";
5
5
  export declare abstract class CallEmitter extends ExpressionEmitter {
6
6
  protected call(node: ts.CallExpression, topLevel: boolean): Value | undefined;
7
+ /** "unsupported call" naming the callee, with the TypeSOL form of common JavaScript calls. */
8
+ private unsupportedCall;
7
9
  protected vecMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
8
10
  /** sha256(...) / keccak256(...) over strings, Pubkeys, Hashes, integers (LE) and booleans. */
9
11
  protected hashCall(node: ts.CallExpression, fn: "sha256" | "keccak256"): Value;
@@ -77,5 +79,7 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
77
79
  count: number | string;
78
80
  };
79
81
  protected errorRef(node: ts.Expression): ErrorDef;
82
+ /** The struct of `returnData<Quote>(…)`, when T is one; refused when its bytes are not its Borsh form. */
83
+ protected returnedStruct(node: ts.CallExpression): StructDef | undefined;
80
84
  protected returnData(node: ts.CallExpression): Value;
81
85
  }
@@ -1,5 +1,6 @@
1
1
  import ts from "typescript";
2
- import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase } from "../analyze.js";
2
+ import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf } from "../analyze.js";
3
+ import { borshIdentical } from "./borsh.js";
3
4
  import { ANCHOR_ERRORS } from "../anchor-errors.js";
4
5
  import { decodeAddress } from "../../keys.js";
5
6
  import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
@@ -107,22 +108,32 @@ export class CallEmitter extends ExpressionEmitter {
107
108
  return { c: t, type: U64 };
108
109
  }
109
110
  case "currentSlot":
110
- case "currentEpoch": {
111
+ case "currentEpoch":
112
+ case "now": {
111
113
  if (args.length !== 0)
112
114
  this.fail(node, `${builtin}() takes no arguments`);
115
+ // Clock { slot, epoch_start_timestamp, epoch, leader_schedule_epoch, unix_timestamp }
116
+ const field = builtin === "currentSlot" ? 0 : builtin === "currentEpoch" ? 2 : 4;
113
117
  const t = this.tmp();
118
+ if (this.ix) {
119
+ // The Clock does not change within a transaction: an instruction reads it once, on first use.
120
+ if (!this.hoisted.some((l) => l.includes("ts_clk_ok")))
121
+ this.hoisted.push(` uint64_t ts_clk[5]; bool ts_clk_ok = false;`);
122
+ this.line(`if (!ts_clk_ok) { TS_TRY(ts_read_clock(ts_clk)); ts_clk_ok = true; }`);
123
+ if (builtin === "now")
124
+ return { c: `((int64_t)ts_clk[4])`, type: I64 };
125
+ this.line(`uint64_t ${t} = ts_clk[${field}];`);
126
+ return { c: t, type: U64 };
127
+ }
128
+ if (builtin === "now") {
129
+ this.line(`int64_t ${t};`);
130
+ this.line(`TS_TRY(ts_now(&${t}));`);
131
+ return { c: t, type: I64 };
132
+ }
114
133
  this.line(`uint64_t ${t};`);
115
- this.line(`TS_TRY(ts_clock_u64(${builtin === "currentSlot" ? 0 : 2}, &${t}));`);
134
+ this.line(`TS_TRY(ts_clock_u64(${field}, &${t}));`);
116
135
  return { c: t, type: U64 };
117
136
  }
118
- case "now": {
119
- if (args.length !== 0)
120
- this.fail(node, "now() takes no arguments");
121
- const t = this.tmp();
122
- this.line(`int64_t ${t};`);
123
- this.line(`TS_TRY(ts_now(&${t}));`);
124
- return { c: t, type: I64 };
125
- }
126
137
  case "pubkey": {
127
138
  const lit = args[0];
128
139
  if (args.length !== 1 || !ts.isStringLiteral(lit))
@@ -419,6 +430,43 @@ export class CallEmitter extends ExpressionEmitter {
419
430
  this.line(`TS_TRY(ts_ata_address(${o.c}, ${m.c}, ${tp.c}, &${t}));`);
420
431
  return { c: `(&${t})`, type: PUBKEY };
421
432
  }
433
+ case "programId":
434
+ if (args.length !== 0)
435
+ this.fail(node, "programId() takes no arguments");
436
+ return { c: `params->program_id`, type: PUBKEY };
437
+ case "findProgramAddressBump": {
438
+ // Pubkey::find_program_address(seeds, program).1: the bump of the canonical PDA.
439
+ if (args.length !== 2)
440
+ this.fail(node, "findProgramAddressBump(seeds, program) takes the seeds and the program's address");
441
+ const seeds = this.seeds(args[0], 0);
442
+ const program = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
443
+ const t = this.tmp("pda");
444
+ const b = this.tmp("bump");
445
+ this.line(`SolPubkey ${t}; uint8_t ${b};`);
446
+ this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
447
+ return { c: `((uint64_t)${b})`, type: { kind: "int", name: "u8" } };
448
+ }
449
+ case "initAccount": {
450
+ // Anchor's AccountLoader::load_init on an account created in the body (system createAccount / allocate +
451
+ // assign): owned by this program (3007), writable (3006), large enough (3003), discriminator still zero
452
+ // (3000); then the discriminator is written and the struct is a mutable view of the data.
453
+ const targ = node.typeArguments?.[0];
454
+ const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
455
+ if (!s || s.size === undefined || s.vec || s.layout === "borsh")
456
+ this.fail(node, "initAccount<T>(account) takes a fixed-layout account struct of this program (no growable Vec, not @layout borsh)");
457
+ if (args.length !== 1)
458
+ this.fail(node, "initAccount<T>(account) takes one account");
459
+ let h = this.handle(args[0]);
460
+ if (!h) {
461
+ const acct = this.accountParam(args[0], "the account");
462
+ if (acct.kind.kind !== "info")
463
+ this.fail(args[0], "initAccount<T>(account) takes a Mut<AccountInfo> parameter or a remaining account");
464
+ h = `a_${acct.name}`;
465
+ }
466
+ this.model.accountStructs.add(s.name);
467
+ this.line(`TS_TRY(ts_init_account(${h}, params->program_id, TS_DISC_${s.name}, sizeof(TSS_${s.name})));`);
468
+ return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: true } };
469
+ }
422
470
  case "findProgramAddress": {
423
471
  // Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
424
472
  if (args.length !== 2)
@@ -592,6 +640,17 @@ export class CallEmitter extends ExpressionEmitter {
592
640
  if (method !== "get")
593
641
  this.fail(node, `arrays support get(i), set(i, v) and .length, not ${method}()`);
594
642
  }
643
+ if (method === "compare") {
644
+ // Pubkey.compare: Rust's Ord on [u8; 32] (lexicographic bytes), as -1, 0 or 1.
645
+ if (args.length !== 1)
646
+ this.fail(node, "compare() takes one argument");
647
+ const left = this.expr(callee.expression);
648
+ if (left.type.kind !== "pubkey")
649
+ this.fail(callee.expression, "compare() orders Pubkeys or Hashes");
650
+ const mark = this.lines.length;
651
+ const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
652
+ return { c: `ts_key_cmp(${this.settle(left, mark).c}, ${right.c})`, type: { kind: "int", name: "i64" } };
653
+ }
595
654
  if (method === "equals") {
596
655
  if (args.length !== 1)
597
656
  this.fail(node, "equals() takes one argument");
@@ -603,8 +662,8 @@ export class CallEmitter extends ExpressionEmitter {
603
662
  const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
604
663
  return { c: `ts_key_eq(${this.settle(left, mark).c}, ${right.c})`, type: BOOL };
605
664
  }
606
- if (ts.isIdentifier(callee.expression)) {
607
- const target = this.accounts.get(callee.expression.text);
665
+ if (this.accountAt(callee.expression)) {
666
+ const target = this.accountAt(callee.expression);
608
667
  // Program accounts used through their methods (systemProgram.transfer, tokenProgram.*…) may be optional.
609
668
  if (target?.optional)
610
669
  this.assertUsable(target, callee.expression);
@@ -622,6 +681,8 @@ export class CallEmitter extends ExpressionEmitter {
622
681
  return this.systemTransfer(node);
623
682
  if (target?.kind.kind === "system" && method === "createAccount")
624
683
  return this.createAccount(node, target);
684
+ if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
685
+ return this.allocateOrAssign(node, target, method);
625
686
  if (target?.kind.kind === "tokenProgram")
626
687
  return this.tokenOp(node, target, method);
627
688
  if (target?.kind.kind === "ataProgram")
@@ -642,7 +703,27 @@ export class CallEmitter extends ExpressionEmitter {
642
703
  this.fail(callee.expression, "fixedArray<T, N>(fill) is only allowed as a local declaration: const xs = fixedArray<u64, 4>(0n)");
643
704
  if (ts.isPropertyAccessExpression(callee) && callee.name.text === "slice" && this.isRemaining(callee.expression))
644
705
  this.fail(node, "rest.slice(a, b) is only for spreading into a CPI's accounts: invoke(p, [..., ...readonly(rest.slice(a, b))], data)");
645
- this.fail(node, "unsupported call");
706
+ this.fail(node, this.unsupportedCall(callee));
707
+ }
708
+ /** "unsupported call" naming the callee, with the TypeSOL form of common JavaScript calls. */
709
+ unsupportedCall(callee) {
710
+ const text = callee.getText();
711
+ const hints = {
712
+ "console.log": "log(…)",
713
+ "Math.min": "min(a, b)",
714
+ "Math.max": "max(a, b)",
715
+ "Date.now": "now() (the Clock's unix timestamp)",
716
+ "JSON.stringify": "log(…) with the values",
717
+ Number: "u64(x) or another integer cast",
718
+ BigInt: "u64(x) or another integer cast",
719
+ String: "a FixedString<N> field, or log(…)",
720
+ };
721
+ const hint = hints[text];
722
+ if (hint)
723
+ return `unsupported call: ${text}; use ${hint}`;
724
+ if (ts.isPropertyAccessExpression(callee) && this.accountAt(callee.expression))
725
+ return `unsupported call: the account ${callee.expression.getText()} has no method ${callee.name.text}`;
726
+ return `unsupported call: ${text.length > 60 ? `${text.slice(0, 57)}…` : text}`;
646
727
  }
647
728
  vecMethod(node, method, v) {
648
729
  const args = node.arguments;
@@ -941,7 +1022,7 @@ export class CallEmitter extends ExpressionEmitter {
941
1022
  /** C pointer (`TsAccount *`) for an expression naming a remaining account, or undefined. */
942
1023
  /** Whether `node` is an InstructionsSysvar parameter. */
943
1024
  instructionsParam(node) {
944
- const a = ts.isIdentifier(node) ? this.accounts.get(node.text) : undefined;
1025
+ const a = this.accountAt(node);
945
1026
  return a?.kind.kind === "instructionsSysvar" ? a : undefined;
946
1027
  }
947
1028
  /** Whether `node` is a TransactionInstruction: a local holding one, or `ixs.get(i)`. */
@@ -1445,7 +1526,20 @@ export class CallEmitter extends ExpressionEmitter {
1445
1526
  }
1446
1527
  this.fail(node, "the error must be a member of an exported error enum or a string literal");
1447
1528
  }
1529
+ /** The struct of `returnData<Quote>(…)`, when T is one; refused when its bytes are not its Borsh form. */
1530
+ returnedStruct(node) {
1531
+ const targ = node.typeArguments?.[0];
1532
+ const name = targ && structNameOf(targ, this.scope);
1533
+ const s = name ? this.model.structs.get(name) : undefined;
1534
+ if (!s)
1535
+ return undefined;
1536
+ if (s.layout !== "borsh" && !borshIdentical({ kind: "struct", name: s.name }, this.model))
1537
+ this.fail(targ, `${s.name} holds Options or FixedStrings, whose fixed layout is not Borsh: declare it /** @layout borsh */ to read it as return data`);
1538
+ return s;
1539
+ }
1448
1540
  returnData(node) {
1541
+ if (this.returnedStruct(node))
1542
+ this.fail(node, "bind a returned struct to a local: const quote = returnData<Quote>(program)");
1449
1543
  const targ = node.typeArguments?.[0];
1450
1544
  const t = targ && resolveScalarType(targ, this.scope);
1451
1545
  if (!t)
@@ -36,6 +36,14 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
36
36
  name: string;
37
37
  count: number | string;
38
38
  };
39
+ /**
40
+ * Several PDAs signing one CPI: `[["vault", owner.key, vaultBump], ["fees", feeBump]]` (or SignerSeeds parameters
41
+ * in the list). Undefined for a single seed list, which keeps the one-signer code.
42
+ */
43
+ protected signerSets(node: ts.Expression): {
44
+ ptr: string;
45
+ count: number;
46
+ } | undefined;
39
47
  /** Object literal properties by name, refusing others. */
40
48
  protected literalProps(o: ts.ObjectLiteralExpression, allowed: string[], what: string): Map<string, ts.Expression>;
41
49
  /** `acct.key` of an account parameter, as an expression to serialize. */
@@ -112,8 +112,8 @@ export class CpiCoreEmitter extends CallEmitter {
112
112
  return { kind: "const", value: Array.from({ length: bytes }, (_, i) => Number((v >> BigInt(8 * i)) & 0xffn)) };
113
113
  }
114
114
  }
115
- if (ts.isPropertyAccessExpression(el) && ts.isIdentifier(el.expression)) {
116
- const a = this.accounts.get(el.expression.text);
115
+ if (ts.isPropertyAccessExpression(el) && this.accountAt(el.expression)) {
116
+ const a = this.accountAt(el.expression);
117
117
  if (a && el.name.text === "key")
118
118
  return { kind: "account", path: snakeCase(a.name) };
119
119
  if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
@@ -166,6 +166,21 @@ export class CpiCoreEmitter extends CallEmitter {
166
166
  }
167
167
  return this.seeds(node, 0);
168
168
  }
169
+ /**
170
+ * Several PDAs signing one CPI: `[["vault", owner.key, vaultBump], ["fees", feeBump]]` (or SignerSeeds parameters
171
+ * in the list). Undefined for a single seed list, which keeps the one-signer code.
172
+ */
173
+ signerSets(node) {
174
+ const isSet = (e) => ts.isArrayLiteralExpression(e) || (ts.isIdentifier(e) && this.lookup(e.text)?.type.kind === "signerSeeds");
175
+ if (!ts.isArrayLiteralExpression(node) || node.elements.length === 0 || !node.elements.every(isSet))
176
+ return undefined;
177
+ if (node.elements.length > 16)
178
+ this.fail(node, "at most 16 PDAs can sign one CPI");
179
+ const sets = node.elements.map((e) => this.signingSeeds(e));
180
+ const arr = this.tmp("signers");
181
+ this.line(`SolSignerSeeds ${arr}[${sets.length}] = {${sets.map((s) => `{${s.name}, ${s.count}}`).join(", ")}};`);
182
+ return { ptr: arr, count: sets.length };
183
+ }
169
184
  /** Object literal properties by name, refusing others. */
170
185
  literalProps(o, allowed, what) {
171
186
  const props = new Map();
@@ -133,7 +133,8 @@ export class CpiEmitter extends MetaplexEmitter {
133
133
  this.serialize(this.expr(el), el, put);
134
134
  }
135
135
  finish(a[2]);
136
- const seeds = hasSeeds ? this.signingSeeds(a[3]) : { name: "NULL", count: 0 };
136
+ const multi = hasSeeds ? this.signerSets(a[3]) : undefined;
137
+ const seeds = hasSeeds && !multi ? this.signingSeeds(a[3]) : { name: "NULL", count: 0 };
137
138
  const metasName = this.tmp("metas");
138
139
  let count = String(metas.length);
139
140
  if (parts.some((p) => p.kind === "spread")) {
@@ -167,7 +168,9 @@ export class CpiEmitter extends MetaplexEmitter {
167
168
  this.line(`SolAccountMeta ${metasName}[${Math.max(metas.length, 1)}] = {${metas.join(", ")}};`);
168
169
  const ixName = this.tmp("cpi");
169
170
  this.line(`SolInstruction ${ixName} = {${programKey}, ${metasName}, ${count}, ${buf}, ${len}};`);
170
- if (hasSeeds) {
171
+ if (multi)
172
+ this.line(`TS_TRY(ts_invoke(params, &${ixName}, ${multi.ptr}, ${multi.count}));`);
173
+ else if (hasSeeds) {
171
174
  const signer = this.tmp("signer");
172
175
  this.line(`SolSignerSeeds ${signer} = {${seeds.name}, ${seeds.count}};`);
173
176
  // No seeds (e.g. signer([]) passed to a helper) means no PDA signature at all.
@@ -213,7 +216,8 @@ export class CpiEmitter extends MetaplexEmitter {
213
216
  if (data.elem.kind !== "int" || data.elem.name !== "u8")
214
217
  this.fail(a[2], "the data is a list of u8");
215
218
  const range = this.remainingRange(a[3]) ?? this.fail(a[3], "pass the accounts the CPI may use: remainingAccounts() or rest.slice(a, b)");
216
- const seeds = a.length === 5 ? this.signingSeeds(a[4]) : undefined;
219
+ const multi = a.length === 5 ? this.signerSets(a[4]) : undefined;
220
+ const seeds = a.length === 5 && !multi ? this.signingSeeds(a[4]) : undefined;
217
221
  const n = this.tmp("dn");
218
222
  const m = this.tmp("dmetas");
219
223
  const i = this.tmp("di");
@@ -232,7 +236,9 @@ export class CpiEmitter extends MetaplexEmitter {
232
236
  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}++]);`);
233
237
  const ixName = this.tmp("cpi");
234
238
  this.line(`SolInstruction ${ixName} = {&${programKey}, ${m}, ${n}, (uint8_t *)${data.items}, ${data.count}};`);
235
- if (seeds) {
239
+ if (multi)
240
+ this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, ${multi.ptr}, ${multi.count}));`);
241
+ else if (seeds) {
236
242
  const signer = this.tmp("signer");
237
243
  this.line(`SolSignerSeeds ${signer} = {${seeds.name}, ${seeds.count}};`);
238
244
  this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, &${signer}, ${typeof seeds.count === "number" ? (seeds.count > 0 ? 1 : 0) : `${seeds.count} > 0 ? 1 : 0`}));`);
@@ -36,4 +36,6 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
36
36
  protected systemTransfer(node: ts.CallExpression): undefined;
37
37
  /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
38
38
  protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
39
+ /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
40
+ protected allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
39
41
  }
@@ -458,8 +458,8 @@ export class CreateEmitter extends CpiCoreEmitter {
458
458
  this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
459
459
  if (this.created.has(target.name))
460
460
  this.fail(node, `${target.name} is already created`);
461
- if (node.arguments.length !== 1)
462
- this.fail(node, `${call}(payer) takes the payer`);
461
+ if (node.arguments.length !== 1 && node.arguments.length !== 2)
462
+ this.fail(node, `${call}(payer, tokenProgram?) takes the payer and, with several token programs, the one to use`);
463
463
  const payer = this.accountParam(node.arguments[0], "the payer");
464
464
  if (payer.kind.kind !== "signer" || !payer.kind.mut)
465
465
  this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
@@ -473,11 +473,22 @@ export class CreateEmitter extends CpiCoreEmitter {
473
473
  };
474
474
  const ataProgram = need("ataProgram", "an AssociatedTokenProgram");
475
475
  const system = need("system", "a SystemProgram");
476
- const tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
477
- // The address is derived under the token program: with two, which one the mint uses is not known here.
478
- const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
479
- if (tokenPrograms.length > 1)
480
- this.fail(node, `${call}(...) needs exactly one token program parameter (found ${tokenPrograms.map((o) => o.name).join(", ")}); use TokenInterface`);
476
+ // The address is derived under the token program: the one passed (Anchor's associated_token::token_program), or the
477
+ // instruction's only one.
478
+ let tokenProgram;
479
+ if (node.arguments[1]) {
480
+ tokenProgram = this.accountParam(node.arguments[1], "the token program");
481
+ if (tokenProgram.kind.kind !== "tokenProgram")
482
+ this.fail(node.arguments[1], "pass a TokenProgram, Token2022Program or TokenInterface parameter");
483
+ if (tokenProgram.optional)
484
+ this.fail(node.arguments[1], `${call}(...) needs "${tokenProgram.name}": it cannot be optional`);
485
+ }
486
+ else {
487
+ tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
488
+ const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
489
+ if (tokenPrograms.length > 1)
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
+ }
481
492
  const { owner, mint } = target.constraints.ata;
482
493
  const a = `a_${target.name}`;
483
494
  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));`;
@@ -504,17 +515,26 @@ export class CreateEmitter extends CpiCoreEmitter {
504
515
  return result;
505
516
  }
506
517
  systemTransfer(node) {
507
- if (node.arguments.length !== 3)
508
- this.fail(node, "transfer(from, to, lamports) takes three arguments");
509
- const [fromN, toN, amtN] = node.arguments;
518
+ const a = node.arguments;
519
+ if (a.length !== 3 && a.length !== 4)
520
+ this.fail(node, "transfer(from, to, lamports, signerSeeds?)");
521
+ const [fromN, toN, amtN] = a;
510
522
  const from = this.accountParam(fromN, "transfer's source");
511
- if (from.kind.kind !== "signer" || !from.kind.mut)
512
- this.fail(fromN, "the source must be a Mut<Signer>");
523
+ if (a.length === 3 && (from.kind.kind !== "signer" || !from.kind.mut))
524
+ 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))
526
+ this.fail(fromN, "the source must be writable (Mut<...>)");
513
527
  const to = this.accountParam(toN, "transfer's destination");
514
528
  if (!isWritable(to.kind))
515
529
  this.fail(toN, "the destination must be writable (Mut<...>)");
516
530
  const amt = this.expect(this.expr(amtN, U64), U64, amtN);
517
- this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
531
+ if (a.length === 3)
532
+ this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
533
+ else {
534
+ // A system-owned PDA of this program (a SOL vault) pays.
535
+ 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}));`);
537
+ }
518
538
  return undefined;
519
539
  }
520
540
  /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
@@ -545,4 +565,27 @@ export class CreateEmitter extends CpiCoreEmitter {
545
565
  ], buf, len, seeds);
546
566
  return undefined;
547
567
  }
568
+ /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
569
+ allocateOrAssign(node, system, method) {
570
+ const a = node.arguments;
571
+ if (a.length !== 2 && a.length !== 3)
572
+ this.fail(node, `${method}(account, ${method === "allocate" ? "space" : "owner"}, signerSeeds?)`);
573
+ const acct = this.accountParam(a[0], "the account");
574
+ if (!isWritable(acct.kind))
575
+ this.fail(a[0], `the account must be writable (Mut<Signer> or Mut<AccountInfo>)`);
576
+ if (acct.kind.kind !== "signer" && a.length !== 3)
577
+ this.fail(a[0], "the account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
578
+ const { buf, len, put, finish } = this.byteBuffer("sys", 36, "TS_ERR_INSTRUCTION_DATA", "system instruction");
579
+ const tag = this.tmp("tag");
580
+ this.line(`uint32_t ${tag} = ${method === "allocate" ? 8 : 1}; /* ${method === "allocate" ? "Allocate" : "Assign"} */`);
581
+ put(`&${tag}`, "4", 4);
582
+ if (method === "allocate")
583
+ this.serialize(this.expect(this.expr(a[1], U64), U64, a[1]), a[1], put);
584
+ else
585
+ this.serialize(this.expect(this.expr(a[1], PUBKEY), PUBKEY, a[1]), a[1], put);
586
+ finish(node);
587
+ const seeds = a.length === 3 ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
588
+ this.cpi(`a_${system.name}`, [[`a_${acct.name}`, true, true]], buf, len, seeds);
589
+ return undefined;
590
+ }
548
591
  }
@@ -59,7 +59,7 @@ export class ExpressionEmitter extends StorageEmitter {
59
59
  */
60
60
  optionalChain(node) {
61
61
  const base = node.expression;
62
- const optAccount = ts.isIdentifier(base) ? this.accounts.get(base.text) : undefined;
62
+ const optAccount = this.accountAt(base);
63
63
  let present;
64
64
  if (optAccount?.optional)
65
65
  present = `a_${optAccount.name} != NULL`;
@@ -205,6 +205,8 @@ export class ExpressionEmitter extends StorageEmitter {
205
205
  }
206
206
  if (this.accounts.has(node.text))
207
207
  this.fail(node, `"${node.text}" is an account; use ${node.text}.key for its address`);
208
+ if (this.isGroup(node.text))
209
+ this.fail(node, `"${node.text}" is a group of accounts; use one of its fields (${node.text}.…)`);
208
210
  if (calleeName(node, this.model.helperDecls, this.checker) || this.model.helpers.has(node.text))
209
211
  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`);
210
212
  this.fail(node, `unknown name "${node.text}"`);
@@ -320,8 +322,10 @@ export class ExpressionEmitter extends StorageEmitter {
320
322
  }
321
323
  this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner and isWritable, not ${field}`);
322
324
  }
323
- if (ts.isIdentifier(node.expression)) {
324
- const a = this.accounts.get(node.expression.text);
325
+ if (this.accountAt(node))
326
+ this.fail(node, `"${node.getText()}" is an account; use ${node.getText()}.key for its address`);
327
+ if (ts.isIdentifier(node.expression) || this.accountAt(node.expression)) {
328
+ const a = this.accountAt(node.expression);
325
329
  if (a) {
326
330
  const v = `a_${a.name}`;
327
331
  // The address is known before an Init account is created (Anchor seeds use `mint.key()` that way).
@@ -421,6 +425,8 @@ export class ExpressionEmitter extends StorageEmitter {
421
425
  return this.readStorage(r, node);
422
426
  this.fail(node.name, `"${field}" is not available on ${a.name}`);
423
427
  }
428
+ if (!ts.isIdentifier(node.expression))
429
+ this.fail(node, "unreachable: an account group's field");
424
430
  if (this.model.errorEnums.has(node.expression.text))
425
431
  this.fail(node, "error enum members can only be used as the second argument of require()");
426
432
  if (this.exportName(node.expression) === "AuthorityType") {
@@ -748,7 +754,7 @@ export class ExpressionEmitter extends StorageEmitter {
748
754
  const isNullNode = (n) => n.kind === ts.SyntaxKind.NullKeyword;
749
755
  if (isEq && (isNullNode(node.left) || isNullNode(node.right))) {
750
756
  const other = isNullNode(node.left) ? node.right : node.left;
751
- const optionalAccount = ts.isIdentifier(other) ? this.accounts.get(other.text) : undefined;
757
+ const optionalAccount = this.accountAt(other);
752
758
  if (optionalAccount?.optional) {
753
759
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
754
760
  return { c: `(a_${optionalAccount.name} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
@@ -874,14 +880,18 @@ export class ExpressionEmitter extends StorageEmitter {
874
880
  break;
875
881
  case K.AsteriskToken:
876
882
  // u64: skips the 128-bit __multi3 call when both factors fit in 32 bits (see ts_mul_overflow_u64).
877
- this.line(`if (${type.name === "u64" ? "ts_mul_overflow_u64" : "__builtin_mul_overflow"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
883
+ // u128: the native 64-bit multiply when both factors fit in 64 bits (see ts_mul_overflow_u128).
884
+ this.line(`if (${type.name === "u64" ? "ts_mul_overflow_u64" : type.name === "u128" ? "ts_mul_overflow_u128" : "__builtin_mul_overflow"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
878
885
  break;
879
886
  case K.SlashToken:
880
887
  case K.PercentToken: {
881
888
  this.line(`if (${right.c} == 0) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
882
889
  if (INT_INFO[type.name].signed)
883
890
  this.line(`if (${left.c} == ${intLiteral(INT_INFO[type.name].min, type.name)} && ${right.c} == -1) ${overflow};`);
884
- this.line(`${t} = ${left.c} ${op === K.SlashToken ? "/" : "%"} ${right.c};`);
891
+ if (type.name === "u128")
892
+ this.line(`${t} = ${op === K.SlashToken ? "ts_div_u128" : "ts_rem_u128"}(${left.c}, ${right.c});`);
893
+ else
894
+ this.line(`${t} = ${left.c} ${op === K.SlashToken ? "/" : "%"} ${right.c};`);
885
895
  break;
886
896
  }
887
897
  case K.AmpersandToken:
@@ -1,4 +1,4 @@
1
- import { type Instruction } from "../model.js";
1
+ import { type AccountParam, type Instruction } from "../model.js";
2
2
  import { StatementEmitter } from "./statements.js";
3
3
  /**
4
4
  * One instruction or helper as a C function: the instruction prologue (account checks, constraints and
@@ -14,6 +14,8 @@ export declare class FunctionEmitter extends StatementEmitter {
14
14
  * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
15
15
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
16
16
  */
17
+ /** `TS_FAIL` for a failed check: your error when the parameter's type names one (Anchor's `@ ErrorCode.X`), else Anchor's. */
18
+ protected checkFail(a: AccountParam, key: string, code: string, msg: string): string;
17
19
  /**
18
20
  * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
19
21
  * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
@@ -45,10 +45,10 @@ export class FunctionEmitter extends StatementEmitter {
45
45
  if (k.kind === "zeroed")
46
46
  head.push(` TS_TRY(ts_check_zeroed(${v}, params->program_id, ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : `sizeof(TSS_${k.struct.name})`}));`);
47
47
  if (isWritable(k))
48
- head.push(` TS_TRY(ts_check_mut(${v}));`);
48
+ head.push(a.constraints.errors?.has("mut") ? ` if (!${v}->is_writable) ${this.checkFail(a, "mut", "", "")};` : ` TS_TRY(ts_check_mut(${v}));`);
49
49
  // Signed<…>: Anchor's `signer` constraint (2002), right after `mut`.
50
50
  if (a.constraints.signed)
51
- head.push(` if (!${v}->is_signer) TS_FAIL(TS_ERR_CONSTRAINT_SIGNER, "TypeSOL: ${a.name} must sign");`);
51
+ head.push(` if (!${v}->is_signer) ${this.checkFail(a, "signer", "TS_ERR_CONSTRAINT_SIGNER", `${a.name} must sign`)};`);
52
52
  // A @layout borsh account only has to hold its smallest Borsh form (unpacking checks the rest).
53
53
  if (k.kind === "account")
54
54
  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)}));`);
@@ -125,11 +125,7 @@ export class FunctionEmitter extends StatementEmitter {
125
125
  const reallocated = (() => {
126
126
  let found = false;
127
127
  const visit = (nd) => {
128
- if (ts.isCallExpression(nd) &&
129
- this.exportName(nd.expression) === "realloc" &&
130
- nd.arguments[0] &&
131
- ts.isIdentifier(nd.arguments[0]) &&
132
- nd.arguments[0].text === a.name)
128
+ if (ts.isCallExpression(nd) && this.exportName(nd.expression) === "realloc" && nd.arguments[0] && this.accountAt(nd.arguments[0]) === a)
133
129
  found = true;
134
130
  ts.forEachChild(nd, visit);
135
131
  };
@@ -411,6 +407,16 @@ export class FunctionEmitter extends StatementEmitter {
411
407
  * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
412
408
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
413
409
  */
410
+ /** `TS_FAIL` for a failed check: your error when the parameter's type names one (Anchor's `@ ErrorCode.X`), else Anchor's. */
411
+ checkFail(a, key, code, msg) {
412
+ const ref = a.constraints.errors?.get(key);
413
+ if (!ref)
414
+ return `TS_FAIL(${code}, ${cString(`TypeSOL: ${msg}`)})`;
415
+ const def = this.model.errorEnums.get(ref.enumName)?.get(ref.member);
416
+ if (!def)
417
+ this.reporter.fail(ref.node, `${ref.enumName}.${ref.member} is not one of this program's errors`);
418
+ return `TS_FAIL(${def.code}, ${cString(`Error ${def.code} ${def.name}: ${def.msg} (${this.location(a.node)})`)})`;
419
+ }
414
420
  /**
415
421
  * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
416
422
  * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
@@ -428,7 +434,7 @@ export class FunctionEmitter extends StatementEmitter {
428
434
  const [acct, cond, error] = call.arguments;
429
435
  if (!acct || !cond || call.arguments.length > 3)
430
436
  this.fail(call, "constraint(account, condition, error?) takes an account parameter, a condition and an optional error");
431
- const a = ts.isIdentifier(acct) ? ix.accounts.find((x) => x.name === acct.text) : undefined;
437
+ const a = this.accountAt(acct);
432
438
  if (!a)
433
439
  this.fail(acct, "constraint's first argument is the account parameter the check belongs to (it runs with that account's checks)");
434
440
  const mark = this.lines.length;
@@ -481,21 +487,24 @@ export class FunctionEmitter extends StatementEmitter {
481
487
  const code = f === "mintAuthority" ? "TS_ERR_MINT_AUTHORITY" : "TS_ERR_FREEZE_AUTHORITY";
482
488
  hasOne.push(` if (ts_read_le(a_${a.name}->data + ${at}, 4) != 1 || !ts_key_eq((const SolPubkey *)(a_${a.name}->data + ${at + 4}), &a_${p}->key)) TS_FAIL(${code}, "TypeSOL: ${p} is not the ${f} of ${a.name}");`);
483
489
  }
484
- else
485
- hasOne.push(` if (!ts_key_eq(&d_${a.name}->${f}, &a_${f}->key)) TS_FAIL(TS_ERR_CONSTRAINT, "TypeSOL: ${a.name}.${f} must be the ${f} account");`);
490
+ else {
491
+ // A field of the same account group, or the parameter of the same name.
492
+ const target = c.hasOneParams?.get(f) ?? f;
493
+ hasOne.push(` if (!ts_key_eq(&d_${a.name}->${f}, &a_${target}->key)) ${this.checkFail(a, `hasOne:${f}`, "TS_ERR_CONSTRAINT", `${a.name}.${f} must be the ${f} account`)};`);
494
+ }
486
495
  }
487
496
  if (k === "account")
488
497
  out.push(...hasOne);
489
498
  out.push(...(raw.get(a.name) ?? []));
490
499
  if (c.owner) {
491
500
  out.push(` static const SolPubkey co_${a.name} = {${cBytes(c.owner.bytes)}};`);
492
- out.push(` if (!ts_key_eq(&a_${a.name}->owner, &co_${a.name})) TS_FAIL(TS_ERR_CONSTRAINT_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`);
501
+ 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`)};`);
493
502
  }
494
503
  if (c.executable)
495
504
  out.push(` if (!a_${a.name}->executable) TS_FAIL(TS_ERR_CONSTRAINT_EXECUTABLE, "TypeSOL: ${a.name} must be an executable program");`);
496
505
  if (c.address) {
497
506
  out.push(` static const SolPubkey ca_${a.name} = {${cBytes(c.address.bytes)}};`);
498
- out.push(` if (!ts_key_eq(&a_${a.name}->key, &ca_${a.name})) TS_FAIL(TS_ERR_ADDRESS, "TypeSOL: ${a.name} is not the expected address");`);
507
+ out.push(` if (!ts_key_eq(&a_${a.name}->key, &ca_${a.name})) ${this.checkFail(a, "address", "TS_ERR_ADDRESS", `${a.name} is not the expected address`)};`);
499
508
  }
500
509
  if (k !== "account")
501
510
  out.push(...hasOne);