@typesol/cli 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,22 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.33.0 — 2026-10-30
10
+
11
+ The rest of what large Anchor programs lean on: account groups (composite accounts), your errors on declarative
12
+ constraints, and structs as CPI return data. Existing programs compile to the same binaries as in 0.32.0.
13
+
14
+ - New: account groups, Anchor's composite accounts. An interface whose fields are accounts is one parameter
15
+ (`p: PoolAccounts`): the body uses `p.pool.reserve` and `p.vault`, constraints inside name the group's own fields,
16
+ the IDL nests the group as Anchor's does, and the client and `typesol/testing` flatten it (`pPool`).
17
+ - New: your errors on declarative constraints, as Anchor's `has_one = owner @ ErrorCode.NotOwner`:
18
+ `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>` and
19
+ `Mut<T, E.X>` (the constraints Anchor names errors for; `constraint(…)` already took one). Nest `HasOne` for an error
20
+ per field.
21
+ - New: structs as CPI return data: `const quote = returnData<Quote>(amm)` after the call. A fixed layout of integers,
22
+ booleans, Pubkeys, unit enums and arrays is read as its bytes; a `@layout borsh` struct (Options, strings, Vecs) is
23
+ Borsh-decoded; anything else fails with 5106.
24
+
9
25
  ## 0.32.0 — 2026-10-30
10
26
 
11
27
  Anchor parity and usability: Raydium CP-Swap's pool creation and what creating accounts by hand needs, several PDAs
package/README.md CHANGED
@@ -204,8 +204,8 @@ 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
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`) |
@@ -295,6 +295,7 @@ export function analyze(entry, files) {
295
295
  const functions = [];
296
296
  const helperNodes = [];
297
297
  const interfaces = [];
298
+ const groups = new Map();
298
299
  const aliases = [];
299
300
  /** Program-wide names (structs, enums, helpers) -> declaring file, for collision errors. */
300
301
  const declared = new Map();
@@ -336,7 +337,11 @@ export function analyze(entry, files) {
336
337
  if (!isExported(stmt))
337
338
  reporter.fail(stmt, "structs must be exported");
338
339
  declare(stmt.name, file);
339
- interfaces.push({ decl: stmt, imports });
340
+ // An interface of accounts is an account group (Anchor's composite `#[derive(Accounts)]` field), not a struct.
341
+ if (isAccountGroup(stmt, imports))
342
+ groups.set(stmt.name.text, { decl: stmt, imports });
343
+ else
344
+ interfaces.push({ decl: stmt, imports });
340
345
  }
341
346
  else if (ts.isTypeAliasDeclaration(stmt)) {
342
347
  if (!isExported(stmt))
@@ -612,7 +617,7 @@ export function analyze(entry, files) {
612
617
  });
613
618
  continue;
614
619
  }
615
- const h = reporter.guard(() => analyzeHelper(fn.node, fn.name, fn.display, reporter, scopeFor(fn.imports), structs));
620
+ const h = reporter.guard(() => analyzeHelper(fn.node, fn.name, fn.display, reporter, scopeFor(fn.imports), structs, undefined, groups));
616
621
  if (h)
617
622
  helpers.set(h.name, h);
618
623
  }
@@ -633,7 +638,7 @@ export function analyze(entry, files) {
633
638
  bound.set(n, t);
634
639
  });
635
640
  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));
641
+ const h = analyzeHelper(g.node, key, display, reporter, { ...scopeFor(g.imports), typeArgs: bound, structArgs: boundStructs }, structs, new Set(g.fnParams), groups);
637
642
  h.typeArgs = bound;
638
643
  h.structArgs = boundStructs;
639
644
  if (g.fnParams.length) {
@@ -649,7 +654,7 @@ export function analyze(entry, files) {
649
654
  const argStructs = new Set();
650
655
  const instructions = [];
651
656
  for (const fn of functions) {
652
- const ix = reporter.guard(() => analyzeInstruction(fn.node, reporter, scopeFor(fn.imports), structs));
657
+ const ix = reporter.guard(() => analyzeInstruction(fn.node, reporter, scopeFor(fn.imports), structs, groups));
653
658
  if (!ix)
654
659
  continue;
655
660
  instructions.push(ix);
@@ -1359,7 +1364,7 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
1359
1364
  reporter.error(s.node.name, `${s.name} is @layout borsh, so it is account data only; ${other.name}.${f.name} cannot hold one`);
1360
1365
  }
1361
1366
  }
1362
- function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new Set()) {
1367
+ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new Set(), groups = new Map()) {
1363
1368
  if (!fn.body)
1364
1369
  reporter.fail(fn, "helper functions need a body");
1365
1370
  if (fn.asteriskToken)
@@ -1405,6 +1410,8 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1405
1410
  wrapped === "Ata" ||
1406
1411
  wrapped === "Signed")
1407
1412
  reporter.fail(p.type, "constraints belong on instruction parameters; helpers take the plain account type");
1413
+ if (ts.isTypeReferenceNode(p.type) && ts.isIdentifier(p.type.typeName) && groups.has(p.type.typeName.text))
1414
+ 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
1415
  const account = resolveAccountKind(p.type, reporter, scope.imports, structs);
1409
1416
  if (account.kind === "init" || account.kind === "initIfNeeded" || account.kind === "zeroed" || account.kind === "migrate")
1410
1417
  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 +1474,55 @@ function checkRecursion(sources, decls, checker, reporter) {
1467
1474
  for (const name of byName.keys())
1468
1475
  walk(name, []);
1469
1476
  }
1470
- function analyzeInstruction(fn, reporter, scope, structs) {
1477
+ /** TypeSOL types an account parameter can have (with the constraint wrappers around them). */
1478
+ const ACCOUNT_TYPES = new Set([
1479
+ "Signer",
1480
+ "AccountInfo",
1481
+ "AccountMeta",
1482
+ "Account",
1483
+ "Mut",
1484
+ "Init",
1485
+ "TokenAccount",
1486
+ "Mint",
1487
+ "SystemProgram",
1488
+ "TokenProgram",
1489
+ "Token2022Program",
1490
+ "TokenInterface",
1491
+ "Program",
1492
+ "UncheckedProgram",
1493
+ "Zeroed",
1494
+ "InstructionsSysvar",
1495
+ "InitIfNeeded",
1496
+ "PythPriceUpdate",
1497
+ "AssociatedTokenProgram",
1498
+ "TokenMetadataProgram",
1499
+ "SwitchboardFeed",
1500
+ "HasOne",
1501
+ "TokenOf",
1502
+ "MintOf",
1503
+ "Seeds",
1504
+ "CloseTo",
1505
+ "Address",
1506
+ "Ata",
1507
+ "Owner",
1508
+ "Executable",
1509
+ "Dup",
1510
+ "Signed",
1511
+ "Migrate",
1512
+ "Optional",
1513
+ "EventAuthority",
1514
+ "MplCoreProgram",
1515
+ "BubblegumProgram",
1516
+ "SelfProgram",
1517
+ "ProgramData",
1518
+ "SystemAccount",
1519
+ ]);
1520
+ 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;
1521
+ /** An interface with an account-typed field: an account group. */
1522
+ function isAccountGroup(decl, imports) {
1523
+ return decl.members.some((m) => ts.isPropertySignature(m) && m.type && ACCOUNT_TYPES.has(typesolName(withoutNull(m.type), imports) ?? ""));
1524
+ }
1525
+ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1471
1526
  const imports = scope.imports;
1472
1527
  if (!fn.name || !fn.body)
1473
1528
  reporter.fail(fn, "instructions need a name and a body");
@@ -1513,33 +1568,91 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1513
1568
  : 0;
1514
1569
  return;
1515
1570
  }
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;
1571
+ // An account group: its accounts are this instruction's, in their order, named `<param>__<field>`.
1572
+ const bare = withoutNull(p.type);
1573
+ if (bare !== p.type && ts.isTypeReferenceNode(bare) && ts.isIdentifier(bare.typeName) && groups.has(bare.typeName.text))
1574
+ reporter.fail(p.type, "account groups cannot be optional; make the accounts inside it optional (field: A | null)");
1575
+ const group = ts.isTypeReferenceNode(p.type) && ts.isIdentifier(p.type.typeName) ? groups.get(p.type.typeName.text) : undefined;
1576
+ if (group) {
1577
+ if (p.type.typeArguments)
1578
+ 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) };
1613
+ a.index = accounts.length;
1614
+ accounts.push(a);
1615
+ }
1616
+ return;
1527
1617
  }
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 } : {}) });
1618
+ const a = accountFrom(p.type, p.name.text, p, imports);
1619
+ a.index = accounts.length;
1620
+ accounts.push(a);
1536
1621
  });
