@typesol/cli 0.33.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,29 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.34.0 — 2026-10-30
10
+
11
+ More of anchor-spl and Anchor's tooling: Memo and Stake CPIs, Token Metadata updates, Token-2022 token groups, the
12
+ SlotHashes sysvar, `@fallback`, account groups inside account groups, and `typesol clone` for tests against cluster
13
+ accounts. Existing programs compile to the same binaries as in 0.33.0.
14
+
15
+ - New: account groups inside account groups (Anchor's nested composite accounts): `d.p.vault`, nested in the IDL,
16
+ flattened by the client and `typesol/testing` (`dPVault` / `d_p_vault`).
17
+ - New: Token Metadata `updateMetadataAccountsV2` (Anchor's `update_metadata_accounts_v2`): the whole DataV2 or null,
18
+ a new update authority, primary sale and mutability, signed by the update authority (a PDA with seeds).
19
+ - New: `StakeProgram`: `initialize`, `authorize`, `delegate`, `deactivate`, `withdraw`, with the sysvars passed in as
20
+ anchor-spl does, signed by wallets or this program's PDAs.
21
+ - New: `typesol clone [<address>…]` (Anchor's `[test.validator.clone]`): cluster accounts and programs copied to
22
+ `tests/accounts/` (`"clone"` and `"accounts"` in `typesol.json`), which `testProgram` loads into its LiteSVM;
23
+ `loadClonedAccounts(svm, dir)` for a LiteSVM of your own.
24
+ - New: `/** @fallback */` (Anchor's `fallback`): an instruction without parameters run when no other matches the data,
25
+ short data included, instead of 101; it reads `const data = instructionData()` and `remainingAccounts()`.
26
+ - New: `MemoProgram`: `memoProgram.memo(text, [signers], signerSeeds?)`, SPL Memo v2 signed by wallets or this
27
+ program's PDAs.
28
+ - New: `SlotHashesSysvar`, the SlotHashes sysvar read as an account: `count`, `latestSlot`, `latestHash`.
29
+ - New: the Token Group interface on Token-2022: `initializeTokenGroup`, `initializeGroupMember`, `updateGroupMaxSize`,
30
+ `updateGroupAuthority`.
31
+
9
32
  ## 0.33.0 — 2026-10-30
10
33
 
11
34
  The rest of what large Anchor programs lean on: account groups (composite accounts), your errors on declarative
package/README.md CHANGED
@@ -208,7 +208,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
208
208
  | **Constraints** | `HasOne`, `Seeds` (also from account fields and under another program; `pdaBump` like `ctx.bumps`), `CloseTo`, `Ata`, `Address`, `Owner`, `Executable`. They are checked before the body runs and recorded in the IDL, and take your own error as Anchor's `@ ErrorCode.X` does |
209
209
  | **Data** | `u8`…`u128`, `i8`…`i128`, `boolean`, `Pubkey`, `Hash`, nested structs, `FixedArray`, `FixedString`, `Option`, unit enums, data enums (discriminated unions), `Vec` that resizes its account, `FixedVec` lists anywhere, and Anchor's own byte layout (`@layout borsh`) to take over existing Anchor accounts and to pass, return and emit structs with String / Vec / Option fields as Anchor does |
210
210
  | **Control flow** | `if`, `for`, `for … of`, `while`, `switch` (with narrowing on data enums), ternaries, `??`, destructuring, helper functions (returning structs too, arrow functions, closures, function arguments, generics), list callbacks (`some`, `find`, `reduce`, …) across multiple files |
211
- | **CPIs** | System, SPL Token, Token-2022 (including extension reads and metadata), ATA, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing (one or several PDAs per call), return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
211
+ | **CPIs** | System, SPL Token, Token-2022 (including extension reads, metadata and token groups), ATA, Memo, Stake, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing (one or several PDAs per call), return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
212
212
  | **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
213
213
  | **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard |
214
214
  | **Interfaces** | custom discriminators (`@discriminator`), so a TypeSOL program can be a Token-2022 transfer hook, with extra accounts (ExtraAccountMetaList) |
@@ -221,6 +221,7 @@ The full reference, with every type, check and built-in, is in [docs/language.md
221
221
  | --- | --- |
222
222
  | `typesol init` | scaffold a project with a program, a LiteSVM test and TypeScript configs |
223
223
  | `typesol new <program>` | add another program and its test to a project |
224
+ | `typesol clone <address…>` | copy mainnet accounts and programs for the tests, loaded by `testProgram` |
224
225
  | `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
225
226
  | `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file) |
226
227
  | `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
package/dist/cli.js CHANGED
@@ -313,6 +313,36 @@ const COMMANDS = {
313
313
  return 0;
314
314
  },
315
315
  },
316
+ clone: {
317
+ usage: "typesol clone [<address>…] [--url <rpc>] [--config <solana cli config>] [--out <dir>]",
318
+ help: [
319
+ "Copy accounts and programs from a cluster for the tests (Anchor's [test.validator.clone]): each account to",
320
+ '<address>.json, each program to <address>.so (its ELF), in the project\'s tests/accounts ("accounts" in typesol.json)',
321
+ 'or --out. Without addresses, the project\'s "clone" list. testProgram loads that directory into its LiteSVM.',
322
+ "The RPC is --url, a cluster moniker, or the Solana CLI config.",
323
+ ].join("\n "),
324
+ options: { url: { type: "string" }, config: { type: "string" }, out: { type: "string" } },
325
+ async run(v, args) {
326
+ const ws = findWorkspace(process.cwd());
327
+ const addresses = args.length ? args : (ws?.clone ?? []);
328
+ if (!addresses.length)
329
+ throw new UsageError(`name the accounts to clone, or list them in ${CONFIG} as "clone": ["…"]`);
330
+ for (const a of addresses)
331
+ if (!decodeAddress(a))
332
+ throw new UsageError(`"${a}" is not a base58 Solana address`);
333
+ const dir = path.resolve(v.out ?? ws?.accounts ?? "accounts");
334
+ const rpcUrl = v.url ?? solanaConfig(v.config).url;
335
+ if (!rpcUrl)
336
+ throw new Error("no RPC: pass --url, or set json_rpc_url in the Solana CLI config");
337
+ const kit = await import("@solana/kit");
338
+ const { cloneAccounts } = await import("./tools/clone.js");
339
+ const lines = await cloneAccounts(kit.createSolanaRpc(clusterUrl(rpcUrl)), [...new Set(addresses)], dir);
340
+ for (const l of lines)
341
+ log(` ${l}`);
342
+ log(` ${lines.length} written to ${path.relative(process.cwd(), dir) || "."}`);
343
+ return 0;
344
+ },
345
+ },
316
346
  cpi: {
317
347
  usage: "typesol cpi <idl.json> [--out <file.ts>] [--prefix <name>] [--address <base58>]",
318
348
  help: "Generate TypeSOL helpers that call another program's instructions, from its Anchor IDL (0.30+/1.x or TypeSOL).",
@@ -94,6 +94,9 @@ const TYPE_EXPORTS = new Set([
94
94
  "PythPriceUpdate",
95
95
  "AssociatedTokenProgram",
96
96
  "TokenMetadataProgram",
97
+ "MemoProgram",
98
+ "StakeProgram",
99
+ "SlotHashesSysvar",
97
100
  "SwitchboardFeed",
98
101
  "HasOne",
99
102
  "TokenOf",
@@ -657,6 +660,14 @@ export function analyze(entry, files) {
657
660
  const ix = reporter.guard(() => analyzeInstruction(fn.node, reporter, scopeFor(fn.imports), structs, groups));
658
661
  if (!ix)
659
662
  continue;
663
+ // `/** @fallback */`: Anchor's fallback, run when no instruction matches the data (instead of 101).
664
+ if (ts.getJSDocTags(fn.node).some((t) => t.tagName.text === "fallback")) {
665
+ if (ix.accounts.length || ix.args.length || ix.returns)
666
+ reporter.error(fn.node.name ?? fn.node, "a @fallback takes no parameters and returns nothing: read remainingAccounts() and instructionData()");
667
+ if (instructions.some((o) => o.fallback))
668
+ reporter.error(fn.node.name ?? fn.node, "a program has at most one @fallback");
669
+ ix.fallback = true;
670
+ }
660
671
  instructions.push(ix);
661
672
  for (const a of ix.args)
662
673
  collectStructs(a.type, structs, dataEnums, argStructs);
@@ -1496,6 +1507,9 @@ const ACCOUNT_TYPES = new Set([
1496
1507
  "PythPriceUpdate",
1497
1508
  "AssociatedTokenProgram",
1498
1509
  "TokenMetadataProgram",
1510
+ "MemoProgram",
1511
+ "StakeProgram",
1512
+ "SlotHashesSysvar",
1499
1513
  "SwitchboardFeed",
1500
1514
  "HasOne",
1501
1515
  "TokenOf",
@@ -1576,40 +1590,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1576
1590
  if (group) {
1577
1591
  if (p.type.typeArguments)
1578
1592
  reporter.fail(p.type, "account groups take no type arguments");
1579
- const members = [];
1580
- for (const m of group.decl.members) {
1581
- if (!ts.isPropertySignature(m) || !m.type || !ts.isIdentifier(m.name))
1582
- reporter.fail(m, "account groups hold plain fields");
1583
- if (m.questionToken)
1584
- reporter.fail(m, `optional accounts are written ${m.name.text}: A | null`);
1585
- if (ts.isTypeReferenceNode(m.type) && ts.isIdentifier(m.type.typeName) && groups.has(m.type.typeName.text))
1586
- reporter.fail(m.type, "account groups do not nest yet: list the inner group's accounts here");
1587
- if (!ACCOUNT_TYPES.has(typesolName(withoutNull(m.type), group.imports) ?? ""))
1588
- reporter.fail(m.type, `${group.decl.name.text} is an account group: every field is an account (pass values as instruction arguments)`);
1589
- const a = accountFrom(m.type, `${p.name.text}__${m.name.text}`, m, group.imports);
1590
- a.group = { param: p.name.text, field: m.name.text, type: group.decl.name.text };
1591
- members.push(a);
1592
- }
1593
- // Constraints in a group name its own fields (as in Anchor's composite accounts), then the instruction's.
1594
- const sibling = (n) => (members.some((x) => x.group.field === n) ? `${p.name.text}__${n}` : n);
1595
- const at = (n) => (n.startsWith("@") ? `@${sibling(n.slice(1).split(".")[0])}${n.slice(1).includes(".") ? n.slice(n.indexOf(".")) : ""}` : n);
1596
- for (const a of members) {
1597
- const c = a.constraints;
1598
- c.hasOne = c.hasOne.map((e) => {
1599
- if (!e.includes("=")) {
1600
- if (sibling(e) !== e)
1601
- (c.hasOneParams ??= new Map()).set(e, sibling(e));
1602
- return e;
1603
- }
1604
- const [f, param] = e.split("=");
1605
- return `${f}=${sibling(param)}`;
1606
- });
1607
- if (c.seeds)
1608
- c.seeds = { ...c.seeds, names: c.seeds.names.map(at), bump: c.seeds.bump && at(c.seeds.bump), program: c.seeds.program && at(c.seeds.program) };
1609
- if (c.closeTo)
1610
- c.closeTo = sibling(c.closeTo);
1611
- if (c.ata)
1612
- c.ata = { owner: sibling(c.ata.owner), mint: sibling(c.ata.mint) };
1593
+ for (const a of expandGroup(group, [p.name.text], new Set())) {
1613
1594
  a.index = accounts.length;
1614
1595
  accounts.push(a);
1615
1596
  }
@@ -1620,6 +1601,60 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1620
1601
  accounts.push(a);
1621
1602
  });
1622
1603
  }
1604
+ /**
1605
+ * A group's accounts, in field order, named by their path (`pool__vault`, `pool__fees__vault` for a group inside a
1606
+ * group). Constraints in a group name its own fields first (as in Anchor's composite accounts), then the
1607
+ * instruction's parameters.
1608
+ */
1609
+ function expandGroup(group, path, visiting) {
1610
+ const name = group.decl.name.text;
1611
+ if (visiting.has(name))
1612
+ reporter.fail(group.decl.name, `${name} contains itself`);
1613
+ const prefix = path.join("__");
1614
+ const all = [];
1615
+ const own = [];
1616
+ for (const m of group.decl.members) {
1617
+ if (!ts.isPropertySignature(m) || !m.type || !ts.isIdentifier(m.name))
1618
+ reporter.fail(m, "account groups hold plain fields");
1619
+ if (m.questionToken)
1620
+ reporter.fail(m, `optional accounts are written ${m.name.text}: A | null`);
1621
+ const inner = ts.isTypeReferenceNode(m.type) && ts.isIdentifier(m.type.typeName) ? groups.get(m.type.typeName.text) : undefined;
1622
+ const innerBare = withoutNull(m.type);
1623
+ if (innerBare !== m.type && ts.isTypeReferenceNode(innerBare) && ts.isIdentifier(innerBare.typeName) && groups.has(innerBare.typeName.text))
1624
+ reporter.fail(m.type, "account groups cannot be optional; make the accounts inside it optional (field: A | null)");
1625
+ if (inner) {
1626
+ all.push(...expandGroup(inner, [...path, m.name.text], new Set([...visiting, name])));
1627
+ continue;
1628
+ }
1629
+ if (!ACCOUNT_TYPES.has(typesolName(withoutNull(m.type), group.imports) ?? ""))
1630
+ reporter.fail(m.type, `${name} is an account group: every field is an account (pass values as instruction arguments)`);
1631
+ const a = accountFrom(m.type, `${prefix}__${m.name.text}`, m, group.imports);
1632
+ a.group = { param: prefix, field: m.name.text, type: name, path };
1633
+ own.push(a);
1634
+ all.push(a);
1635
+ }
1636
+ const sibling = (n) => (own.some((x) => x.group.field === n) ? `${prefix}__${n}` : n);
1637
+ const at = (n) => (n.startsWith("@") ? `@${sibling(n.slice(1).split(".")[0])}${n.slice(1).includes(".") ? n.slice(n.indexOf(".")) : ""}` : n);
1638
+ for (const a of own) {
1639
+ const c = a.constraints;
1640
+ c.hasOne = c.hasOne.map((e) => {
1641
+ if (!e.includes("=")) {
1642
+ if (sibling(e) !== e)
1643
+ (c.hasOneParams ??= new Map()).set(e, sibling(e));
1644
+ return e;
1645
+ }
1646
+ const [f, param] = e.split("=");
1647
+ return `${f}=${sibling(param)}`;
1648
+ });
1649
+ if (c.seeds)
1650
+ c.seeds = { ...c.seeds, names: c.seeds.names.map(at), bump: c.seeds.bump && at(c.seeds.bump), program: c.seeds.program && at(c.seeds.program) };
1651
+ if (c.closeTo)
1652
+ c.closeTo = sibling(c.closeTo);
1653
+ if (c.ata)
1654
+ c.ata = { owner: sibling(c.ata.owner), mint: sibling(c.ata.mint) };
1655
+ }
1656
+ return all;
1657
+ }
1623
1658
  /** An account parameter (or a group's field) of type `typeNode`. */
1624
1659
  function accountFrom(typeNode, name, node, imports) {
1625
1660
  // Optional accounts: `Mut<Vault> | null` or `Optional<Mut<Vault>>`.
@@ -1651,8 +1686,8 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1651
1686
  }
1652
1687
  // A group parameter's name is taken too: `pool.vault` reads its field, so no other parameter may be `pool`.
1653
1688
  for (const a of accounts)
1654
- if (a.group && [...args, ...accounts].some((o) => o.name === a.group.param))
1655
- reporter.error(a.node, `"${a.group.param}" names both an account group and another parameter`);
1689
+ if (a.group && [...args, ...accounts].some((o) => o.name === a.group.path[0]))
1690
+ reporter.error(a.node, `"${a.group.path[0]}" names both an account group and another parameter`);
1656
1691
  // Constraints refer to other parameters by name: check them now that all are known.
1657
1692
  for (const a of accounts) {
1658
1693
  const c = a.constraints;
@@ -1964,6 +1999,12 @@ function resolveAccountKind(node, reporter, imports, structs) {
1964
1999
  return { kind: "selfProgram" };
1965
2000
  case "AssociatedTokenProgram":
1966
2001
  return { kind: "ataProgram" };
2002
+ case "MemoProgram":
2003
+ return { kind: "memoProgram" };
2004
+ case "StakeProgram":
2005
+ return { kind: "stakeProgram" };
2006
+ case "SlotHashesSysvar":
2007
+ return { kind: "slotHashes" };
1967
2008
  case "TokenMetadataProgram":
1968
2009
  return { kind: "metadataProgram" };
1969
2010
  case "SwitchboardFeed": {
@@ -105,8 +105,12 @@ export declare abstract class EmitterBase {
105
105
  protected withoutBang(node: ts.Expression): ts.PropertyAccessExpression | undefined;
106
106
  /** The account an expression names: a parameter (`vault`) or a field of an account group (`pool.vault`). */
107
107
  protected accountAt(node: ts.Expression): AccountParam | undefined;
108
+ /** `pool.fees.vault` as ["pool", "fees", "vault"] when `pool` is an account group parameter. */
109
+ protected groupPath(node: ts.Expression): string[] | undefined;
108
110
  /** An account group parameter's name. */
109
111
  protected isGroup(name: string): boolean;
112
+ /** `pool` or `pool.fees`: a group (or a group inside one), not an account. */
113
+ protected isGroupValue(node: ts.Expression): boolean;
110
114
  protected accountParam(node: ts.Expression, what: string): AccountParam;
111
115
  protected assertUsable(a: AccountParam, node: ts.Node): void;
112
116
  protected abstract expect(v: Value, want: ValueType | undefined, node: ts.Node): Value;
@@ -132,6 +136,8 @@ export declare abstract class EmitterBase {
132
136
  protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
133
137
  protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
134
138
  protected abstract ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
139
+ protected abstract memoOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
140
+ protected abstract stakeOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
135
141
  protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
136
142
  protected abstract coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
137
143
  protected abstract bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
@@ -360,14 +360,36 @@ export class EmitterBase {
360
360
  accountAt(node) {
361
361
  if (ts.isIdentifier(node))
362
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;
363
+ const path = this.groupPath(node);
364
+ return path && path.length > 1 ? this.accounts.get(path.join("__")) : undefined;
365
+ }
366
+ /** `pool.fees.vault` as ["pool", "fees", "vault"] when `pool` is an account group parameter. */
367
+ groupPath(node) {
368
+ const names = [];
369
+ let e = node;
370
+ while (ts.isPropertyAccessExpression(e)) {
371
+ names.unshift(e.name.text);
372
+ e = e.expression;
373
+ }
374
+ if (!ts.isIdentifier(e) || !this.isGroup(e.text))
375
+ return undefined;
376
+ return [e.text, ...names];
366
377
  }
367
378
  /** An account group parameter's name. */
368
379
  isGroup(name) {
369
380
  for (const a of this.accounts.values())
370
- if (a.group?.param === name)
381
+ if (a.group?.path[0] === name)
382
+ return true;
383
+ return false;
384
+ }
385
+ /** `pool` or `pool.fees`: a group (or a group inside one), not an account. */
386
+ isGroupValue(node) {
387
+ const path = ts.isIdentifier(node) ? (this.isGroup(node.text) ? [node.text] : undefined) : this.groupPath(node);
388
+ if (!path)
389
+ return false;
390
+ const prefix = `${path.join("__")}__`;
391
+ for (const a of this.accounts.values())
392
+ if (a.name.startsWith(prefix))
371
393
  return true;
372
394
  return false;
373
395
  }
@@ -377,8 +399,8 @@ export class EmitterBase {
377
399
  return this.accountParam(node.expression, what);
378
400
  const a = this.accountAt(node);
379
401
  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}.…)`);
402
+ if (this.isGroupValue(node))
403
+ this.fail(node, `${what} must be an account; "${node.getText()}" is a group of accounts: pass one of its fields (${node.getText()}.…)`);
382
404
  if (!ts.isIdentifier(node))
383
405
  this.fail(node, `${what} must be an account parameter`);
384
406
  this.fail(node, `${what} must be an account parameter, "${node.text}" is not one`);
@@ -536,6 +536,8 @@ export class CallEmitter extends ExpressionEmitter {
536
536
  }
537
537
  case "returnData":
538
538
  return this.returnData(node);
539
+ case "instructionData":
540
+ this.fail(node, "bind the data to a local first: const data = instructionData()");
539
541
  case "fixedArray":
540
542
  this.fail(node, "fixedArray<T, N>(fill) is only allowed as a local declaration: const xs = fixedArray<u64, 4>(0n)");
541
543
  case "readonly":
@@ -687,6 +689,10 @@ export class CallEmitter extends ExpressionEmitter {
687
689
  return this.tokenOp(node, target, method);
688
690
  if (target?.kind.kind === "ataProgram")
689
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);
690
696
  if (target?.kind.kind === "metadataProgram")
691
697
  return this.metadataOp(node, target, method);
692
698
  // Each Metaplex CPI in its own C block: its data buffer's stack slot is reused by the next one.
@@ -324,6 +324,8 @@ export class ExpressionEmitter extends StorageEmitter {
324
324
  }
325
325
  if (this.accountAt(node))
326
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()}.…)`);
327
329
  if (ts.isIdentifier(node.expression) || this.accountAt(node.expression)) {
328
330
  const a = this.accountAt(node.expression);
329
331
  if (a) {
@@ -371,6 +373,16 @@ export class ExpressionEmitter extends StorageEmitter {
371
373
  if (field === "tokenProgram")
372
374
  return { c: `&${v}->owner`, type: PUBKEY };
373
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
+ }
374
386
  if (k.kind === "pyth") {
375
387
  // Raw fields of the update; pythPrice() is the checked read.
376
388
  const m = `${v}->data + pm_${a.name}`;
@@ -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")
@@ -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
  }
@@ -902,6 +902,14 @@ export class StatementEmitter extends CpiEmitter {
902
902
  continue;
903
903
  }
904
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
+ }
905
913
  // A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
906
914
  if (fn === "signer") {
907
915
  if (mutable)
@@ -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
  }