@typesol/cli 0.32.0 → 0.34.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.
@@ -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";
@@ -535,6 +536,8 @@ export class CallEmitter extends ExpressionEmitter {
535
536
  }
536
537
  case "returnData":
537
538
  return this.returnData(node);
539
+ case "instructionData":
540
+ this.fail(node, "bind the data to a local first: const data = instructionData()");
538
541
  case "fixedArray":
539
542
  this.fail(node, "fixedArray<T, N>(fill) is only allowed as a local declaration: const xs = fixedArray<u64, 4>(0n)");
540
543
  case "readonly":
@@ -661,8 +664,8 @@ export class CallEmitter extends ExpressionEmitter {
661
664
  const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
662
665
  return { c: `ts_key_eq(${this.settle(left, mark).c}, ${right.c})`, type: BOOL };
663
666
  }
664
- if (ts.isIdentifier(callee.expression)) {
665
- const target = this.accounts.get(callee.expression.text);
667
+ if (this.accountAt(callee.expression)) {
668
+ const target = this.accountAt(callee.expression);
666
669
  // Program accounts used through their methods (systemProgram.transfer, tokenProgram.*…) may be optional.
667
670
  if (target?.optional)
668
671
  this.assertUsable(target, callee.expression);
@@ -686,6 +689,10 @@ export class CallEmitter extends ExpressionEmitter {
686
689
  return this.tokenOp(node, target, method);
687
690
  if (target?.kind.kind === "ataProgram")
688
691
  return this.ataOp(node, target, method);
692
+ if (target?.kind.kind === "memoProgram")
693
+ return this.memoOp(node, target, method);
694
+ if (target?.kind.kind === "stakeProgram")
695
+ return this.stakeOp(node, target, method);
689
696
  if (target?.kind.kind === "metadataProgram")
690
697
  return this.metadataOp(node, target, method);
691
698
  // Each Metaplex CPI in its own C block: its data buffer's stack slot is reused by the next one.
@@ -720,10 +727,8 @@ export class CallEmitter extends ExpressionEmitter {
720
727
  const hint = hints[text];
721
728
  if (hint)
722
729
  return `unsupported call: ${text}; use ${hint}`;
723
- if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
724
- if (this.accounts.get(callee.expression.text))
725
- return `unsupported call: the account ${callee.expression.text} has no method ${callee.name.text}`;
726
- }
730
+ if (ts.isPropertyAccessExpression(callee) && this.accountAt(callee.expression))
731
+ return `unsupported call: the account ${callee.expression.getText()} has no method ${callee.name.text}`;
727
732
  return `unsupported call: ${text.length > 60 ? `${text.slice(0, 57)}…` : text}`;
728
733
  }
729
734
  vecMethod(node, method, v) {
@@ -1023,7 +1028,7 @@ export class CallEmitter extends ExpressionEmitter {
1023
1028
  /** C pointer (`TsAccount *`) for an expression naming a remaining account, or undefined. */
1024
1029
  /** Whether `node` is an InstructionsSysvar parameter. */
1025
1030
  instructionsParam(node) {
1026
- const a = ts.isIdentifier(node) ? this.accounts.get(node.text) : undefined;
1031
+ const a = this.accountAt(node);
1027
1032
  return a?.kind.kind === "instructionsSysvar" ? a : undefined;
1028
1033
  }
1029
1034
  /** Whether `node` is a TransactionInstruction: a local holding one, or `ixs.get(i)`. */
@@ -1527,7 +1532,20 @@ export class CallEmitter extends ExpressionEmitter {
1527
1532
  }
1528
1533
  this.fail(node, "the error must be a member of an exported error enum or a string literal");
1529
1534
  }
1535
+ /** The struct of `returnData<Quote>(…)`, when T is one; refused when its bytes are not its Borsh form. */
1536
+ returnedStruct(node) {
1537
+ const targ = node.typeArguments?.[0];
1538
+ const name = targ && structNameOf(targ, this.scope);
1539
+ const s = name ? this.model.structs.get(name) : undefined;
1540
+ if (!s)
1541
+ return undefined;
1542
+ if (s.layout !== "borsh" && !borshIdentical({ kind: "struct", name: s.name }, this.model))
1543
+ 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`);
1544
+ return s;
1545
+ }
1530
1546
  returnData(node) {
1547
+ if (this.returnedStruct(node))
1548
+ this.fail(node, "bind a returned struct to a local: const quote = returnData<Quote>(program)");
1531
1549
  const targ = node.typeArguments?.[0];
1532
1550
  const t = targ && resolveScalarType(targ, this.scope);
1533
1551
  if (!t)
@@ -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")) {
@@ -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,12 @@ 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 (this.isGroupValue(node))
328
+ this.fail(node, `"${node.getText()}" is a group of accounts; use one of its fields (${node.getText()}.…)`);
329
+ if (ts.isIdentifier(node.expression) || this.accountAt(node.expression)) {
330
+ const a = this.accountAt(node.expression);
325
331
  if (a) {
326
332
  const v = `a_${a.name}`;
327
333
  // The address is known before an Init account is created (Anchor seeds use `mint.key()` that way).
@@ -367,6 +373,16 @@ export class ExpressionEmitter extends StorageEmitter {
367
373
  if (field === "tokenProgram")
368
374
  return { c: `&${v}->owner`, type: PUBKEY };
369
375
  }
376
+ if (k.kind === "slotHashes") {
377
+ // u64 count, then (u64 slot, 32-byte hash) entries, newest first; the entry check ran at entry.
378
+ if (field === "count")
379
+ return { c: `ts_read_le(${v}->data, 8)`, type: U64 };
380
+ if (field === "latestSlot")
381
+ return { c: `ts_read_le(${v}->data + 8, 8)`, type: U64 };
382
+ if (field === "latestHash")
383
+ return { c: `((const SolPubkey *)(${v}->data + 16))`, type: HASH };
384
+ this.fail(node.name, "SlotHashesSysvar has count, latestSlot and latestHash");
385
+ }
370
386
  if (k.kind === "pyth") {
371
387
  // Raw fields of the update; pythPrice() is the checked read.
372
388
  const m = `${v}->data + pm_${a.name}`;
@@ -421,6 +437,8 @@ export class ExpressionEmitter extends StorageEmitter {
421
437
  return this.readStorage(r, node);
422
438
  this.fail(node.name, `"${field}" is not available on ${a.name}`);
423
439
  }
440
+ if (!ts.isIdentifier(node.expression))
441
+ this.fail(node, "unreachable: an account group's field");
424
442
  if (this.model.errorEnums.has(node.expression.text))
425
443
  this.fail(node, "error enum members can only be used as the second argument of require()");
426
444
  if (this.exportName(node.expression) === "AuthorityType") {
@@ -748,7 +766,7 @@ export class ExpressionEmitter extends StorageEmitter {
748
766
  const isNullNode = (n) => n.kind === ts.SyntaxKind.NullKeyword;
749
767
  if (isEq && (isNullNode(node.left) || isNullNode(node.right))) {
750
768
  const other = isNullNode(node.left) ? node.right : node.left;
751
- const optionalAccount = ts.isIdentifier(other) ? this.accounts.get(other.text) : undefined;
769
+ const optionalAccount = this.accountAt(other);
752
770
  if (optionalAccount?.optional) {
753
771
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
754
772
  return { c: `(a_${optionalAccount.name} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
@@ -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)}));`);
@@ -76,6 +76,13 @@ export class FunctionEmitter extends StatementEmitter {
76
76
  head.push(` TS_TRY(ts_check_switchboard(${v}, ${k.devnet}));`);
77
77
  if (k.kind === "ataProgram")
78
78
  head.push(` TS_TRY(ts_check_address(${v}, &TS_ATA_PROGRAM_ID));`);
79
+ if (k.kind === "memoProgram")
80
+ head.push(` TS_TRY(ts_check_address(${v}, &TS_MEMO_PROGRAM_ID));`);
81
+ if (k.kind === "stakeProgram")
82
+ head.push(` TS_TRY(ts_check_address(${v}, &TS_STAKE_PROGRAM_ID));`);
83
+ // SlotHashes: the address, and room for its length and one entry (u64 count, then (u64 slot, hash) newest first).
84
+ if (k.kind === "slotHashes")
85
+ head.push(` TS_TRY(ts_check_address(${v}, &TS_SLOT_HASHES_ID));`, ` if (${v}->data_len < 48 || ts_read_le(${v}->data, 8) == 0) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: SlotHashes has no entries");`);
79
86
  if (k.kind === "metadataProgram")
80
87
  head.push(` TS_TRY(ts_check_address(${v}, &TS_MPL_METADATA_ID));`);
81
88
  if (k.kind === "coreProgram")
@@ -125,11 +132,7 @@ export class FunctionEmitter extends StatementEmitter {
125
132
  const reallocated = (() => {
126
133
  let found = false;
127
134
  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)
135
+ if (ts.isCallExpression(nd) && this.exportName(nd.expression) === "realloc" && nd.arguments[0] && this.accountAt(nd.arguments[0]) === a)
133
136
  found = true;
134
137
  ts.forEachChild(nd, visit);
135
138
  };
@@ -411,6 +414,16 @@ export class FunctionEmitter extends StatementEmitter {
411
414
  * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
412
415
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
413
416
  */
417
+ /** `TS_FAIL` for a failed check: your error when the parameter's type names one (Anchor's `@ ErrorCode.X`), else Anchor's. */
418
+ checkFail(a, key, code, msg) {
419
+ const ref = a.constraints.errors?.get(key);
420
+ if (!ref)
421
+ return `TS_FAIL(${code}, ${cString(`TypeSOL: ${msg}`)})`;
422
+ const def = this.model.errorEnums.get(ref.enumName)?.get(ref.member);
423
+ if (!def)
424
+ this.reporter.fail(ref.node, `${ref.enumName}.${ref.member} is not one of this program's errors`);
425
+ return `TS_FAIL(${def.code}, ${cString(`Error ${def.code} ${def.name}: ${def.msg} (${this.location(a.node)})`)})`;
426
+ }
414
427
  /**
415
428
  * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
416
429
  * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
@@ -428,7 +441,7 @@ export class FunctionEmitter extends StatementEmitter {
428
441
  const [acct, cond, error] = call.arguments;
429
442
  if (!acct || !cond || call.arguments.length > 3)
430
443
  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;
444
+ const a = this.accountAt(acct);
432
445
  if (!a)
433
446
  this.fail(acct, "constraint's first argument is the account parameter the check belongs to (it runs with that account's checks)");
434
447
  const mark = this.lines.length;
@@ -481,21 +494,24 @@ export class FunctionEmitter extends StatementEmitter {
481
494
  const code = f === "mintAuthority" ? "TS_ERR_MINT_AUTHORITY" : "TS_ERR_FREEZE_AUTHORITY";
482
495
  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
496
  }
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");`);
497
+ else {
498
+ // A field of the same account group, or the parameter of the same name.
499
+ const target = c.hasOneParams?.get(f) ?? f;
500
+ 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`)};`);
501
+ }
486
502
  }
487
503
  if (k === "account")
488
504
  out.push(...hasOne);
489
505
  out.push(...(raw.get(a.name) ?? []));
490
506
  if (c.owner) {
491
507
  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");`);
508
+ 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
509
  }
494
510
  if (c.executable)
495
511
  out.push(` if (!a_${a.name}->executable) TS_FAIL(TS_ERR_CONSTRAINT_EXECUTABLE, "TypeSOL: ${a.name} must be an executable program");`);
496
512
  if (c.address) {
497
513
  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");`);
514
+ 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
515
  }
500
516
  if (k !== "account")
501
517
  out.push(...hasOne);
@@ -14,6 +14,17 @@ type MplField = {
14
14
  /** Metaplex: Token Metadata, Core (plugins and external plugins) and Bubblegum. */
15
15
  export declare abstract class MetaplexEmitter extends TokenEmitter {
16
16
  protected metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
17
+ /** Metaplex creators `[{ address, verified, share }, …]` (1 to 5, shares adding up to 100): 34 bytes each. */
18
+ protected mplCreators(list0: ts.Expression): {
19
+ buf: string;
20
+ count: string;
21
+ };
22
+ /**
23
+ * updateMetadataAccountsV2(metadata, updateAuthority, data | null, newUpdateAuthority | null, primarySaleHappened |
24
+ * null, isMutable | null, signerSeeds?): Anchor's `update_metadata_accounts_v2`. `data` is the whole new DataV2
25
+ * (`{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`); each null leaves that part as it is.
26
+ */
27
+ protected metadataUpdate(node: ts.CallExpression, program: AccountParam): undefined;
17
28
  /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
18
29
  protected metadataCollectionOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
19
30
  /**
@@ -2,6 +2,7 @@ import ts from "typescript";
2
2
  import { isWritable, optionKey } from "../model.js";
3
3
  import { U64, U8, BOOL, PUBKEY, STRING, cBytes } from "./shared.js";
4
4
  import { TokenEmitter } from "./token.js";
5
+ const U16V = { kind: "int", name: "u16" };
5
6
  /**
6
7
  * Bubblegum instructions that replace a leaf: discriminator, accounts in order ([label, writable, signer, optional,
7
8
  * either-signs]) and the leaf's shape. Optional accounts take `null` (the program id). The Merkle proof follows the
@@ -186,8 +187,10 @@ export class MetaplexEmitter extends TokenEmitter {
186
187
  metadataOp(node, program, method) {
187
188
  if (method === "createMasterEditionV3" || method === "verifyCollection")
188
189
  return this.metadataCollectionOp(node, program, method);
190
+ if (method === "updateMetadataAccountsV2")
191
+ return this.metadataUpdate(node, program);
189
192
  if (method !== "createV3")
190
- this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3 and verifyCollection, not ${method}`);
193
+ this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3, verifyCollection and updateMetadataAccountsV2, not ${method}`);
191
194
  const a = node.arguments;
192
195
  const usage = "createV3(metadata, mint, mintAuthority, payer, updateAuthority, systemProgram, name, symbol, uri, sellerFeeBasisPoints, isMutable, { creators?, collection?, isCollection? }?, signerSeeds?)";
193
196
  // An object literal after isMutable carries the optional creators / collection; signerSeeds stays last.
@@ -228,42 +231,9 @@ export class MetaplexEmitter extends TokenEmitter {
228
231
  if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name))
229
232
  this.fail(p, "use creators: [...], collection: key and isCollection: boolean");
230
233
  if (p.name.text === "creators") {
231
- if (!ts.isArrayLiteralExpression(p.initializer))
232
- this.fail(p.initializer, "creators: [{ address, verified, share }, …] (an array literal)");
233
- const list = p.initializer.elements;
234
- if (list.length < 1 || list.length > 5)
235
- this.fail(p.initializer, "Metaplex takes 1 to 5 creators");
236
- const buf = this.tmp("creators");
237
- this.line(`uint8_t ${buf}[${34 * list.length}];`);
238
- let shares = 0n;
239
- let constant = true;
240
- list.forEach((el, i) => {
241
- if (!ts.isObjectLiteralExpression(el))
242
- this.fail(el, "a creator is { address, verified, share }");
243
- const field = (k) => {
244
- const q = el.properties.find((x) => ts.isPropertyAssignment(x) && ts.isIdentifier(x.name) && x.name.text === k);
245
- const sh = el.properties.find((x) => ts.isShorthandPropertyAssignment(x) && x.name.text === k);
246
- if (!q && !sh)
247
- this.fail(el, `a creator needs ${k}`);
248
- return q ? q.initializer : sh.name;
249
- };
250
- const at = 34 * i;
251
- const key = this.expect(this.expr(field("address"), PUBKEY), PUBKEY, el);
252
- this.line(`ts_memcpy(${buf} + ${at}, ${key.c}, 32);`);
253
- const verified = this.expect(this.expr(field("verified"), BOOL), BOOL, el);
254
- this.line(`${buf}[${at + 32}] = (${verified.c}) ? 1 : 0;`);
255
- const shareNode = field("share");
256
- if (ts.isBigIntLiteral(shareNode))
257
- shares += BigInt(shareNode.text.slice(0, -1));
258
- else
259
- constant = false;
260
- const share = this.expect(this.expr(shareNode, U8), U8, el);
261
- this.line(`${buf}[${at + 33}] = (uint8_t)(${share.c});`);
262
- });
263
- if (constant && shares !== 100n)
264
- this.fail(p.initializer, `creator shares add up to ${shares}; Metaplex requires 100`);
265
- creators = buf;
266
- ncreators = String(list.length);
234
+ const c = this.mplCreators(p.initializer);
235
+ creators = c.buf;
236
+ ncreators = c.count;
267
237
  }
268
238
  else if (p.name.text === "collection") {
269
239
  const key = this.expect(this.expr(p.initializer, PUBKEY), PUBKEY, p.initializer);
@@ -287,6 +257,107 @@ export class MetaplexEmitter extends TokenEmitter {
287
257
  this.line(`TS_TRY(ts_mpl_create_v3(params, a_${program.name}, a_${metadata.name}, a_${mint.name}, a_${mintAuth.name}, a_${payer.name}, a_${updateAuth.name}, a_${sys.name}, ${name.c}, ${symbol.c}, ${uri.c}, ${fee.c}, ${mutable.c}, ${creators}, ${ncreators}, ${collection}, ${sized}, ${seeds.name}, ${seeds.count}));`);
288
258
  return undefined;
289
259
  }
260
+ /** Metaplex creators `[{ address, verified, share }, …]` (1 to 5, shares adding up to 100): 34 bytes each. */
261
+ mplCreators(list0) {
262
+ if (!ts.isArrayLiteralExpression(list0))
263
+ this.fail(list0, "creators: [{ address, verified, share }, …] (an array literal)");
264
+ const list = list0.elements;
265
+ if (list.length < 1 || list.length > 5)
266
+ this.fail(list0, "Metaplex takes 1 to 5 creators");
267
+ const buf = this.tmp("creators");
268
+ this.line(`uint8_t ${buf}[${34 * list.length}];`);
269
+ let shares = 0n;
270
+ let constant = true;
271
+ list.forEach((el, i) => {
272
+ if (!ts.isObjectLiteralExpression(el))
273
+ this.fail(el, "a creator is { address, verified, share }");
274
+ const field = (k) => {
275
+ const q = el.properties.find((x) => ts.isPropertyAssignment(x) && ts.isIdentifier(x.name) && x.name.text === k);
276
+ const sh = el.properties.find((x) => ts.isShorthandPropertyAssignment(x) && x.name.text === k);
277
+ if (!q && !sh)
278
+ this.fail(el, `a creator needs ${k}`);
279
+ return q ? q.initializer : sh.name;
280
+ };
281
+ const at = 34 * i;
282
+ const key = this.expect(this.expr(field("address"), PUBKEY), PUBKEY, el);
283
+ this.line(`ts_memcpy(${buf} + ${at}, ${key.c}, 32);`);
284
+ const verified = this.expect(this.expr(field("verified"), BOOL), BOOL, el);
285
+ this.line(`${buf}[${at + 32}] = (${verified.c}) ? 1 : 0;`);
286
+ const shareNode = field("share");
287
+ if (ts.isBigIntLiteral(shareNode))
288
+ shares += BigInt(shareNode.text.slice(0, -1));
289
+ else
290
+ constant = false;
291
+ const share = this.expect(this.expr(shareNode, U8), U8, el);
292
+ this.line(`${buf}[${at + 33}] = (uint8_t)(${share.c});`);
293
+ });
294
+ if (constant && shares !== 100n)
295
+ this.fail(list0, `creator shares add up to ${shares}; Metaplex requires 100`);
296
+ return { buf, count: String(list.length) };
297
+ }
298
+ /**
299
+ * updateMetadataAccountsV2(metadata, updateAuthority, data | null, newUpdateAuthority | null, primarySaleHappened |
300
+ * null, isMutable | null, signerSeeds?): Anchor's `update_metadata_accounts_v2`. `data` is the whole new DataV2
301
+ * (`{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`); each null leaves that part as it is.
302
+ */
303
+ metadataUpdate(node, program) {
304
+ const a = node.arguments;
305
+ const usage = "updateMetadataAccountsV2(metadata, updateAuthority, data | null, newUpdateAuthority | null, primarySaleHappened | null, isMutable | null, signerSeeds?)";
306
+ if (a.length !== 6 && a.length !== 7)
307
+ this.fail(node, usage);
308
+ const metadata = this.accountParam(a[0], "the metadata account");
309
+ if (!isWritable(metadata.kind))
310
+ this.fail(a[0], "the metadata account must be Mut<AccountInfo>");
311
+ const ua = this.accountParam(a[1], "the update authority");
312
+ const isNull = (n) => n.kind === ts.SyntaxKind.NullKeyword;
313
+ let hasData = "false";
314
+ let name = "ts_str(NULL, 0)";
315
+ let symbol = name;
316
+ let uri = name;
317
+ let fee = "0";
318
+ let creators = "NULL";
319
+ let ncreators = "-1";
320
+ let collection = "NULL";
321
+ if (!isNull(a[2])) {
322
+ if (!ts.isObjectLiteralExpression(a[2]))
323
+ this.fail(a[2], "data is { name, symbol, uri, sellerFeeBasisPoints, creators?, collection? } or null");
324
+ const props = this.literalProps(a[2], ["name", "symbol", "uri", "sellerFeeBasisPoints", "creators", "collection"], "data");
325
+ for (const k of ["name", "symbol", "uri", "sellerFeeBasisPoints"])
326
+ if (!props.has(k))
327
+ this.fail(a[2], `data needs ${k} (it replaces the whole DataV2)`);
328
+ const text = (k) => {
329
+ const t = this.tmp("md");
330
+ this.line(`TS_Str ${t} = ${this.expect(this.expr(props.get(k), STRING), STRING, props.get(k)).c};`);
331
+ return t;
332
+ };
333
+ [name, symbol, uri] = ["name", "symbol", "uri"].map(text);
334
+ const f = this.tmp("fee");
335
+ this.line(`uint16_t ${f} = ${this.expect(this.expr(props.get("sellerFeeBasisPoints"), U16V), U16V, props.get("sellerFeeBasisPoints")).c};`);
336
+ fee = f;
337
+ if (props.has("creators"))
338
+ ({ buf: creators, count: ncreators } = this.mplCreators(props.get("creators")));
339
+ if (props.has("collection")) {
340
+ const key = this.expect(this.expr(props.get("collection"), PUBKEY), PUBKEY, props.get("collection"));
341
+ const t = this.tmp("coll");
342
+ this.line(`SolPubkey ${t} = *(${key.c});`);
343
+ collection = `&${t}`;
344
+ }
345
+ hasData = "true";
346
+ }
347
+ let next = "NULL";
348
+ if (!isNull(a[3])) {
349
+ const key = this.expect(this.expr(a[3], PUBKEY), PUBKEY, a[3]);
350
+ const t = this.tmp("ua");
351
+ this.line(`SolPubkey ${t} = *(${key.c});`);
352
+ next = `&${t}`;
353
+ }
354
+ const flag = (n) => (isNull(n) ? "-1" : `((${this.expect(this.expr(n, BOOL), BOOL, n).c}) ? 1 : 0)`);
355
+ const primary = flag(a[4]);
356
+ const mutable = flag(a[5]);
357
+ const seeds = this.signerSeeds(a[6], ua, a[1]);
358
+ this.line(`TS_TRY(ts_mpl_update_v2(params, a_${program.name}, a_${metadata.name}, a_${ua.name}, ${hasData}, ${name}, ${symbol}, ${uri}, ${fee}, ${creators}, ${ncreators}, ${collection}, ${next}, ${primary}, ${mutable}, ${seeds.name}, ${seeds.count}));`);
359
+ return undefined;
360
+ }
290
361
  /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
291
362
  metadataCollectionOp(node, program, method) {
292
363
  const a = node.arguments;
@@ -160,12 +160,16 @@ export function emitProgram(analysis, opts = {}) {
160
160
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
161
161
  if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_claim_mut(")))
162
162
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
163
- const minDisc = Math.min(8, ...model.instructions.map((ix) => ix.discriminator.length));
164
- out.push(` if (params.data_len < ${minDisc}) TS_FAIL(TS_ERR_INSTRUCTION_MISSING, "TypeSOL: instruction data too short");`);
163
+ const fallback = model.instructions.find((ix) => ix.fallback);
164
+ const dispatched = model.instructions.filter((ix) => !ix.fallback);
165
+ const minDisc = Math.min(8, ...dispatched.map((ix) => ix.discriminator.length));
166
+ // With a @fallback, short data goes to it too (Anchor's dispatch); each comparison below checks the length.
167
+ if (!fallback)
168
+ out.push(` if (params.data_len < ${minDisc}) TS_FAIL(TS_ERR_INSTRUCTION_MISSING, "TypeSOL: instruction data too short");`);
165
169
  // Self-CPI events (emitCpi): accept the event instruction when its authority PDA signed it, like Anchor.
166
170
  if (model.instructions.some((ix) => ix.accounts.some((a) => a.kind.kind === "eventAuthority")))
167
171
  out.push(` if (params.data_len >= 8 && ts_mem_eq(params.data, TS_EVENT_IX_TAG, 8)) return ts_event_dispatch(&params);`);
168
- for (const ix of model.instructions) {
172
+ for (const ix of dispatched) {
169
173
  const n = ix.discriminator.length;
170
174
  // An 8-byte discriminator is one u64 compare (the data is little-endian bytes, the literal their u64 value).
171
175
  if (n === 8) {
@@ -178,7 +182,7 @@ export function emitProgram(analysis, opts = {}) {
178
182
  out.push(` if (params.data_len >= ${n} && ts_mem_eq(params.data, disc, ${n})) return ix_${ix.name}(&params);`);
179
183
  out.push(` }`);
180
184
  }
181
- out.push(` TS_FAIL(TS_ERR_INSTRUCTION_NOT_FOUND, "TypeSOL: unknown instruction");`);
185
+ out.push(fallback ? ` return ix_${fallback.name}(&params);` : ` TS_FAIL(TS_ERR_INSTRUCTION_NOT_FOUND, "TypeSOL: unknown instruction");`);
182
186
  out.push(`}`);
183
187
  return out.join("\n") + "\n";
184
188
  }
@@ -547,8 +547,9 @@ export class StatementEmitter extends CpiEmitter {
547
547
  params.set(name, { c: "", type: BOOL, mutable: false, closure: this.closureOf(arg) });
548
548
  return;
549
549
  }
550
- if (p.type && ts.isIdentifier(arg) && !this.lookup(arg.text) && this.accounts.has(arg.text) && !resolveValueType(p.type, calleeScope)) {
551
- aliases.set(name, this.accounts.get(arg.text));
550
+ const passed = ts.isIdentifier(arg) && this.lookup(arg.text) ? undefined : this.accountAt(arg);
551
+ if (p.type && passed && !resolveValueType(p.type, calleeScope)) {
552
+ aliases.set(name, passed);
552
553
  return;
553
554
  }
554
555
  const c2 = `l_${name}_${this.temp++}`;
@@ -887,7 +888,7 @@ export class StatementEmitter extends CpiEmitter {
887
888
  if (this.scopes.at(-1).has(name))
888
889
  this.fail(d.name, `"${name}" is already declared`);
889
890
  // Account lookups go by name, so a local must not hide a parameter (it would read the parameter instead).
890
- if (this.accounts.has(name) || this.args.has(name))
891
+ if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
891
892
  this.fail(d.name, `"${name}" shadows the parameter "${name}"; use another name`);
892
893
  const c = `l_${name}_${this.temp++}`;
893
894
  const init = d.initializer;
@@ -901,6 +902,14 @@ export class StatementEmitter extends CpiEmitter {
901
902
  continue;
902
903
  }
903
904
  const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
905
+ // The instruction's data as sent, discriminator included (a @fallback's input): a list of u8.
906
+ if (fn === "instructionData") {
907
+ if (init.arguments.length)
908
+ this.fail(init, "instructionData() takes no arguments");
909
+ this.line(`TS_VecArg ${c} = {params->data, (uint32_t)params->data_len};`);
910
+ this.scopes.at(-1).set(name, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
911
+ continue;
912
+ }
904
913
  // A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
905
914
  if (fn === "signer") {
906
915
  if (mutable)
@@ -930,6 +939,40 @@ export class StatementEmitter extends CpiEmitter {
930
939
  this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d });
931
940
  continue;
932
941
  }
942
+ // A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
943
+ if (fn === "returnData" && this.returnedStruct(init)) {
944
+ if (mutable)
945
+ this.fail(d, "bind return data with const (its fields can still be updated)");
946
+ const S = this.returnedStruct(init);
947
+ const call = init;
948
+ if (call.arguments.length !== 1)
949
+ this.fail(call, "returnData<T>(program) takes the program that returned it");
950
+ const program = this.accountParam(call.arguments[0], "returnData's program");
951
+ const bad = `TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid ${S.name} return data")`;
952
+ if (S.layout === "borsh") {
953
+ // Borsh of any size: unpacked into the fixed-layout struct, every byte used.
954
+ const raw = `${c}__raw`;
955
+ this.line(`uint8_t *${raw};`);
956
+ this.line(`uint64_t ${raw}_len = 0, ${raw}_used = 0;`);
957
+ this.line(`TS_TRY(ts_return_data_any(a_${program.name}, &${raw}, &${raw}_len));`);
958
+ this.line(`TSS_${S.name} *${c};`);
959
+ this.line(`TS_TRY(ts_alloc(sizeof(TSS_${S.name}), (uint8_t **)&${c}));`);
960
+ this.line(`if (ts_unpack_${S.name}(${raw}, ${raw}_len, ${c}, &${raw}_used) != SUCCESS || ${raw}_used != ${raw}_len) ${bad};`);
961
+ for (const f of S.fields)
962
+ if (f.type.kind === "fstring")
963
+ this.line(`if (!ts_utf8_valid(${c}->${f.name}.bytes, ${c}->${f.name}.len)) ${bad};`);
964
+ }
965
+ else {
966
+ // A fixed layout whose bytes are its Borsh form: copied in, then bools and enums checked.
967
+ this.line(`TSS_${S.name} ${c}__v;`);
968
+ this.line(`TS_TRY(ts_return_data_exact(a_${program.name}, &${c}__v, sizeof(TSS_${S.name})));`);
969
+ for (const l of this.validation(`${c}__v`, { kind: "struct", name: S.name }, "", bad))
970
+ this.line(l.trim());
971
+ this.line(`TSS_${S.name} *${c} = &${c}__v;`);
972
+ }
973
+ this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
974
+ continue;
975
+ }
933
976
  // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
934
977
  const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
935
978
  if (structType) {
@@ -184,8 +184,8 @@ export class StorageEmitter extends AliasEmitter {
184
184
  if (ts.isPropertyAccessExpression(node)) {
185
185
  const field = node.name.text;
186
186
  // Migrate<From, To>: acct.from (the old data, read-only, until migrate()) and acct.to (after it).
187
- if (ts.isIdentifier(node.expression)) {
188
- const m = this.accounts.get(node.expression.text);
187
+ if (this.accountAt(node.expression)) {
188
+ const m = this.accountAt(node.expression);
189
189
  if (m?.kind.kind === "migrate") {
190
190
  const migrated = this.created.has(m.name);
191
191
  if (field === "from") {
@@ -202,8 +202,8 @@ export class StorageEmitter extends AliasEmitter {
202
202
  }
203
203
  }
204
204
  // acct.field on a struct account
205
- if (ts.isIdentifier(node.expression)) {
206
- const a = this.accounts.get(node.expression.text);
205
+ if (this.accountAt(node.expression)) {
206
+ const a = this.accountAt(node.expression);
207
207
  if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
208
208
  const f = a.kind.struct.fields.find((x) => x.name === field);
209
209
  if (!f)
@@ -445,9 +445,9 @@ export class StorageEmitter extends AliasEmitter {
445
445
  */
446
446
  /** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
447
447
  wholeAccount(node) {
448
- if (!ts.isIdentifier(node) || this.lookup(node.text))
448
+ if (ts.isIdentifier(node) && this.lookup(node.text))
449
449
  return undefined;
450
- const a = this.accounts.get(node.text);
450
+ const a = this.accountAt(node);
451
451
  if (!a || !(a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "initIfNeeded") || a.kind.struct.size === undefined || a.kind.struct.vec)
452
452
  return undefined;
453
453
  this.assertUsable(a, node);
@@ -680,8 +680,8 @@ export class StorageEmitter extends AliasEmitter {
680
680
  return { type: l.type, read: `(&${l.c})`, write: (c) => `${l.c} = *(${c})` };
681
681
  return { type: l.type, read: l.c, write: (c) => `${l.c} = ${c}` };
682
682
  }
683
- if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.name.text === "lamports") {
684
- const a = this.accounts.get(node.expression.text);
683
+ if (ts.isPropertyAccessExpression(node) && node.name.text === "lamports" && this.accountAt(node.expression)) {
684
+ const a = this.accountAt(node.expression);
685
685
  if (a) {
686
686
  this.assertUsable(a, node);
687
687
  if (!isWritable(a.kind))
@@ -5,4 +5,12 @@ import { CreateEmitter } from "./create.js";
5
5
  export declare abstract class TokenEmitter extends CreateEmitter {
6
6
  protected tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
7
7
  protected ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
8
+ /** memoProgram.memo(text, signers?, signerSeeds?): SPL Memo v2, the UTF-8 text as data, each signer a signing account. */
9
+ protected memoOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
10
+ /**
11
+ * The Stake program (bincode: a u32 instruction tag): initialize, authorize, delegate, deactivate and withdraw, with
12
+ * the sysvar and config accounts it reads passed in, as anchor-spl's stake module does. Each authority signs (a PDA of
13
+ * this program with `signerSeeds`).
14
+ */
15
+ protected stakeOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
8
16
  }