@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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,45 @@ 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
+
32
+ ## 0.33.0 — 2026-10-30
33
+
34
+ The rest of what large Anchor programs lean on: account groups (composite accounts), your errors on declarative
35
+ constraints, and structs as CPI return data. Existing programs compile to the same binaries as in 0.32.0.
36
+
37
+ - New: account groups, Anchor's composite accounts. An interface whose fields are accounts is one parameter
38
+ (`p: PoolAccounts`): the body uses `p.pool.reserve` and `p.vault`, constraints inside name the group's own fields,
39
+ the IDL nests the group as Anchor's does, and the client and `typesol/testing` flatten it (`pPool`).
40
+ - New: your errors on declarative constraints, as Anchor's `has_one = owner @ ErrorCode.NotOwner`:
41
+ `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>` and
42
+ `Mut<T, E.X>` (the constraints Anchor names errors for; `constraint(…)` already took one). Nest `HasOne` for an error
43
+ per field.
44
+ - New: structs as CPI return data: `const quote = returnData<Quote>(amm)` after the call. A fixed layout of integers,
45
+ booleans, Pubkeys, unit enums and arrays is read as its bytes; a `@layout borsh` struct (Options, strings, Vecs) is
46
+ Borsh-decoded; anything else fails with 5106.
47
+
9
48
  ## 0.32.0 — 2026-10-30
10
49
 
11
50
  Anchor parity and usability: Raydium CP-Swap's pool creation and what creating accounts by hand needs, several PDAs
package/README.md CHANGED
@@ -204,11 +204,11 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
204
204
 
205
205
  | | |
206
206
  | --- | --- |
207
- | **Accounts** | `Signer`, `Account<T>`, `Mut<T>`, `Init<T>`, `InitIfNeeded<T>` (PDAs or keypair accounts, with Anchor's `space`; mints, token accounts and associated token accounts), `Zeroed<T>` (up to 10 MiB), optional accounts (`A \| null`), token accounts and mints, `SystemAccount`, programs, sysvars |
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 |
207
+ | **Accounts** | `Signer`, `Account<T>`, `Mut<T>`, `Init<T>`, `InitIfNeeded<T>` (PDAs or keypair accounts, with Anchor's `space`; mints, token accounts and associated token accounts), `Zeroed<T>` (up to 10 MiB), optional accounts (`A \| null`), token accounts and mints, `SystemAccount`, programs, sysvars, and account groups (Anchor's composite accounts) |
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",
@@ -295,6 +298,7 @@ export function analyze(entry, files) {
295
298
  const functions = [];
296
299
  const helperNodes = [];
297
300
  const interfaces = [];
301
+ const groups = new Map();
298
302
  const aliases = [];
299
303
  /** Program-wide names (structs, enums, helpers) -> declaring file, for collision errors. */
300
304
  const declared = new Map();
@@ -336,7 +340,11 @@ export function analyze(entry, files) {
336
340
  if (!isExported(stmt))
337
341
  reporter.fail(stmt, "structs must be exported");
338
342
  declare(stmt.name, file);
339
- interfaces.push({ decl: stmt, imports });
343
+ // An interface of accounts is an account group (Anchor's composite `#[derive(Accounts)]` field), not a struct.
344
+ if (isAccountGroup(stmt, imports))
345
+ groups.set(stmt.name.text, { decl: stmt, imports });
346
+ else
347
+ interfaces.push({ decl: stmt, imports });
340
348
  }
341
349
  else if (ts.isTypeAliasDeclaration(stmt)) {
342
350
  if (!isExported(stmt))
@@ -612,7 +620,7 @@ export function analyze(entry, files) {
612
620
  });
613
621
  continue;
614
622
  }
615
- const h = reporter.guard(() => analyzeHelper(fn.node, fn.name, fn.display, reporter, scopeFor(fn.imports), structs));
623
+ const h = reporter.guard(() => analyzeHelper(fn.node, fn.name, fn.display, reporter, scopeFor(fn.imports), structs, undefined, groups));
616
624
  if (h)
617
625
  helpers.set(h.name, h);
618
626
  }