1537
1622
  }
1623
+ /** An account parameter (or a group's field) of type `typeNode`. */
1624
+ function accountFrom(typeNode, name, node, imports) {
1625
+ // Optional accounts: `Mut<Vault> | null` or `Optional<Mut<Vault>>`.
1626
+ let optional = false;
1627
+ const isNull = (t) => ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword;
1628
+ if (ts.isUnionTypeNode(typeNode) && typeNode.types.length === 2 && typeNode.types.some(isNull)) {
1629
+ optional = true;
1630
+ typeNode = typeNode.types.find((t) => !isNull(t));
1631
+ }
1632
+ else if (typesolName(typeNode, imports) === "Optional") {
1633
+ optional = true;
1634
+ typeNode = typeNode.typeArguments?.[0] ?? typeNode;
1635
+ }
1636
+ const constraints = { hasOne: [] };
1637
+ const inner = unwrapConstraints(typeNode, reporter, imports, constraints);
1638
+ const kind = resolveAccountKind(inner, reporter, imports, structs);
1639
+ if (optional &&
1640
+ (["init", "initIfNeeded", "zeroed", "migrate", "pyth", "eventAuthority", "selfProgram", "programData"].includes(kind.kind) ||
1641
+ ((kind.kind === "token" || kind.kind === "mint") && kind.init)))
1642
+ reporter.fail(node, "Init, InitIfNeeded, Zeroed, PythPriceUpdate, EventAuthority, SelfProgram and ProgramData accounts cannot be optional");
1643
+ return { name, index: 0, kind, node, constraints, ...(optional ? { optional } : {}) };
1644
+ }
1538
1645
  checkSnakeDuplicates(args.map((a) => ({ name: a.name, node: a.node })), "arguments", reporter);
1539
1646
  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`);
1647
+ for (const p of [...args, ...accounts]) {
1648
+ const own = "group" in p && p.group ? p.group.field : p.name;
1649
+ if (own.includes("__") || own.includes("$"))
1650
+ reporter.error(p.node, `"${own}": "__" and "$" are reserved in names`);
1651
+ }
1652
+ // A group parameter's name is taken too: `pool.vault` reads its field, so no other parameter may be `pool`.
1653
+ 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`);
1543
1656
  // Constraints refer to other parameters by name: check them now that all are known.
1544
1657
  for (const a of accounts) {
1545
1658
  const c = a.constraints;
@@ -1570,7 +1683,8 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1570
1683
  reporter.fail(a.node, "MintOf<…> applies to a Mint");
1571
1684
  continue;
1572
1685
  }
1573
- if (!accounts.some((o) => o.name === f))
1686
+ const target = c.hasOneParams?.get(f) ?? f;
1687
+ if (!accounts.some((o) => o.name === target))
1574
1688
  reporter.fail(a.node, `HasOne<…, "${f}">: add an account parameter named "${f}"`);
1575
1689
  if (a.kind.kind === "token") {
1576
1690
  if (f !== "mint" && f !== "owner")
@@ -1587,8 +1701,6 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1587
1701
  const field = struct.fields.find((x) => x.name === f);
1588
1702
  if (!field || field.type.kind !== "pubkey" || field.type.hash)
1589
1703
  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
1704
  }