@@ -633,7 +641,7 @@ export function analyze(entry, files) {
633
641
  bound.set(n, t);
634
642
  });
635
643
  const display = `${g.display}<${[...typeArgs.map((t) => (t.kind === "struct" ? t.name : typeName(t))), ...fnArgs].join(", ")}>`;
636
- const h = analyzeHelper(g.node, key, display, reporter, { ...scopeFor(g.imports), typeArgs: bound, structArgs: boundStructs }, structs, new Set(g.fnParams));
644
+ const h = analyzeHelper(g.node, key, display, reporter, { ...scopeFor(g.imports), typeArgs: bound, structArgs: boundStructs }, structs, new Set(g.fnParams), groups);
637
645
  h.typeArgs = bound;
638
646
  h.structArgs = boundStructs;
639
647
  if (g.fnParams.length) {
@@ -649,9 +657,17 @@ export function analyze(entry, files) {
649
657
  const argStructs = new Set();
650
658
  const instructions = [];
651
659
  for (const fn of functions) {
652
- const ix = reporter.guard(() => analyzeInstruction(fn.node, reporter, scopeFor(fn.imports), structs));
660
+ const ix = reporter.guard(() => analyzeInstruction(fn.node, reporter, scopeFor(fn.imports), structs, groups));
653
661
  if (!ix)
654
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
+ }
655
671
  instructions.push(ix);
656
672
  for (const a of ix.args)
657
673
  collectStructs(a.type, structs, dataEnums, argStructs);
@@ -1359,7 +1375,7 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
1359
1375
  reporter.error(s.node.name, `${s.name} is @layout borsh, so it is account data only; ${other.name}.${f.name} cannot hold one`);
1360
1376
  }
1361
1377
  }
1362
- function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new Set()) {
1378
+ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new Set(), groups = new Map()) {
1363
1379
  if (!fn.body)
1364
1380
  reporter.fail(fn, "helper functions need a body");
1365
1381
  if (fn.asteriskToken)
@@ -1405,6 +1421,8 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1405
1421
  wrapped === "Ata" ||
1406
1422
  wrapped === "Signed")
1407
1423
  reporter.fail(p.type, "constraints belong on instruction parameters; helpers take the plain account type");
1424
+ if (ts.isTypeReferenceNode(p.type) && ts.isIdentifier(p.type.typeName) && groups.has(p.type.typeName.text))
1425
+ reporter.fail(p.type, `${p.type.typeName.text} is an account group: helpers take its accounts one by one (h(p.pool, p.vault))`);
1408
1426
  const account = resolveAccountKind(p.type, reporter, scope.imports, structs);
1409
1427
  if (account.kind === "init" || account.kind === "initIfNeeded" || account.kind === "zeroed" || account.kind === "migrate")
1410
1428
  reporter.fail(p.type, "helpers take accounts that exist: create Init/InitIfNeeded/Zeroed accounts in the instruction, then pass them as Mut<T>");
@@ -1467,7 +1485,58 @@ function checkRecursion(sources, decls, checker, reporter) {
1467
1485
  for (const name of byName.keys())
1468
1486
  walk(name, []);
1469
1487
  }
1470
- function analyzeInstruction(fn, reporter, scope, structs) {
1488
+ /** TypeSOL types an account parameter can have (with the constraint wrappers around them). */
1489
+ const ACCOUNT_TYPES = new Set([
1490
+ "Signer",
1491
+ "AccountInfo",
1492
+ "AccountMeta",
1493
+ "Account",
1494
+ "Mut",
1495
+ "Init",
1496
+ "TokenAccount",
1497
+ "Mint",
1498
+ "SystemProgram",
1499
+ "TokenProgram",
1500
+ "Token2022Program",
1501
+ "TokenInterface",
1502
+ "Program",
1503
+ "UncheckedProgram",
1504
+ "Zeroed",
1505
+ "InstructionsSysvar",
1506
+ "InitIfNeeded",
1507
+ "PythPriceUpdate",
1508
+ "AssociatedTokenProgram",
1509
+ "TokenMetadataProgram",
1510
+ "MemoProgram",
1511
+ "StakeProgram",
1512
+ "SlotHashesSysvar",
1513
+ "SwitchboardFeed",
1514
+ "HasOne",
1515
+ "TokenOf",
1516
+ "MintOf",
1517
+ "Seeds",
1518
+ "CloseTo",
1519
+ "Address",
1520
+ "Ata",
1521
+ "Owner",
1522
+ "Executable",
1523
+ "Dup",
1524
+ "Signed",
1525
+ "Migrate",
1526
+ "Optional",
1527
+ "EventAuthority",
1528
+ "MplCoreProgram",
1529
+ "BubblegumProgram",
1530
+ "SelfProgram",
1531
+ "ProgramData",
1532
+ "SystemAccount",
1533
+ ]);
1534
+ const withoutNull = (t) => ts.isUnionTypeNode(t) && t.types.length === 2 ? (t.types.find((x) => !(ts.isLiteralTypeNode(x) && x.literal.kind === ts.SyntaxKind.NullKeyword)) ?? t) : t;
1535
+ /** An interface with an account-typed field: an account group. */
1536
+ function isAccountGroup(decl, imports) {
1537
+ return decl.members.some((m) => ts.isPropertySignature(m) && m.type && ACCOUNT_TYPES.has(typesolName(withoutNull(m.type), imports) ?? ""));
1538
+ }
1539
+ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1471
1540
  const imports = scope.imports;
1472
1541
  if (!fn.name || !fn.body)
1473
1542
  reporter.fail(fn, "instructions need a name and a body");
@@ -1513,33 +1582,112 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1513
1582
  : 0;
1514
1583
  return;
1515
1584
  }
1516
- // Optional accounts: `Mut<Vault> | null` or `Optional<Mut<Vault>>`.
1517
- let typeNode = p.type;
1518
- let optional = false;
1519
- const isNull = (t) => ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword;
1520
- if (ts.isUnionTypeNode(typeNode) && typeNode.types.length === 2 && typeNode.types.some(isNull)) {
1521
- optional = true;
1522
- typeNode = typeNode.types.find((t) => !isNull(t));
1523
- }
1524
- else if (typesolName(typeNode, imports) === "Optional") {
1525
- optional = true;
1526
- typeNode = typeNode.typeArguments?.[0] ?? typeNode;
1585
+ // An account group: its accounts are this instruction's, in their order, named `<param>__<field>`.
1586
+ const bare = withoutNull(p.type);
1587
+ if (bare !== p.type && ts.isTypeReferenceNode(bare) && ts.isIdentifier(bare.typeName) && groups.has(bare.typeName.text))
1588
+ reporter.fail(p.type, "account groups cannot be optional; make the accounts inside it optional (field: A | null)");
1589
+ const group = ts.isTypeReferenceNode(p.type) && ts.isIdentifier(p.type.typeName) ? groups.get(p.type.typeName.text) : undefined;
1590
+ if (group) {
1591
+ if (p.type.typeArguments)
1592
+ reporter.fail(p.type, "account groups take no type arguments");
1593
+ for (const a of expandGroup(group, [p.name.text], new Set())) {
1594
+ a.index = accounts.length;
1595
+ accounts.push(a);
1596
+ }
1597
+ return;
1527
1598
  }
1528
- const constraints = { hasOne: [] };
1529
- const inner = unwrapConstraints(typeNode, reporter, imports, constraints);
1530
- const kind = resolveAccountKind(inner, reporter, imports, structs);
1531
- if (optional &&
1532
- (["init", "initIfNeeded", "zeroed", "migrate", "pyth", "eventAuthority", "selfProgram", "programData"].includes(kind.kind) ||
1533
- ((kind.kind === "token" || kind.kind === "mint") && kind.init)))
1534
- reporter.fail(p, "Init, InitIfNeeded, Zeroed, PythPriceUpdate, EventAuthority, SelfProgram and ProgramData accounts cannot be optional");
1535
- accounts.push({ name: p.name.text, index: accounts.length, kind, node: p, constraints, ...(optional ? { optional } : {}) });
1599
+ const a = accountFrom(p.type, p.name.text, p, imports);
1600
+ a.index = accounts.length;
1601
+ accounts.push(a);
1536
1602
  });