1593
1705
  if (c.seeds?.bump?.startsWith("@")) {
1594
1706
  // "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`).
@@ -1631,7 +1743,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1631
1743
  for (const a of accounts) {
1632
1744
  const c = a.constraints;
1633
1745
  const refs = [
1634
- ...c.hasOne.map((e) => e.split("=").at(-1)),
1746
+ ...c.hasOne.map((e) => (e.includes("=") ? e.split("=").at(-1) : (c.hasOneParams?.get(e) ?? e))),
1635
1747
  ...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).split(".")[0]),
1636
1748
  ...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
1637
1749
  ...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
@@ -1704,9 +1816,24 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1704
1816
  /** Peel HasOne / Seeds / CloseTo wrappers off a parameter type, recording what they ask for. */
1705
1817
  function unwrapConstraints(node, reporter, imports, out) {
1706
1818
  const name = typesolName(node, imports);
1819
+ const args = node.typeArguments ?? [];
1820
+ // One of the program's errors in a type position: `ErrorCode.NotOwner` (Anchor's `@ ErrorCode.NotOwner`).
1821
+ const customError = (key, t) => {
1822
+ if (!t || t.kind === ts.SyntaxKind.NeverKeyword)
1823
+ return;
1824
+ const q = ts.isTypeReferenceNode(t) && ts.isQualifiedName(t.typeName) && ts.isIdentifier(t.typeName.left) ? t.typeName : undefined;
1825
+ if (!q || t.typeArguments)
1826
+ reporter.fail(t, "the error is a member of one of your error enums: ErrorCode.NotOwner");
1827
+ (out.errors ??= new Map()).set(key, { enumName: q.left.text, member: q.right.text, node: t });
1828
+ };
1829
+ // Mut<T, ErrorCode.X>: Anchor's `mut @ ErrorCode.X`.
1830
+ if (name === "Mut") {
1831
+ if (args.length === 2)
1832
+ customError("mut", args[1]);
1833
+ return node;
1834
+ }
1707
1835
  if (!["HasOne", "TokenOf", "MintOf", "Seeds", "CloseTo", "Address", "Ata", "Owner", "Executable", "Dup", "Signed"].includes(name ?? ""))
1708
1836
  return node;
1709
- const args = node.typeArguments ?? [];
1710
1837
  const lit = (t) => {
1711
1838
  if (!t)
1712
1839
  return [];
@@ -1716,8 +1843,12 @@ function unwrapConstraints(node, reporter, imports, out) {
1716
1843
  return t.types.flatMap(lit);
1717
1844
  reporter.fail(t, "expected a string literal type");
1718
1845
  };
1719
- if (name === "HasOne")
1720
- out.hasOne.push(...lit(args[1]));
1846
+ if (name === "HasOne") {
1847
+ const fields = lit(args[1]);
1848
+ out.hasOne.push(...fields);
1849
+ for (const f of fields)
1850
+ customError(`hasOne:${f}`, args[2]);
1851
+ }
1721
1852
  // Anchor's `token::mint = m, token::authority = a` / `mint::authority = a, mint::freeze_authority = f` naming the
1722
1853
  // parameters: recorded as "field=param" (`never` leaves one out).
1723
1854
  if (name === "TokenOf" || name === "MintOf") {
@@ -1743,19 +1874,23 @@ function unwrapConstraints(node, reporter, imports, out) {
1743
1874
  if (!bytes)
1744
1875
  reporter.fail(args[1] ?? node, `Owner<…, "base58">: "${text}" is not a valid base58 Solana address`);
1745
1876
  out.owner = { base58: text, bytes: [...bytes] };
1877
+ customError("owner", args[2]);
1746
1878
  }
1747
1879
  if (name === "Executable")
1748
1880
  out.executable = true;
1749
1881
  if (name === "Dup")
1750
1882
  out.dup = true;
1751
- if (name === "Signed")
1883
+ if (name === "Signed") {
1752
1884
  out.signed = true;
1885
+ customError("signer", args[1]);
1886
+ }
1753
1887
  if (name === "Address") {
1754
1888
  const text = lit(args[1])[0];
1755
1889
  const bytes = text === undefined ? undefined : decodeAddress(text);
1756
1890
  if (!bytes)
1757
1891
  reporter.fail(args[1] ?? node, `Address<…, "base58">: "${text}" is not a valid base58 Solana address`);
1758
1892
  out.address = { base58: text, bytes: [...bytes] };
1893
+ customError("address", args[2]);
1759
1894
  }
1760
1895
  if (name === "Ata") {
1761
1896
  const [owner] = lit(args[1]);
@@ -1912,7 +2047,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
1912
2047
  return { kind: "zeroed", struct: s };
1913
2048
  }
1914
2049
  case "Mut": {
1915
- const t = inner();
2050
+ // Mut<T, ErrorCode.X>: the error is recorded with the constraints.
2051
+ const t = ref.typeArguments?.length === 2 ? ref.typeArguments[0] : inner();
1916
2052
  const s = structOf(t);
1917
2053
  if (s)
1918
2054
  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,10 @@ 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
+ /** An account group parameter's name. */
109
+ protected isGroup(name: string): boolean;
106
110
  protected accountParam(node: ts.Expression, what: string): AccountParam;
107
111
  protected assertUsable(a: AccountParam, node: ts.Node): void;
108
112
  protected abstract expect(v: Value, want: ValueType | undefined, node: ts.Node): Value;
@@ -349,22 +349,40 @@ export class EmitterBase {
349
349
  if (!ts.isPropertyAccessExpression(node) || !ts.isNonNullExpression(node.expression))
350
350
  return undefined;
351
351
  const inner = node.expression.expression;
352
- if (!ts.isIdentifier(inner) || !this.accounts.get(inner.text)?.optional)
352
+ if (!this.accountAt(inner)?.optional)
353
353
  return undefined;
354
354
  const plain = ts.factory.createPropertyAccessExpression(inner, node.name);
355
355
  ts.setTextRange(plain, node);
356
356
  plain.parent = node.parent;
357
357
  return plain;
358
358
  }
359
+ /** The account an expression names: a parameter (`vault`) or a field of an account group (`pool.vault`). */
360
+ accountAt(node) {
361
+ if (ts.isIdentifier(node))
362
+ return this.accounts.get(node.text);
363
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && this.isGroup(node.expression.text))
364
+ return this.accounts.get(`${node.expression.text}__${node.name.text}`);
365
+ return undefined;
366
+ }
367
+ /** An account group parameter's name. */
368
+ isGroup(name) {
369
+ for (const a of this.accounts.values())
370
+ if (a.group?.param === name)
371
+ return true;
372
+ return false;
373
+ }
359
374
  accountParam(node, what) {
360
375
  // `acct!` on an optional account: the account (its use checks it was passed).
361
- if (ts.isNonNullExpression(node) && ts.isIdentifier(node.expression) && this.accounts.get(node.expression.text)?.optional)
376
+ if (ts.isNonNullExpression(node) && this.accountAt(node.expression)?.optional)
362
377
  return this.accountParam(node.expression, what);
363
- if (!ts.isIdentifier(node))
364
- this.fail(node, `${what} must be an account parameter`);
365
- const a = this.accounts.get(node.text);
366
- if (!a)
378
+ const a = this.accountAt(node);
379
+ if (!a) {
380
+ if (ts.isIdentifier(node) && this.isGroup(node.text))
381
+ this.fail(node, `${what} must be an account; "${node.text}" is a group of accounts: pass one of its fields (${node.text}.…)`);
382
+ if (!ts.isIdentifier(node))
383
+ this.fail(node, `${what} must be an account parameter`);
367
384
  this.fail(node, `${what} must be an account parameter, "${node.text}" is not one`);
385
+ }
368
386
  this.assertUsable(a, node);
369
387
  return a;
370
388
  }
@@ -1,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
  }
@@ -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";
@@ -661,8 +662,8 @@ export class CallEmitter extends ExpressionEmitter {
661
662
  const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
662
663
  return { c: `ts_key_eq(${this.settle(left, mark).c}, ${right.c})`, type: BOOL };
663
664
  }
664
- if (ts.isIdentifier(callee.expression)) {
665
- const target = this.accounts.get(callee.expression.text);
665
+ if (this.accountAt(callee.expression)) {
666
+ const target = this.accountAt(callee.expression);
666
667
  // Program accounts used through their methods (systemProgram.transfer, tokenProgram.*…) may be optional.
667
668
  if (target?.optional)
668
669
  this.assertUsable(target, callee.expression);
@@ -720,10 +721,8 @@ export class CallEmitter extends ExpressionEmitter {
720
721
  const hint = hints[text];
721
722
  if (hint)
722
723
  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
- }
724
+ if (ts.isPropertyAccessExpression(callee) && this.accountAt(callee.expression))
725
+ return `unsupported call: the account ${callee.expression.getText()} has no method ${callee.name.text}`;
727
726
  return `unsupported call: ${text.length > 60 ? `${text.slice(0, 57)}…` : text}`;
728
727
  }
729
728
  vecMethod(node, method, v) {
@@ -1023,7 +1022,7 @@ export class CallEmitter extends ExpressionEmitter {
1023
1022
  /** C pointer (`TsAccount *`) for an expression naming a remaining account, or undefined. */
1024
1023
  /** Whether `node` is an InstructionsSysvar parameter. */
1025
1024
  instructionsParam(node) {
1026
- const a = ts.isIdentifier(node) ? this.accounts.get(node.text) : undefined;
1025
+ const a = this.accountAt(node);
1027
1026
  return a?.kind.kind === "instructionsSysvar" ? a : undefined;
1028
1027
  }
1029
1028
  /** Whether `node` is a TransactionInstruction: a local holding one, or `ixs.get(i)`. */
@@ -1527,7 +1526,20 @@ export class CallEmitter extends ExpressionEmitter {
1527
1526
  }
1528
1527
  this.fail(node, "the error must be a member of an exported error enum or a string literal");
1529
1528
  }
1529
+ /** The struct of `returnData<Quote>(…)`, when T is one; refused when its bytes are not its Borsh form. */
1530
+ returnedStruct(node) {
1531
+ const targ = node.typeArguments?.[0];
1532
+ const name = targ && structNameOf(targ, this.scope);
1533
+ const s = name ? this.model.structs.get(name) : undefined;
1534
+ if (!s)
1535
+ return undefined;
1536
+ if (s.layout !== "borsh" && !borshIdentical({ kind: "struct", name: s.name }, this.model))
1537
+ this.fail(targ, `${s.name} holds Options or FixedStrings, whose fixed layout is not Borsh: declare it /** @layout borsh */ to read it as return data`);
1538
+ return s;
1539
+ }
1530
1540
  returnData(node) {
1541
+ if (this.returnedStruct(node))
1542
+ this.fail(node, "bind a returned struct to a local: const quote = returnData<Quote>(program)");
1531
1543
  const targ = node.typeArguments?.[0];
1532
1544
  const t = targ && resolveScalarType(targ, this.scope);
1533
1545
  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,10 @@ export class ExpressionEmitter extends StorageEmitter {
320
322
  }
321
323
  this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner and isWritable, not ${field}`);
322
324
  }
323
- if (ts.isIdentifier(node.expression)) {
324
- const a = this.accounts.get(node.expression.text);
325
+ if (this.accountAt(node))
326
+ this.fail(node, `"${node.getText()}" is an account; use ${node.getText()}.key for its address`);
327
+ if (ts.isIdentifier(node.expression) || this.accountAt(node.expression)) {
328
+ const a = this.accountAt(node.expression);
325
329
  if (a) {
326
330
  const v = `a_${a.name}`;
327
331
  // The address is known before an Init account is created (Anchor seeds use `mint.key()` that way).
@@ -421,6 +425,8 @@ export class ExpressionEmitter extends StorageEmitter {
421
425
  return this.readStorage(r, node);
422
426
  this.fail(node.name, `"${field}" is not available on ${a.name}`);
423
427
  }
428
+ if (!ts.isIdentifier(node.expression))
429
+ this.fail(node, "unreachable: an account group's field");
424
430
  if (this.model.errorEnums.has(node.expression.text))
425
431
  this.fail(node, "error enum members can only be used as the second argument of require()");
426
432
  if (this.exportName(node.expression) === "AuthorityType") {
@@ -748,7 +754,7 @@ export class ExpressionEmitter extends StorageEmitter {
748
754
  const isNullNode = (n) => n.kind === ts.SyntaxKind.NullKeyword;
749
755
  if (isEq && (isNullNode(node.left) || isNullNode(node.right))) {
750
756
  const other = isNullNode(node.left) ? node.right : node.left;
751
- const optionalAccount = ts.isIdentifier(other) ? this.accounts.get(other.text) : undefined;
757
+ const optionalAccount = this.accountAt(other);
752
758
  if (optionalAccount?.optional) {
753
759
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
754
760
  return { c: `(a_${optionalAccount.name} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
@@ -1,4 +1,4 @@
1
- import { type Instruction } from "../model.js";
1
+ import { type AccountParam, type Instruction } from "../model.js";
2
2
  import { StatementEmitter } from "./statements.js";
3
3
  /**
4
4
  * One instruction or helper as a C function: the instruction prologue (account checks, constraints and
@@ -14,6 +14,8 @@ export declare class FunctionEmitter extends StatementEmitter {
14
14
  * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
15
15
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
16
16
  */
17
+ /** `TS_FAIL` for a failed check: your error when the parameter's type names one (Anchor's `@ ErrorCode.X`), else Anchor's. */
18
+ protected checkFail(a: AccountParam, key: string, code: string, msg: string): string;
17
19
  /**
18
20
  * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
19
21
  * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
@@ -45,10 +45,10 @@ export class FunctionEmitter extends StatementEmitter {
45
45
  if (k.kind === "zeroed")
46
46
  head.push(` TS_TRY(ts_check_zeroed(${v}, params->program_id, ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : `sizeof(TSS_${k.struct.name})`}));`);
47
47
  if (isWritable(k))
48
- head.push(` TS_TRY(ts_check_mut(${v}));`);
48
+ head.push(a.constraints.errors?.has("mut") ? ` if (!${v}->is_writable) ${this.checkFail(a, "mut", "", "")};` : ` TS_TRY(ts_check_mut(${v}));`);
49
49
  // Signed<…>: Anchor's `signer` constraint (2002), right after `mut`.
50
50
  if (a.constraints.signed)
51
- head.push(` if (!${v}->is_signer) TS_FAIL(TS_ERR_CONSTRAINT_SIGNER, "TypeSOL: ${a.name} must sign");`);
51
+ head.push(` if (!${v}->is_signer) ${this.checkFail(a, "signer", "TS_ERR_CONSTRAINT_SIGNER", `${a.name} must sign`)};`);
52
52
  // A @layout borsh account only has to hold its smallest Borsh form (unpacking checks the rest).
53
53
  if (k.kind === "account")
54
54
  head.push(` TS_TRY(ts_check_program_account(${v}, params->program_id, TS_DISC_${k.struct.name}, ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : emptySizeC(k.struct)}));`);
@@ -125,11 +125,7 @@ export class FunctionEmitter extends StatementEmitter {
125
125
  const reallocated = (() => {
126
126
  let found = false;
127
127
  const visit = (nd) => {
128
- if (ts.isCallExpression(nd) &&
129
- this.exportName(nd.expression) === "realloc" &&
130
- nd.arguments[0] &&
131
- ts.isIdentifier(nd.arguments[0]) &&
132
- nd.arguments[0].text === a.name)
128
+ if (ts.isCallExpression(nd) && this.exportName(nd.expression) === "realloc" && nd.arguments[0] && this.accountAt(nd.arguments[0]) === a)
133
129
  found = true;
134
130
  ts.forEachChild(nd, visit);
135
131
  };
@@ -411,6 +407,16 @@ export class FunctionEmitter extends StatementEmitter {
411
407
  * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
412
408
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
413
409
  */
410
+ /** `TS_FAIL` for a failed check: your error when the parameter's type names one (Anchor's `@ ErrorCode.X`), else Anchor's. */
411
+ checkFail(a, key, code, msg) {
412
+ const ref = a.constraints.errors?.get(key);
413
+ if (!ref)
414
+ return `TS_FAIL(${code}, ${cString(`TypeSOL: ${msg}`)})`;
415
+ const def = this.model.errorEnums.get(ref.enumName)?.get(ref.member);
416
+ if (!def)
417
+ this.reporter.fail(ref.node, `${ref.enumName}.${ref.member} is not one of this program's errors`);
418
+ return `TS_FAIL(${def.code}, ${cString(`Error ${def.code} ${def.name}: ${def.msg} (${this.location(a.node)})`)})`;
419
+ }
414
420
  /**
415
421
  * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
416
422
  * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
@@ -428,7 +434,7 @@ export class FunctionEmitter extends StatementEmitter {
428
434
  const [acct, cond, error] = call.arguments;
429
435
  if (!acct || !cond || call.arguments.length > 3)
430
436
  this.fail(call, "constraint(account, condition, error?) takes an account parameter, a condition and an optional error");
431
- const a = ts.isIdentifier(acct) ? ix.accounts.find((x) => x.name === acct.text) : undefined;
437
+ const a = this.accountAt(acct);
432
438
  if (!a)
433
439
  this.fail(acct, "constraint's first argument is the account parameter the check belongs to (it runs with that account's checks)");
434
440
  const mark = this.lines.length;
@@ -481,21 +487,24 @@ export class FunctionEmitter extends StatementEmitter {
481
487
  const code = f === "mintAuthority" ? "TS_ERR_MINT_AUTHORITY" : "TS_ERR_FREEZE_AUTHORITY";
482
488
  hasOne.push(` if (ts_read_le(a_${a.name}->data + ${at}, 4) != 1 || !ts_key_eq((const SolPubkey *)(a_${a.name}->data + ${at + 4}), &a_${p}->key)) TS_FAIL(${code}, "TypeSOL: ${p} is not the ${f} of ${a.name}");`);
483
489
  }
484
- else
485
- hasOne.push(` if (!ts_key_eq(&d_${a.name}->${f}, &a_${f}->key)) TS_FAIL(TS_ERR_CONSTRAINT, "TypeSOL: ${a.name}.${f} must be the ${f} account");`);
490
+ else {
491
+ // A field of the same account group, or the parameter of the same name.
492
+ const target = c.hasOneParams?.get(f) ?? f;
493
+ hasOne.push(` if (!ts_key_eq(&d_${a.name}->${f}, &a_${target}->key)) ${this.checkFail(a, `hasOne:${f}`, "TS_ERR_CONSTRAINT", `${a.name}.${f} must be the ${f} account`)};`);
494
+ }
486
495
  }
487
496
  if (k === "account")
488
497
  out.push(...hasOne);
489
498
  out.push(...(raw.get(a.name) ?? []));
490
499
  if (c.owner) {
491
500
  out.push(` static const SolPubkey co_${a.name} = {${cBytes(c.owner.bytes)}};`);
492
- out.push(` if (!ts_key_eq(&a_${a.name}->owner, &co_${a.name})) TS_FAIL(TS_ERR_CONSTRAINT_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`);
501
+ out.push(` if (!ts_key_eq(&a_${a.name}->owner, &co_${a.name})) ${this.checkFail(a, "owner", "TS_ERR_CONSTRAINT_OWNER", `${a.name} is not owned by the expected program`)};`);
493
502
  }
494
503
  if (c.executable)
495
504
  out.push(` if (!a_${a.name}->executable) TS_FAIL(TS_ERR_CONSTRAINT_EXECUTABLE, "TypeSOL: ${a.name} must be an executable program");`);
496
505
  if (c.address) {
497
506
  out.push(` static const SolPubkey ca_${a.name} = {${cBytes(c.address.bytes)}};`);
498
- out.push(` if (!ts_key_eq(&a_${a.name}->key, &ca_${a.name})) TS_FAIL(TS_ERR_ADDRESS, "TypeSOL: ${a.name} is not the expected address");`);
507
+ out.push(` if (!ts_key_eq(&a_${a.name}->key, &ca_${a.name})) ${this.checkFail(a, "address", "TS_ERR_ADDRESS", `${a.name} is not the expected address`)};`);
499
508
  }
500
509
  if (k !== "account")
501
510
  out.push(...hasOne);
@@ -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;
@@ -930,6 +931,40 @@ export class StatementEmitter extends CpiEmitter {
930
931
  this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d });
931
932
  continue;
932
933
  }
934
+ // A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
935
+ if (fn === "returnData" && this.returnedStruct(init)) {
936
+ if (mutable)
937
+ this.fail(d, "bind return data with const (its fields can still be updated)");
938
+ const S = this.returnedStruct(init);
939
+ const call = init;
940
+ if (call.arguments.length !== 1)
941
+ this.fail(call, "returnData<T>(program) takes the program that returned it");
942
+ const program = this.accountParam(call.arguments[0], "returnData's program");
943
+ const bad = `TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid ${S.name} return data")`;
944
+ if (S.layout === "borsh") {
945
+ // Borsh of any size: unpacked into the fixed-layout struct, every byte used.
946
+ const raw = `${c}__raw`;
947
+ this.line(`uint8_t *${raw};`);
948
+ this.line(`uint64_t ${raw}_len = 0, ${raw}_used = 0;`);
949
+ this.line(`TS_TRY(ts_return_data_any(a_${program.name}, &${raw}, &${raw}_len));`);
950
+ this.line(`TSS_${S.name} *${c};`);
951
+ this.line(`TS_TRY(ts_alloc(sizeof(TSS_${S.name}), (uint8_t **)&${c}));`);
952
+ this.line(`if (ts_unpack_${S.name}(${raw}, ${raw}_len, ${c}, &${raw}_used) != SUCCESS || ${raw}_used != ${raw}_len) ${bad};`);
953
+ for (const f of S.fields)
954
+ if (f.type.kind === "fstring")
955
+ this.line(`if (!ts_utf8_valid(${c}->${f.name}.bytes, ${c}->${f.name}.len)) ${bad};`);
956
+ }
957
+ else {
958
+ // A fixed layout whose bytes are its Borsh form: copied in, then bools and enums checked.
959
+ this.line(`TSS_${S.name} ${c}__v;`);
960
+ this.line(`TS_TRY(ts_return_data_exact(a_${program.name}, &${c}__v, sizeof(TSS_${S.name})));`);
961
+ for (const l of this.validation(`${c}__v`, { kind: "struct", name: S.name }, "", bad))
962
+ this.line(l.trim());
963
+ this.line(`TSS_${S.name} *${c} = &${c}__v;`);
964
+ }
965
+ this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
966
+ continue;
967
+ }
933
968
  // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
934
969
  const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
935
970
  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))
@@ -22,6 +22,9 @@ function docsOf(node) {
22
22
  }
23
23
  /** `@param name text` of a function parameter. */
24
24
  function paramDocs(param) {
25
+ // A group's field: its own doc comment.
26
+ if (ts.isPropertySignature(param))
27
+ return docsOf(param);
25
28
  const text = ts
26
29
  .getJSDocParameterTags(param)
27
30
  .map((t) => (typeof t.comment === "string" ? t.comment : (ts.getTextOfJSDocComment(t.comment) ?? "")))
@@ -86,9 +89,26 @@ function idlType(t, borshOption = false) {
86
89
  throw new Error(`no IDL type for ${t.kind}`);
87
90
  }
88
91
  }
92
+ /**
93
+ * An account path as the IDL writes it from where it is used: a field of the same group by its own name (Anchor's
94
+ * composite accounts), a field of another group as `<group>_<field>` (how clients flatten groups), else the name.
95
+ */
96
+ function relativePath(path, from) {
97
+ const at = path.indexOf("__");
98
+ if (at < 0)
99
+ return path;
100
+ const group = path.slice(0, at);
101
+ return group === from ? path.slice(at + 2) : `${group}_${path.slice(at + 2)}`;
102
+ }
103
+ function relativeSeeds(seeds, from) {
104
+ if (!Array.isArray(seeds))
105
+ return seeds;
106
+ return seeds.map((sd) => (sd.kind === "account" && sd.path ? { ...sd, path: relativePath(sd.path, from) } : sd));
107
+ }
89
108
  function accountEntry(ix, name, k, programAddress) {
90
109
  const param = ix.accounts.find((a) => a.name === name);
91
- const entry = { name: snakeCase(name), ...(param ? paramDocs(param.node) : {}) };
110
+ const group = param?.group ? snakeCase(param.group.param) : undefined;
111
+ const entry = { name: snakeCase(param?.group ? param.group.field : name), ...(param ? paramDocs(param.node) : {}) };
92
112
  if (isWritable(k))
93
113
  entry.writable = true;
94
114
  if (param?.optional)
@@ -115,13 +135,16 @@ function accountEntry(ix, name, k, programAddress) {
115
135
  entry.address = k.address.base58;
116
136
  // Anchor's direction: the account named by a has_one lists the accounts that hold it (Anchor clients then read
117
137
  // `holder.data[name]` to fill it in). Only struct accounts' HasOne are has_one relations in Anchor's sense.
118
- const relations = ix.accounts.filter((a) => a.kind.kind === "account" && a.constraints.hasOne.includes(name)).map((a) => a.name);
138
+ const holds = (a) => a.constraints.hasOne.some((f) => !f.includes("=") && (a.constraints.hasOneParams?.get(f) ?? f) === name);
139
+ const relations = ix.accounts.filter((a) => a.kind.kind === "account" && holds(a)).map((a) => relativePath(snakeCase(a.name), group));
119
140
  if (relations.length)
120
- entry.relations = relations.map(snakeCase);
141
+ entry.relations = relations;
121
142
  const seeds = ix.pdas.get(name);
122
143
  const program = ix.pdaPrograms.get(name);
123
- if (seeds)
124
- entry.pda = program ? { seeds, program } : { seeds };
144
+ if (seeds) {
145
+ const own = relativeSeeds(seeds, group);
146
+ entry.pda = program ? { seeds: own, program: relativeSeeds([program], group)[0] } : { seeds: own };
147
+ }
125
148
  const address = ix.accounts.find((a) => a.name === name)?.constraints.address;
126
149
  if (address)
127
150
  entry.address = address.base58;
@@ -134,6 +157,24 @@ function accountEntry(ix, name, k, programAddress) {
134
157
  entry.pda = { seeds: [{ kind: "const", value: [...programId] }], program: { kind: "const", value: BPF_UPGRADEABLE_LOADER } };
135
158
  return entry;
136
159
  }
160
+ /** The instruction's account entries, an account group's fields nested under it: `{ name: "pool", accounts: [...] }`. */
161
+ function nestGroups(ix, entry) {
162
+ const out = [];
163
+ let open;
164
+ for (const a of ix.accounts) {
165
+ if (!a.group) {
166
+ open = undefined;
167
+ out.push(entry(a));
168
+ continue;
169
+ }
170
+ if (open?.param !== a.group.param) {
171
+ open = { param: a.group.param, accounts: [] };
172
+ out.push({ name: snakeCase(a.group.param), accounts: open.accounts });
173
+ }
174
+ open.accounts.push(entry(a));
175
+ }
176
+ return out;
177
+ }
137
178
  /** Anchor IDL (spec 0.1.0) so existing Anchor / Codama clients can talk to TypeSOL programs. */
138
179
  export function buildIdl(model, address, version = "0.1.0") {
139
180
  const structs = [...model.structs.values()];
@@ -145,7 +186,7 @@ export function buildIdl(model, address, version = "0.1.0") {
145
186
  name: ix.name,
146
187
  ...docsOf(ix.node),
147
188
  discriminator: ix.discriminator,
148
- accounts: ix.accounts.map((a) => accountEntry(ix, a.name, a.kind, address)),
189
+ accounts: nestGroups(ix, (a) => accountEntry(ix, a.name, a.kind, address)),
149
190
  args: ix.args.map((a) => ({ name: snakeCase(a.name), ...paramDocs(a.node), type: idlType(a.type, true) })),
150
191
  ...(ix.returns ? { returns: idlType(ix.returns) } : {}),
151
192
  })),
@@ -293,6 +293,17 @@ export interface Constraints {
293
293
  owner: string;
294
294
  mint: string;
295
295
  };
296
+ /**
297
+ * Your errors for these checks (Anchor's `@ ErrorCode.X`), by check: "mut", "signer", "owner", "address" or
298
+ * "hasOne:<field>"; the enum and member named in the type, looked up among the program's error enums.
299
+ */
300
+ errors?: Map<string, {
301
+ enumName: string;
302
+ member: string;
303
+ node: ts.Node;
304
+ }>;
305
+ /** HasOne fields checked against another parameter than the one of the same name (a field of the same group). */
306
+ hasOneParams?: Map<string, string>;
296
307
  }
297
308
  export interface AccountParam {
298
309
  name: string;
@@ -300,8 +311,15 @@ export interface AccountParam {
300
311
  kind: ParamKind;
301
312
  /** `A | null` / `Optional<A>`: the client passes this program's id instead of an account to leave it out. */
302
313
  optional?: boolean;
303
- node: ts.ParameterDeclaration;
314
+ /** The parameter, or the field of an account group. */
315
+ node: ts.ParameterDeclaration | ts.PropertySignature;
304
316
  constraints: Constraints;
317
+ /** A field of an account group: the group parameter, the field, and the group's interface. `name` is `<param>__<field>`. */
318
+ group?: {
319
+ param: string;
320
+ field: string;
321
+ type: string;
322
+ };
305
323
  /** Created in the body as a new keypair account (`create(payer, null, …)`), so it signs: the IDL says so. */
306
324
  signsInit?: boolean;
307
325
  }
package/dist/testing.js CHANGED
@@ -28,6 +28,25 @@ import { buildWorkspace, findWorkspace } from "./workspace.js";
28
28
  export { svmConnection };
29
29
  // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
30
30
  const { BN, BorshCoder } = anchor;
31
+ /**
32
+ * An instruction's accounts with groups flattened as the generated client does: `pool.vault` becomes `pool_vault`
33
+ * (`poolVault` in `t.ix`), and a seed naming a field of the same group names its flattened account.
34
+ */
35
+ function flattenAccounts(items, prefix = "") {
36
+ const out = [];
37
+ for (const it of items) {
38
+ if (it.accounts) {
39
+ const group = `${prefix}${it.name}_`;
40
+ const fields = new Set(it.accounts.filter((f) => !f.accounts).map((f) => f.name));
41
+ const local = (sd) => (sd.kind === "account" && fields.has(sd.path.split(".")[0]) ? { ...sd, path: `${group}${sd.path}` } : sd);
42
+ for (const f of flattenAccounts(it.accounts, group))
43
+ out.push(f.pda ? { ...f, pda: { seeds: f.pda.seeds.map(local), ...(f.pda.program ? { program: local(f.pda.program) } : {}) } } : f);
44
+ continue;
45
+ }
46
+ out.push({ ...it, name: `${prefix}${it.name}` });
47
+ }
48
+ return out;
49
+ }
31
50
  const BIG = new Set(["u64", "i64", "u128", "i128"]);
32
51
  const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
33
52
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
@@ -50,7 +69,8 @@ export async function testProgram(program, from) {
50
69
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
51
70
  export function programHarness(svm, programId, idl) {
52
71
  const coder = new BorshCoder(idl);
53
- const pidl = idl;
72
+ const source = idl;
73
+ const pidl = { ...source, instructions: source.instructions.map((ix) => ({ ...ix, accounts: flattenAccounts(ix.accounts) })) };
54
74
  const types = new Map((pidl.types ?? []).map((t) => [t.name, t]));
55
75
  const enc = getAddressEncoder();
56
76
  /** A plain value → what the Anchor coder expects for `type`. */
package/docs/language.md CHANGED
@@ -67,8 +67,10 @@ The full reference. For a tour, start with the [README](../README.md).
67
67
  | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable) |
68
68
  | `Init<T>` | writable; `create(payer, seeds)` derives the PDA, verifies it, funds rent, writes the discriminator (up to 10 KiB); `create(payer, null)` creates a new keypair account that signs the transaction instead (3010 if it did not; a signer in the IDL); a third argument is Anchor's `space = …` (discriminator included, at least 8 + the struct's size) |
69
69
  | `InitIfNeeded<T>` | `const created = acct.createIfNeeded(payer, seeds)` — creates once; afterwards re-derives the PDA and checks owner, discriminator and size (Anchor `init_if_needed`); `acct.pdaBump` after create. An existing account is used as it is: check the fields you rely on |
70
+ | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`); a group may not be optional, nest another group, or be a helper parameter. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
70
71
  | `constraint(acct, condition, error?)` | Anchor's `constraint = condition @ error` on `acct`: statements at the very start of the body, run with that account's checks (after its `has_one`, before the next account), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
71
72
  | `HasOne<A, "owner">`, `Seeds<A, ["vault", "@owner"], "bump">`, `CloseTo<A, "owner">` | declarative constraints like Anchor's `has_one`, `seeds`/`bump` and `close`: checked before the body (2001 / 2006), close runs when the instruction succeeds; `"@name"` = account key or argument bytes, `"@acct.field"` = a Pubkey, integer or unit enum field of a struct account parameter (also the account's own: `["offer", "@maker", "@offer.id"]`), other strings are literals; recorded as `relations` / `pda` in the IDL. a bump stored in another struct account is named `"@acct.field"` (Anchor `bump = multisig.nonce`); `acct.pdaBump` is the bump (Anchor `ctx.bumps.acct`): the stored field when one is named, else the canonical bump the check found — use it to sign as the PDA |
73
+ | `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` | one of your errors instead of Anchor's code, as Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the constraints Anchor lets you name an error for); a member of one of the program's error enums. For several `HasOne` fields with different errors, nest them: `HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>` |
72
74
  | `HasOne<TokenAccount, "mint" \| "owner">`, `HasOne<Mint, "mintAuthority" \| "freezeAuthority">` | token constraints (2014 / 2015 / 2016 / 2017) against the parameter with that name; `TokenOf<TokenAccount, "mintParam", "authorityParam", "tokenProgramParam">` / `MintOf<Mint, "authorityParam", "freezeParam", "tokenProgramParam">` name the parameters, as Anchor's `token::mint = …` / `mint::authority = …` / `…::token_program = …` do (`never` leaves one out; the token program one: owned by that token program, 2021 / 2022) |
73
75
  | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
74
76
  | `Ata<Init<TokenAccount>, "owner", "mint">`, `Ata<InitIfNeeded<TokenAccount>, "owner", "mint">` | Anchor `init` / `init_if_needed` with `associated_token::…`: `acct.create(payer)` creates the ATA (fails if it exists); `const created = acct.createIfNeeded(payer)` creates it only when missing, otherwise checks it is that ATA (2009). Then it is a `TokenAccount` of that mint and owner (2014 / 2015). Needs `AssociatedTokenProgram`, `SystemProgram` and a token program parameter; call it at the top level before using the account |
@@ -159,6 +161,9 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
159
161
  - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
160
162
  wherever signerSeeds go.
161
163
  - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
164
+ A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
165
+ unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
166
+ declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106.
162
167
 
163
168
  A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
164
169
  `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`):
@@ -30,6 +30,7 @@ and error codes. Its notes (on stderr) list what an existing Anchor client would
30
30
  | Anchor | TypeSOL |
31
31
  | --- | --- |
32
32
  | `#[derive(Accounts)] struct Ctx` + `ctx.accounts.x` | the instruction's parameters, in the same order |
33
+ | a composite field, `pub pool: PoolAccounts<'info>` + `ctx.accounts.pool.vault` | an account group: `export interface PoolAccounts { vault: Mut<TokenAccount>; … }`, the parameter `pool: PoolAccounts`, and `pool.vault` |
33
34
  | `Signer<'info>` / `#[account(mut)] Signer` | `Signer` / `Mut<Signer>` |
34
35
  | `Account<'info, T>` / `#[account(mut)]` | `Account<T>` / `Mut<T>` |
35
36
  | `#[account(init, payer = p, space = …, seeds = […], bump)]` | `Init<T>`, then `const bump = acct.create(p, ["seed", other.key])` (space is computed; `acct.create(p, […], 8n + 64n)` keeps an explicit `space`) |
@@ -38,6 +39,7 @@ and error codes. Its notes (on stderr) list what an existing Anchor client would
38
39
  | `seeds = [b"vault", owner.key().as_ref()], bump = vault.bump` | `Seeds<Mut<Vault>, ["vault", "@owner"], "bump">` |
39
40
  | `seeds = [b"offer", offer.maker.as_ref(), offer.id.to_le_bytes().as_ref()]` | `Seeds<…, ["offer", "@offer.maker", "@offer.id"], "bump">` |
40
41
  | `has_one = owner` | `HasOne<Mut<T>, "owner">` |
42
+ | `has_one = owner @ ErrorCode::NotOwner` (also `address`, `owner`, `signer`, `mut` with `@ …`) | `HasOne<Mut<T>, "owner", ErrorCode.NotOwner>`; `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` |
41
43
  | `close = destination` | `CloseTo<Mut<T>, "destination">`, or `close(acct, destination)` in the body |
42
44
  | `address = ADMIN` | `Address<AccountInfo, "Admin1111…">` |
43
45
  | `owner = program`, `executable` | `Owner<A, "…">`, `Executable<A>` |
@@ -113,6 +115,7 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
113
115
  | `token::mint_to_checked` / `burn_checked` / `approve_checked` | `tokenProgram.mintToChecked(mint, to, authority, amount)` / `burnChecked(from, mint, authority, amount)` / `approveChecked(source, mint, delegate, owner, amount)` |
114
116
  | `system_program::transfer(CpiContext::new_with_signer(…, &[vault_seeds]), lamports)` | `systemProgram.transfer(vault, to, lamports, ["vault", owner.key, bump])` |
115
117
  | `invoke_signed(&ix, infos, &[seeds_a, seeds_b])` | `invoke(program, accounts, data, [seedsA, seedsB])` |
118
+ | `let (_, data) = get_return_data().unwrap(); Quote::try_from_slice(&data)?` | `const quote = returnData<Quote>(program)` (a `@layout borsh` struct when it holds Options, strings or Vecs) |
116
119
  | `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
117
120
  | `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
118
121
  | `multisig.owners = owners` (a `Vec` argument into account data) | the same |
package/lib/typesol.d.ts CHANGED
@@ -469,8 +469,11 @@ export interface AccountMeta {
469
469
  */
470
470
  export declare function pubkey(base58: string): Pubkey;
471
471
 
472
- /** The account must be this exact address (Anchor `address = …`, error 2012): `Address<Mut<AccountInfo>, "4Nd1…">`. */
473
- export type Address<A, Base58 extends string> = A & { readonly __address?: Base58 };
472
+ /**
473
+ * The account must be this exact address (Anchor `address = …`, error 2012): `Address<Mut<AccountInfo>, "4Nd1…">`.
474
+ * A third argument fails with one of your errors instead (Anchor's `address = … @ ErrorCode.X`).
475
+ */
476
+ export type Address<A, Base58 extends string, E = never> = A & { readonly __address?: [Base58, E] };
474
477
 
475
478
  /**
476
479
  * Token constraints, checked before your code runs:
@@ -561,8 +564,11 @@ export interface AccountInfo extends AccountMeta {
561
564
  /** A program-owned account holding struct `T`. Owner and discriminator are checked. */
562
565
  export type Account<T> = Readonly<T> & AccountMeta;
563
566
 
564
- /** Like `Account<T>` but writable. Also usable as `Mut<Signer>`, `Mut<AccountInfo>`, `Mut<TokenAccount>`. */
565
- export type Mut<T> = T & AccountMeta;
567
+ /**
568
+ * Like `Account<T>` but writable. Also usable as `Mut<Signer>`, `Mut<AccountInfo>`, `Mut<TokenAccount>`. A second
569
+ * argument fails with one of your errors when the account is not writable (Anchor's `mut @ ErrorCode.X`; else 2000).
570
+ */
571
+ export type Mut<T, E = never> = T & AccountMeta;
566
572
 
567
573
  /** A PDA seed: a string, a Pubkey, an integer (at its width) or a unit enum value (one byte). */
568
574
  export type Seed = string | Pubkey | bigint | number;
@@ -647,8 +653,12 @@ export type InitIfNeeded<T> = T extends TokenAccount
647
653
  * ("@param" names a program parameter, or give a base58 address).
648
654
  * - `CloseTo<Mut<Vault>, "owner">`: close the account into `owner` when the instruction succeeds.
649
655
  * They nest: `CloseTo<HasOne<Mut<Vault>, "owner">, "owner">`.
656
+ *
657
+ * `HasOne`, `Address`, `Owner`, `Signed` and `Mut` take one of your errors as their last argument, as Anchor's
658
+ * `has_one = owner @ ErrorCode.NotOwner` does: `HasOne<Mut<Vault>, "owner", ErrorCode.NotOwner>` (for one field each
659
+ * its own error, nest them: `HasOne<HasOne<Mut<Vault>, "owner", E.A>, "admin", E.B>`).
650
660
  */
651
- export type HasOne<A, Field extends string> = A & { readonly __hasOne?: Field };
661
+ export type HasOne<A, Field extends string, E = never> = A & { readonly __hasOne?: [Field, E] };
652
662
  /**
653
663
  * Anchor's `token::mint = mintParam, token::authority = authorityParam, token::token_program = tokenProgramParam` on an
654
664
  * existing token account, naming the parameters (2014 / 2015 / 2021: owned by that token program); `never` leaves one out.
@@ -673,7 +683,7 @@ export type Dup<A> = A & { readonly __dup?: true };
673
683
  * The account must sign the transaction (Anchor's `signer` constraint on an account that is not a `Signer`; 2002), e.g.
674
684
  * `Signed<Zeroed<Multisig>>` for an account the client creates with a fresh keypair in the same transaction.
675
685
  */
676
- export type Signed<A> = A & { readonly __signed?: true };
686
+ export type Signed<A, E = never> = A & { readonly __signed?: E | true };
677
687
  /**
678
688
  * Anchor 1.0's `Migration<From, To>`: an existing `From` account (owner, discriminator and size checked) that this
679
689
  * instruction rewrites as `To` with `acct.migrate(payer, value)`, a top-level statement every path must reach. Read
@@ -694,8 +704,8 @@ export type Seeds<A, Names extends readonly string[], Bump extends string = neve
694
704
  /** The PDA's bump (Anchor `ctx.bumps.<account>`): the stored bump field when one is named, else the canonical bump found. */
695
705
  readonly pdaBump: u8;
696
706
  };
697
- /** The account's owner program must be this address (Anchor `owner = …`, 2004). */
698
- export type Owner<A, Base58 extends string> = A & { readonly __owner?: Base58 };
707
+ /** The account's owner program must be this address (Anchor `owner = …`, 2004; a third argument: one of your errors). */
708
+ export type Owner<A, Base58 extends string, E = never> = A & { readonly __owner?: [Base58, E] };
699
709
  /**
700
710
  * An optional account (Anchor `Option<Account<…>>`): the client passes this program's id in its slot to leave it out.
701
711
  * Same as `A | null`. Check `x !== null` before using it; its checks and constraints run only when it is passed.
@@ -1793,9 +1803,12 @@ export declare function emit<T>(event: T): void;
1793
1803
 
1794
1804
  /**
1795
1805
  * Read the return data the last invoke() left behind, checking it came from `program`
1796
- * and has exactly the size of T: `const n = returnData<u64>(counterProgram)`.
1806
+ * and has exactly the size of T: `const n = returnData<u64>(counterProgram)`. A struct is bound to a local:
1807
+ * `const quote = returnData<Quote>(amm)`. A fixed layout of integers, booleans, Pubkeys, unit enums and arrays is its
1808
+ * own Borsh form; a struct with Options, strings or Vecs is declared `@layout borsh` and Borsh-decoded (5106 when the
1809
+ * bytes do not decode to exactly it).
1797
1810
  */
1798
- export declare function returnData<T extends bigint | boolean | Pubkey | Hash>(program: AccountMeta): T;
1811
+ export declare function returnData<T extends bigint | boolean | Pubkey | Hash | object>(program: AccountMeta): T;
1799
1812
 
1800
1813
  /**
1801
1814
  * Verify `account.key` is the PDA for `seeds` + `bump` under this program. Any bump that gives a PDA passes (Anchor's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1249,6 +1249,15 @@ static inline uint64_t ts_return_data(const TsAccount *program, uint8_t *out, ui
1249
1249
  return SUCCESS;
1250
1250
  }
1251
1251
 
1252
+ /* Return data of exactly `size` bytes (a struct), copied straight into `out`. */
1253
+ static inline uint64_t ts_return_data_exact(const TsAccount *program, void *out, uint64_t size) {
1254
+ SolPubkey from;
1255
+ uint64_t n = sol_get_return_data((uint8_t *)out, size, &from);
1256
+ if (n != size || !ts_key_eq(&from, &program->key))
1257
+ TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: missing or mismatched return data");
1258
+ return SUCCESS;
1259
+ }
1260
+
1252
1261
  /* ---- Crypto ---------------------------------------------------------------- */
1253
1262
  static const SolPubkey TS_ED25519_PROGRAM_ID = {{3,125,70,214,124,147,251,190,18,249,66,143,131,141,64,255,5,112,116,73,39,244,138,100,252,202,112,68,128,0,0,0}};
1254
1263
  static const SolPubkey TS_INSTRUCTIONS_SYSVAR_ID = {{6,167,213,23,24,123,209,102,53,218,212,4,85,253,194,192,193,36,198,143,33,86,117,165,219,186,203,95,8,0,0,0}};
@@ -1431,6 +1440,17 @@ static inline uint64_t ts_alloc(uint64_t n, uint8_t **out) {
1431
1440
  return SUCCESS;
1432
1441
  }
1433
1442
 
1443
+ /* Return data of any size (Borsh, at most 1024 bytes) into a heap buffer: its bytes and length. */
1444
+ static inline uint64_t ts_return_data_any(const TsAccount *program, uint8_t **out, uint64_t *len) {
1445
+ TS_TRY(ts_alloc(1024, out));
1446
+ SolPubkey from;
1447
+ uint64_t n = sol_get_return_data(*out, 1024, &from);
1448
+ if (n == 0 || n > 1024 || !ts_key_eq(&from, &program->key))
1449
+ TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: missing or mismatched return data");
1450
+ *len = n;
1451
+ return SUCCESS;
1452
+ }
1453
+
1434
1454
  /* A heap Vec (a Vec<T> in a @layout borsh struct, held on the heap while the instruction runs): room for at least
1435
1455
  `need` elements of `size` bytes, doubling as Rust's Vec does. Elements move when it grows (the compiler refuses
1436
1456
  references into it that would outlive a push). Bounded by the heap; the account bounds it when it is packed (3004). */