1537
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
+ }
1658
+ /** An account parameter (or a group's field) of type `typeNode`. */
1659
+ function accountFrom(typeNode, name, node, imports) {
1660
+ // Optional accounts: `Mut<Vault> | null` or `Optional<Mut<Vault>>`.
1661
+ let optional = false;
1662
+ const isNull = (t) => ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword;
1663
+ if (ts.isUnionTypeNode(typeNode) && typeNode.types.length === 2 && typeNode.types.some(isNull)) {
1664
+ optional = true;
1665
+ typeNode = typeNode.types.find((t) => !isNull(t));
1666
+ }
1667
+ else if (typesolName(typeNode, imports) === "Optional") {
1668
+ optional = true;
1669
+ typeNode = typeNode.typeArguments?.[0] ?? typeNode;
1670
+ }
1671
+ const constraints = { hasOne: [] };
1672
+ const inner = unwrapConstraints(typeNode, reporter, imports, constraints);
1673
+ const kind = resolveAccountKind(inner, reporter, imports, structs);
1674
+ if (optional &&
1675
+ (["init", "initIfNeeded", "zeroed", "migrate", "pyth", "eventAuthority", "selfProgram", "programData"].includes(kind.kind) ||
1676
+ ((kind.kind === "token" || kind.kind === "mint") && kind.init)))
1677
+ reporter.fail(node, "Init, InitIfNeeded, Zeroed, PythPriceUpdate, EventAuthority, SelfProgram and ProgramData accounts cannot be optional");
1678
+ return { name, index: 0, kind, node, constraints, ...(optional ? { optional } : {}) };
1679
+ }
1538
1680
  checkSnakeDuplicates(args.map((a) => ({ name: a.name, node: a.node })), "arguments", reporter);
1539
1681
  checkSnakeDuplicates(accounts.map((a) => ({ name: a.name, node: a.node })), "accounts", reporter);
1540
- for (const p of [...args, ...accounts])
1541
- if (p.name.includes("__") || p.name.includes("$"))
1542
- reporter.error(p.node, `"${p.name}": "__" and "$" are reserved in names`);
1682
+ for (const p of [...args, ...accounts]) {
1683
+ const own = "group" in p && p.group ? p.group.field : p.name;
1684
+ if (own.includes("__") || own.includes("$"))
1685
+ reporter.error(p.node, `"${own}": "__" and "$" are reserved in names`);
1686
+ }
1687
+ // A group parameter's name is taken too: `pool.vault` reads its field, so no other parameter may be `pool`.
1688
+ for (const a of accounts)
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`);
1543
1691
  // Constraints refer to other parameters by name: check them now that all are known.
1544
1692
  for (const a of accounts) {
1545
1693
  const c = a.constraints;
@@ -1570,7 +1718,8 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1570
1718
  reporter.fail(a.node, "MintOf<…> applies to a Mint");
1571
1719
  continue;
1572
1720
  }
1573
- if (!accounts.some((o) => o.name === f))
1721
+ const target = c.hasOneParams?.get(f) ?? f;
1722
+ if (!accounts.some((o) => o.name === target))
1574
1723
  reporter.fail(a.node, `HasOne<…, "${f}">: add an account parameter named "${f}"`);
1575
1724
  if (a.kind.kind === "token") {
1576
1725
  if (f !== "mint" && f !== "owner")
@@ -1587,8 +1736,6 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1587
1736
  const field = struct.fields.find((x) => x.name === f);
1588
1737
  if (!field || field.type.kind !== "pubkey" || field.type.hash)
1589
1738
  reporter.fail(a.node, `HasOne<…, "${f}">: ${struct.name} needs a Pubkey field "${f}"`);
1590
- if (!accounts.some((o) => o.name === f))
1591
- reporter.fail(a.node, `HasOne<…, "${f}">: add an account parameter named "${f}"`);
1592
1739
  }
1593
1740
  if (c.seeds?.bump?.startsWith("@")) {
1594
1741
  // "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`).
@@ -1631,7 +1778,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1631
1778
  for (const a of accounts) {
1632
1779
  const c = a.constraints;
1633
1780
  const refs = [
1634
- ...c.hasOne.map((e) => e.split("=").at(-1)),
1781
+ ...c.hasOne.map((e) => (e.includes("=") ? e.split("=").at(-1) : (c.hasOneParams?.get(e) ?? e))),
1635
1782
  ...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).split(".")[0]),
1636
1783
  ...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
1637
1784
  ...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
@@ -1704,9 +1851,24 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1704
1851
  /** Peel HasOne / Seeds / CloseTo wrappers off a parameter type, recording what they ask for. */
1705
1852
  function unwrapConstraints(node, reporter, imports, out) {
1706
1853
  const name = typesolName(node, imports);
1854
+ const args = node.typeArguments ?? [];
1855
+ // One of the program's errors in a type position: `ErrorCode.NotOwner` (Anchor's `@ ErrorCode.NotOwner`).
1856
+ const customError = (key, t) => {
1857
+ if (!t || t.kind === ts.SyntaxKind.NeverKeyword)
1858
+ return;
1859
+ const q = ts.isTypeReferenceNode(t) && ts.isQualifiedName(t.typeName) && ts.isIdentifier(t.typeName.left) ? t.typeName : undefined;
1860
+ if (!q || t.typeArguments)
1861
+ reporter.fail(t, "the error is a member of one of your error enums: ErrorCode.NotOwner");
1862
+ (out.errors ??= new Map()).set(key, { enumName: q.left.text, member: q.right.text, node: t });
1863
+ };
1864
+ // Mut<T, ErrorCode.X>: Anchor's `mut @ ErrorCode.X`.
1865
+ if (name === "Mut") {
1866
+ if (args.length === 2)
1867
+ customError("mut", args[1]);
1868
+ return node;
1869
+ }
1707
1870
  if (!["HasOne", "TokenOf", "MintOf", "Seeds", "CloseTo", "Address", "Ata", "Owner", "Executable", "Dup", "Signed"].includes(name ?? ""))
1708
1871
  return node;
1709
- const args = node.typeArguments ?? [];
1710
1872
  const lit = (t) => {
1711
1873
  if (!t)
1712
1874
  return [];
@@ -1716,8 +1878,12 @@ function unwrapConstraints(node, reporter, imports, out) {
1716
1878
  return t.types.flatMap(lit);
1717
1879
  reporter.fail(t, "expected a string literal type");
1718
1880
  };
1719
- if (name === "HasOne")
1720
- out.hasOne.push(...lit(args[1]));
1881
+ if (name === "HasOne") {
1882
+ const fields = lit(args[1]);
1883
+ out.hasOne.push(...fields);
1884
+ for (const f of fields)
1885
+ customError(`hasOne:${f}`, args[2]);
1886
+ }
1721
1887
  // Anchor's `token::mint = m, token::authority = a` / `mint::authority = a, mint::freeze_authority = f` naming the
1722
1888
  // parameters: recorded as "field=param" (`never` leaves one out).
1723
1889
  if (name === "TokenOf" || name === "MintOf") {
@@ -1743,19 +1909,23 @@ function unwrapConstraints(node, reporter, imports, out) {
1743
1909
  if (!bytes)
1744
1910
  reporter.fail(args[1] ?? node, `Owner<…, "base58">: "${text}" is not a valid base58 Solana address`);
1745
1911
  out.owner = { base58: text, bytes: [...bytes] };
1912
+ customError("owner", args[2]);
1746
1913
  }
1747
1914
  if (name === "Executable")
1748
1915
  out.executable = true;
1749
1916
  if (name === "Dup")
1750
1917
  out.dup = true;
1751
- if (name === "Signed")
1918
+ if (name === "Signed") {
1752
1919
  out.signed = true;
1920
+ customError("signer", args[1]);
1921
+ }
1753
1922
  if (name === "Address") {
1754
1923
  const text = lit(args[1])[0];
1755
1924
  const bytes = text === undefined ? undefined : decodeAddress(text);
1756
1925
  if (!bytes)
1757
1926
  reporter.fail(args[1] ?? node, `Address<…, "base58">: "${text}" is not a valid base58 Solana address`);
1758
1927
  out.address = { base58: text, bytes: [...bytes] };
1928
+ customError("address", args[2]);
1759
1929
  }
1760
1930
  if (name === "Ata") {
1761
1931
  const [owner] = lit(args[1]);
@@ -1829,6 +1999,12 @@ function resolveAccountKind(node, reporter, imports, structs) {
1829
1999
  return { kind: "selfProgram" };
1830
2000
  case "AssociatedTokenProgram":
1831
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" };
1832
2008
  case "TokenMetadataProgram":
1833
2009
  return { kind: "metadataProgram" };
1834
2010
  case "SwitchboardFeed": {
@@ -1912,7 +2088,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
1912
2088
  return { kind: "zeroed", struct: s };
1913
2089
  }
1914
2090
  case "Mut": {
1915
- const t = inner();
2091
+ // Mut<T, ErrorCode.X>: the error is recorded with the constraints.
2092
+ const t = ref.typeArguments?.length === 2 ? ref.typeArguments[0] : inner();
1916
2093
  const s = structOf(t);
1917
2094
  if (s)
1918
2095
  return { kind: "account", struct: s, mut: true };
@@ -31,8 +31,12 @@ export class AliasEmitter extends EmitterBase {
31
31
  return l.paths ?? (l.type.kind === "array" ? [`@${l.c}`] : undefined);
32
32
  return this.accounts.has(node.text) ? [node.text] : undefined;
33
33
  }
34
- if (ts.isPropertyAccessExpression(node))
34
+ if (ts.isPropertyAccessExpression(node)) {
35
+ const field = this.accountAt(node);
36
+ if (field && !ts.isIdentifier(node))
37
+ return [field.name];
35
38
  return this.pathsOf(node.expression)?.map((p) => `${p}.${node.name.text}`);
39
+ }
36
40
  if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "get")
37
41
  return this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`);
38
42
  if (ts.isConditionalExpression(node)) {
@@ -103,6 +103,14 @@ export declare abstract class EmitterBase {
103
103
  * failing with 5115 otherwise). Returns undefined for anything else.
104
104
  */
105
105
  protected withoutBang(node: ts.Expression): ts.PropertyAccessExpression | undefined;
106
+ /** The account an expression names: a parameter (`vault`) or a field of an account group (`pool.vault`). */
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;
110
+ /** An account group parameter's name. */
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;
106
114
  protected accountParam(node: ts.Expression, what: string): AccountParam;
107
115
  protected assertUsable(a: AccountParam, node: ts.Node): void;
108
116
  protected abstract expect(v: Value, want: ValueType | undefined, node: ts.Node): Value;
@@ -128,6 +136,8 @@ export declare abstract class EmitterBase {
128
136
  protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
129
137
  protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
130
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;
131
141
  protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
132
142
  protected abstract coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
133
143
  protected abstract bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
@@ -349,22 +349,62 @@ 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
+ 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];
377
+ }
378
+ /** An account group parameter's name. */
379
+ isGroup(name) {
380
+ for (const a of this.accounts.values())
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))
393
+ return true;
394
+ return false;
395
+ }
359
396
  accountParam(node, what) {
360
397
  // `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)
398
+ if (ts.isNonNullExpression(node) && this.accountAt(node.expression)?.optional)
362
399
  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)
400
+ const a = this.accountAt(node);
401
+ if (!a) {
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()}.…)`);
404
+ if (!ts.isIdentifier(node))
405
+ this.fail(node, `${what} must be an account parameter`);
367
406
  this.fail(node, `${what} must be an account parameter, "${node.text}" is not one`);
407
+ }
368
408
  this.assertUsable(a, node);
369
409
  return a;
370
410
  }
@@ -1,5 +1,5 @@
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 {
@@ -79,5 +79,7 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
79
79
  count: number | string;
80
80
  };
81
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;
82
84
  protected returnData(node: ts.CallExpression): Value;
83
85
  }