@typesol/cli 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +10 -9
  3. package/dist/cli.js +50 -5
  4. package/dist/compiler/analyze.js +187 -42
  5. package/dist/compiler/emit/alias.js +5 -1
  6. package/dist/compiler/emit/base.d.ts +5 -0
  7. package/dist/compiler/emit/base.js +24 -6
  8. package/dist/compiler/emit/calls.d.ts +5 -1
  9. package/dist/compiler/emit/calls.js +109 -15
  10. package/dist/compiler/emit/cpi-core.d.ts +8 -0
  11. package/dist/compiler/emit/cpi-core.js +17 -2
  12. package/dist/compiler/emit/cpi.js +10 -4
  13. package/dist/compiler/emit/create.d.ts +2 -0
  14. package/dist/compiler/emit/create.js +56 -13
  15. package/dist/compiler/emit/expressions.js +16 -6
  16. package/dist/compiler/emit/function.d.ts +3 -1
  17. package/dist/compiler/emit/function.js +21 -12
  18. package/dist/compiler/emit/statements.js +53 -3
  19. package/dist/compiler/emit/storage.js +8 -8
  20. package/dist/compiler/emit/token.js +43 -0
  21. package/dist/compiler/idl.js +47 -6
  22. package/dist/compiler/model.d.ts +19 -1
  23. package/dist/templates.js +13 -36
  24. package/dist/testing.d.ts +30 -0
  25. package/dist/testing.js +85 -3
  26. package/dist/workspace.d.ts +16 -1
  27. package/dist/workspace.js +49 -5
  28. package/docs/audit.md +1 -1
  29. package/docs/case-study-escrow.md +3 -3
  30. package/docs/case-study-multisig.md +3 -3
  31. package/docs/case-study-raydium-cp-swap.md +51 -21
  32. package/docs/cli.md +5 -3
  33. package/docs/errors.md +3 -1
  34. package/docs/language.md +17 -5
  35. package/docs/migrate-from-anchor.md +6 -0
  36. package/docs/test-your-program.md +12 -3
  37. package/docs/testing.md +1 -1
  38. package/lib/typesol.d.ts +51 -15
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -7
package/CHANGELOG.md CHANGED
@@ -6,6 +6,60 @@ 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
+
25
+ ## 0.32.0 — 2026-10-30
26
+
27
+ Anchor parity and usability: Raydium CP-Swap's pool creation and what creating accounts by hand needs, several PDAs
28
+ signing one CPI, PDA-signed SOL transfers, the checked token instructions, faster u128 arithmetic and Clock reads,
29
+ clearer errors, and tooling for fresh clones, multi-program projects and token tests.
30
+
31
+ - New: `systemProgram.allocate(account, space, seeds?)` / `assign(account, owner, seeds?)`, `programId()`,
32
+ `findProgramAddressBump(seeds, program)`, `initAccount<T>(account)` (Anchor's `load_init` on an account the body
33
+ created: 3007 / 3006 / 3003 / 3000), `Pubkey.compare(other)` (Rust's byte order), and `ata.create(payer,
34
+ tokenProgram)` / `createIfNeeded(payer, tokenProgram)` to pick among several token programs.
35
+ - Changed: an `Init` create on an address already in use now fails as Anchor's `init` does, with the System Program's
36
+ AccountAlreadyInUse (custom 0) instead of TypeSOL's 3000; a payer that is the account being created fails with 4101
37
+ (TryingToInitPayerAsProgramAccount). Programs creating accounts use 9–13 fewer compute units; binaries move by ±1%.
38
+ - Faster: u128 multiplication, division and remainder take the native 64-bit instructions when the values fit in 64
39
+ bits (most amounts and rates) instead of the 128-bit library routines; results are unchanged (the arithmetic fuzzer
40
+ now samples such values a third of the time).
41
+ - Faster: an instruction reads the Clock sysvar once, on its first `now()` / `currentSlot()` / `currentEpoch()`, and
42
+ reuses it (the Clock does not change within a transaction). With both, Raydium CP-Swap's swap drops from 7,478 to
43
+ 5,734 compute units.
44
+ - Changed: examples/raydium-cp-swap ports `initialize` too (10 of 24 instructions; 70 transactions against mainnet).
45
+ - New: several PDAs can sign one CPI: `invoke` / `invokeInstruction` take a list of seed lists (`[["vault", key, b1],
46
+ ["fees", b2]]`, at most 16). A seed list can be named once and reused: `const vault = signer([...])`.
47
+ - New: `systemProgram.transfer(from, to, lamports, signerSeeds)` pays out of a system-owned PDA of the program (a SOL
48
+ vault).
49
+ - New: `tokenProgram.mintToChecked`, `burnChecked` and `approveChecked`, which take the decimals from the mint.
50
+ - Better errors: `throw`, `try`/`catch`, optional and default parameters, `...rest` parameters and optional fields now
51
+ say what to write instead; "unsupported call" names the callee and, for common JavaScript calls (`console.log`,
52
+ `Math.min`, `BigInt`, …), the TypeSOL form.
53
+ - Tooling: a project without its program keypair (a fresh clone, CI) builds and tests at the address `typesol.json`
54
+ records; only `deploy` needs the keypair. New projects run `typesol build` before `npm test` and `npm run
55
+ typecheck`, which import the client it writes.
56
+ - Tooling: `typesol new <program>` adds a program and its test to a project; `typesol check` with no argument checks
57
+ every program of the project (or those named).
58
+ - Testing: `t.mint`, `t.tokenAccount` and `t.tokenBalance` write and read SPL Token / Token-2022 accounts in the VM,
59
+ `t.warp` moves the Clock, `t.errorName(code)` names an error, and a failed `t.ok` names the error. The escrow
60
+ template uses them (and no longer needs `@solana-program/token`).
61
+ - Docs: the docs in the npm package link to tests and examples on GitHub.
62
+
9
63
  ## 0.31.0 — 2026-10-30
10
64
 
11
65
  A second real program checked against its mainnet binary: Raydium CP-Swap's trading core, and the Token-2022 reads an
package/README.md CHANGED
@@ -178,7 +178,7 @@ starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-
178
178
  program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
179
179
  checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units), and
180
180
  [docs/case-study-raydium-cp-swap.md](docs/case-study-raydium-cp-swap.md) does the same for Raydium CP-Swap's swaps and liquidity
181
- (same outcomes, account bytes and events on 59 transactions; 51–79% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
181
+ (pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
182
182
  mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
183
183
 
184
184
  ## How it works
@@ -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, return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
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`) |
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) |
@@ -220,8 +220,9 @@ The full reference, with every type, check and built-in, is in [docs/language.md
220
220
  | Command | What it does |
221
221
  | --- | --- |
222
222
  | `typesol init` | scaffold a project with a program, a LiteSVM test and TypeScript configs |
223
+ | `typesol new <program>` | add another program and its test to a project |
223
224
  | `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
224
- | `typesol check` | typecheck and subset-check without compiling |
225
+ | `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file) |
225
226
  | `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
226
227
  | `typesol idl publish` | upload the IDL to the Program Metadata program (canonical when the upgrade authority signs) |
227
228
  | `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
@@ -254,16 +255,16 @@ toolchain and records them with every result:
254
255
  <!-- bench:table -->
255
256
  | Instruction | TypeSOL | Pinocchio 0.10 | Native Rust | Anchor 1.0.2 |
256
257
  | --- | ---: | ---: | ---: | ---: |
257
- | counter.initialize | **1,866** | 3,186 | 4,601 | 6,573 |
258
+ | counter.initialize | **1,857** | 3,186 | 4,601 | 6,573 |
258
259
  | counter.increment | **110** | 113 | 857 | 2,323 |
259
- | vault.open | **1,885** | 3,185 | 4,613 | 6,627 |
260
+ | vault.open | **1,874** | 3,185 | 4,613 | 6,627 |
260
261
  | vault.deposit | **1,314** | 1,377 | 2,832 | 4,355 |
261
262
  | vault.withdraw | **315** | 370 | 1,176 | 3,628 |
262
263
  | vault.shut | **161** | 167 | 950 | 2,024 |
263
- | escrow.make | **3,605** | 6,179 | 9,240 | 13,304 |
264
+ | escrow.make | **3,596** | 6,179 | 9,240 | 13,304 |
264
265
  | escrow.take | **4,019** | 4,051 | 8,500 | 14,365 |
265
266
  | escrow.refund | **2,696** | 2,769 | 5,695 | 8,449 |
266
- | binary, counter / vault / escrow | 11.0 / 14.1 / 21.3 KB | 19.6 / 22.9 / 29.4 KB | 27.9 / 35.0 / 46.5 KB | 145.2 / 158.9 / 190.7 KB |
267
+ | binary, counter / vault / escrow | 11.1 / 14.1 / 21.4 KB | 19.6 / 22.9 / 29.4 KB | 27.9 / 35.0 / 46.5 KB | 145.2 / 158.9 / 190.7 KB |
267
268
  <!-- /bench:table -->
268
269
 
269
270
  `initialize`, `open` and `make` include the PDA bump search. TypeSOL hashes PDA candidates with the sha256 and
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ import { buildIdl } from "./compiler/idl.js";
13
13
  import { decodeAddress, loadOrCreateKeypair, readKeypair } from "./keys.js";
14
14
  import { formatProfile, profileLogs } from "./tools/profile.js";
15
15
  import { TEMPLATE_NAMES } from "./templates.js";
16
- import { buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold } from "./workspace.js";
16
+ import { addProgram, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, } from "./workspace.js";
17
17
  import { clusterUrl, deployPreflight, doctorChecks, formatChecks, INSTALL_AGAVE, solanaConfig as readSolanaConfig, toolchainCheck } from "./tools/doctor.js";
18
18
  const ASSETS = fileURLToPath(new URL("../assets/", import.meta.url));
19
19
  /** A usage problem: printed with the command's help, exit code 2. */
@@ -40,6 +40,29 @@ function banner() {
40
40
  }
41
41
  const SBPF = `--sbpf v0|v1|v2 SBPF version (default v0, or "sbpf" in ${CONFIG}); v1/v2 need clusters that enabled them`;
42
42
  const COMMANDS = {
43
+ new: {
44
+ usage: "typesol new <program> [--template counter|vault|escrow]",
45
+ help: [
46
+ "Add a program to this project: programs/<program>.ts, tests/<program>.test.ts and its entry in typesol.json.",
47
+ "Refuses to overwrite files. <program> must be snake_case. Templates as for `typesol init`.",
48
+ ].join("\n "),
49
+ options: { template: { type: "string" } },
50
+ run(v, args) {
51
+ const name = one(args, "<program>");
52
+ if (!/^[a-z][a-z0-9_]*$/.test(name))
53
+ throw new UsageError(`"${name}" must be snake_case (a-z, 0-9, _; starting with a letter)`);
54
+ const template = v.template ?? "counter";
55
+ if (!TEMPLATE_NAMES.includes(template))
56
+ throw new UsageError(`--template "${template}" is not one of ${TEMPLATE_NAMES.join(", ")}`);
57
+ const ws = needWorkspace("new");
58
+ const { files, missing } = addProgram(ws, name, template);
59
+ for (const f of files)
60
+ log(` ${f === CONFIG ? "updated" : "created"} ${path.relative(process.cwd(), path.join(ws.root, f)) || f}`);
61
+ if (missing.length)
62
+ log(`\n The ${template} test also needs: npm install -D ${missing.join(" ")}`);
63
+ return 0;
64
+ },
65
+ },
43
66
  init: {
44
67
  usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
45
68
  help: [
@@ -103,7 +126,7 @@ const COMMANDS = {
103
126
  if (!v.quiet && process.stdout.isTTY)
104
127
  log(banner());
105
128
  for (const b of buildWorkspace(ws, inProject ? [inProject] : names(ws, args), { sbpf, profile }))
106
- log(` ${b.paths.name.padEnd(12)} ${b.address}${b.created ? " (new keypair)" : ""} ${path.relative(process.cwd(), b.result.soPath)}`);
129
+ log(` ${b.paths.name.padEnd(12)} ${b.address}${b.created ? " (new keypair)" : b.keyless ? " (no keypair here: deploying needs it)" : ""} ${path.relative(process.cwd(), b.result.soPath)}`);
107
130
  return 0;
108
131
  }
109
132
  if (!file)
@@ -131,15 +154,37 @@ const COMMANDS = {
131
154
  },
132
155
  },
133
156
  check: {
134
- usage: "typesol check <program.ts> [--json] [--stdin | --files]",
157
+ usage: "typesol check [<program.ts> | <program>…] [--json] [--stdin | --files]",
135
158
  help: [
136
- "Typecheck and validate the TypeSOL subset without building.",
159
+ "Typecheck and validate the TypeSOL subset without building. In a project, no argument checks every program.",
137
160
  "--json print { ok, diagnostics: [{ file, line, column, message }] } (exit 1 when there are diagnostics)",
138
161
  "--stdin read <program.ts>'s text from stdin instead of the file (an editor's unsaved buffer); its imports are read from disk",
139
162
  '--files read { "files": { "<absolute path>": "<text>", … } } from stdin: those files\' texts instead of the disk (unsaved buffers)',
140
163
  ].join("\n "),
141
164
  options: { json: { type: "boolean" }, stdin: { type: "boolean" }, files: { type: "boolean" } },
142
165
  run(v, args) {
166
+ // In a project: the named programs, or all of them.
167
+ const ws = !v.stdin && !v.files && !args.some((a) => a.endsWith(".ts")) ? findWorkspace(process.cwd()) : undefined;
168
+ if (ws) {
169
+ const diagnostics = [];
170
+ for (const name of names(ws, args)) {
171
+ try {
172
+ const { model } = generate(programPaths(ws, name).entry);
173
+ if (!v.json)
174
+ log(`ok ${name}: ${model.instructions.length} instruction(s), ${model.accountStructs.size} account type(s), ${model.events.size} event(s)`);
175
+ }
176
+ catch (e) {
177
+ if (!(e instanceof CompileError))
178
+ throw e;
179
+ diagnostics.push(...e.diagnostics);
180
+ if (!v.json)
181
+ console.error(`${name}:\n${e.message}`);
182
+ }
183
+ }
184
+ if (v.json)
185
+ log(JSON.stringify({ ok: !diagnostics.length, diagnostics }));
186
+ return diagnostics.length ? 1 : 0;
187
+ }
143
188
  const file = path.resolve(one(args, "<program.ts>"));
144
189
  let files;
145
190
  if (v.stdin)
@@ -203,7 +248,7 @@ const COMMANDS = {
203
248
  options: { url: { type: "string" }, keypair: { type: "string" }, config: { type: "string" }, "dry-run": { type: "boolean" }, sbpf: { type: "string" } },
204
249
  async run(v, args) {
205
250
  const ws = needWorkspace("deploy");
206
- const built = buildWorkspace(ws, names(ws, args), { sbpf: sbpfOf(v) });
251
+ const built = buildWorkspace(ws, names(ws, args), { sbpf: sbpfOf(v), needKeypair: true });
207
252
  if (!v["dry-run"]) {
208
253
  // Before any transaction: the RPC answers and the payer can afford it, with what to do if not.
209
254
  const cfg = solanaConfig(v.config);
@@ -25,6 +25,17 @@ const C_RESERVED = new Set([
25
25
  ..."auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while bool true false asm typeof".split(" "),
26
26
  ..."NULL SUCCESS HEAP_LENGTH HEAP_START_ADDRESS MAX_PERMITTED_DATA_INCREASE MAX_RETURN_DATA MAX_SEED_LENGTH_EXCEEDED INVALID_SEEDS SIZE_PUBKEY memcpy memset strlen static_assert offsetof sol_log_64".split(" "),
27
27
  ]);
28
+ /** A parameter is a plain name with an explicit type; say what to write instead of the rest. */
29
+ function paramShape(p, reporter) {
30
+ if (p.questionToken)
31
+ reporter.fail(p, `optional parameters are not supported; use ${p.name.getText()}: Option<T> and pass null for none`);
32
+ if (p.initializer)
33
+ reporter.fail(p, "default values are not supported; the client passes every argument");
34
+ if (p.dotDotDotToken)
35
+ reporter.fail(p, "...rest parameters are not supported; take a Vec<T> argument, or remainingAccounts() for accounts");
36
+ if (!ts.isIdentifier(p.name) || !p.type)
37
+ reporter.fail(p, "parameters need a plain name and an explicit type");
38
+ }
28
39
  /** Why a name cannot be used as a C member, or undefined when it can. */
29
40
  export function cNameProblem(name) {
30
41
  if (name.includes("__") || name.startsWith("_"))
@@ -284,6 +295,7 @@ export function analyze(entry, files) {
284
295
  const functions = [];
285
296
  const helperNodes = [];
286
297
  const interfaces = [];
298
+ const groups = new Map();
287
299
  const aliases = [];
288
300
  /** Program-wide names (structs, enums, helpers) -> declaring file, for collision errors. */
289
301
  const declared = new Map();
@@ -325,7 +337,11 @@ export function analyze(entry, files) {
325
337
  if (!isExported(stmt))
326
338
  reporter.fail(stmt, "structs must be exported");
327
339
  declare(stmt.name, file);
328
- 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 });
329
345
  }
330
346
  else if (ts.isTypeAliasDeclaration(stmt)) {
331
347
  if (!isExported(stmt))
@@ -601,7 +617,7 @@ export function analyze(entry, files) {
601
617
  });
602
618
  continue;
603
619
  }
604
- 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));
605
621
  if (h)
606
622
  helpers.set(h.name, h);
607
623
  }
@@ -622,7 +638,7 @@ export function analyze(entry, files) {
622
638
  bound.set(n, t);
623
639
  });
624
640
  const display = `${g.display}<${[...typeArgs.map((t) => (t.kind === "struct" ? t.name : typeName(t))), ...fnArgs].join(", ")}>`;
625
- 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);
626
642
  h.typeArgs = bound;
627
643
  h.structArgs = boundStructs;
628
644
  if (g.fnParams.length) {
@@ -638,7 +654,7 @@ export function analyze(entry, files) {
638
654
  const argStructs = new Set();
639
655
  const instructions = [];
640
656
  for (const fn of functions) {
641
- 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));
642
658
  if (!ix)
643
659
  continue;
644
660
  instructions.push(ix);
@@ -997,7 +1013,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
997
1013
  if (!ts.isPropertySignature(m) || !m.type || !ts.isIdentifier(m.name))
998
1014
  reporter.fail(m, "structs may only contain plain fields");
999
1015
  if (m.questionToken)
1000
- reporter.fail(m, "optional fields are not supported");
1016
+ reporter.fail(m, `optional fields are not supported; use ${m.name.getText()}: Option<T> (null for none)`);
1001
1017
  const name = m.name.text;
1002
1018
  if (RESERVED_FIELDS.has(name))
1003
1019
  reporter.fail(m.name, `"${name}" is reserved; pick another field name`);
@@ -1348,7 +1364,7 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
1348
1364
  reporter.error(s.node.name, `${s.name} is @layout borsh, so it is account data only; ${other.name}.${f.name} cannot hold one`);
1349
1365
  }
1350
1366
  }
1351
- 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()) {
1352
1368
  if (!fn.body)
1353
1369
  reporter.fail(fn, "helper functions need a body");
1354
1370
  if (fn.asteriskToken)
@@ -1374,8 +1390,7 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1374
1390
  const params = fn.parameters
1375
1391
  .filter((_, i) => !skip.has(i))
1376
1392
  .map((p) => {
1377
- if (!ts.isIdentifier(p.name) || !p.type || p.initializer || p.questionToken || p.dotDotDotToken)
1378
- reporter.fail(p, "parameters need a plain name and an explicit type");
1393
+ paramShape(p, reporter);
1379
1394
  // `p_<name>__n` carries a SignerSeeds count: "__" in a name could collide with it.
1380
1395
  if (p.name.text.includes("__") || p.name.text.includes("$"))
1381
1396
  reporter.error(p.name, `"${p.name.text}": "__" and "$" are reserved in names`);
@@ -1395,6 +1410,8 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1395
1410
  wrapped === "Ata" ||
1396
1411
  wrapped === "Signed")
1397
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))`);
1398
1415
  const account = resolveAccountKind(p.type, reporter, scope.imports, structs);
1399
1416
  if (account.kind === "init" || account.kind === "initIfNeeded" || account.kind === "zeroed" || account.kind === "migrate")
1400
1417
  reporter.fail(p.type, "helpers take accounts that exist: create Init/InitIfNeeded/Zeroed accounts in the instruction, then pass them as Mut<T>");
@@ -1457,7 +1474,55 @@ function checkRecursion(sources, decls, checker, reporter) {
1457
1474
  for (const name of byName.keys())
1458
1475
  walk(name, []);
1459
1476
  }
1460
- 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()) {
1461
1526
  const imports = scope.imports;
1462
1527
  if (!fn.name || !fn.body)
1463
1528
  reporter.fail(fn, "instructions need a name and a body");
@@ -1487,8 +1552,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1487
1552
  let minArgsSize = 0;
1488
1553
  for (const p of fn.parameters) {
1489
1554
  reporter.guard(() => {
1490
- if (!ts.isIdentifier(p.name) || !p.type || p.initializer || p.questionToken || p.dotDotDotToken)
1491
- reporter.fail(p, "parameters need a plain name and an explicit type");
1555
+ paramShape(p, reporter);
1492
1556
  const value = resolveValueType(p.type, scope, true) ?? resolveArgAggregate(p.type, scope, structs);
1493
1557
  if (value) {
1494
1558
  args.push({ name: p.name.text, type: value, node: p });
@@ -1504,33 +1568,91 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1504
1568
  : 0;
1505
1569
  return;
1506
1570
  }
1507
- // Optional accounts: `Mut<Vault> | null` or `Optional<Mut<Vault>>`.
1508
- let typeNode = p.type;
1509
- let optional = false;
1510
- const isNull = (t) => ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword;
1511
- if (ts.isUnionTypeNode(typeNode) && typeNode.types.length === 2 && typeNode.types.some(isNull)) {
1512
- optional = true;
1513
- typeNode = typeNode.types.find((t) => !isNull(t));
1514
- }
1515
- else if (typesolName(typeNode, imports) === "Optional") {
1516
- optional = true;
1517
- 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;
1518
1617
  }
1519
- const constraints = { hasOne: [] };
1520
- const inner = unwrapConstraints(typeNode, reporter, imports, constraints);
1521
- const kind = resolveAccountKind(inner, reporter, imports, structs);
1522
- if (optional &&
1523
- (["init", "initIfNeeded", "zeroed", "migrate", "pyth", "eventAuthority", "selfProgram", "programData"].includes(kind.kind) ||
1524
- ((kind.kind === "token" || kind.kind === "mint") && kind.init)))
1525
- reporter.fail(p, "Init, InitIfNeeded, Zeroed, PythPriceUpdate, EventAuthority, SelfProgram and ProgramData accounts cannot be optional");
1526
- 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);
1527
1621
  });
1528
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
+ }
1529
1645
  checkSnakeDuplicates(args.map((a) => ({ name: a.name, node: a.node })), "arguments", reporter);
1530
1646
  checkSnakeDuplicates(accounts.map((a) => ({ name: a.name, node: a.node })), "accounts", reporter);
1531
- for (const p of [...args, ...accounts])
1532
- if (p.name.includes("__") || p.name.includes("$"))
1533
- 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`);
1534
1656
  // Constraints refer to other parameters by name: check them now that all are known.
1535
1657
  for (const a of accounts) {
1536
1658
  const c = a.constraints;
@@ -1561,7 +1683,8 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1561
1683
  reporter.fail(a.node, "MintOf<…> applies to a Mint");
1562
1684
  continue;
1563
1685
  }
1564
- if (!accounts.some((o) => o.name === f))
1686
+ const target = c.hasOneParams?.get(f) ?? f;
1687
+ if (!accounts.some((o) => o.name === target))
1565
1688
  reporter.fail(a.node, `HasOne<…, "${f}">: add an account parameter named "${f}"`);
1566
1689
  if (a.kind.kind === "token") {
1567
1690
  if (f !== "mint" && f !== "owner")
@@ -1578,8 +1701,6 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1578
1701
  const field = struct.fields.find((x) => x.name === f);
1579
1702
  if (!field || field.type.kind !== "pubkey" || field.type.hash)
1580
1703
  reporter.fail(a.node, `HasOne<…, "${f}">: ${struct.name} needs a Pubkey field "${f}"`);
1581
- if (!accounts.some((o) => o.name === f))
1582
- reporter.fail(a.node, `HasOne<…, "${f}">: add an account parameter named "${f}"`);
1583
1704
  }
1584
1705
  if (c.seeds?.bump?.startsWith("@")) {
1585
1706
  // "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`).
@@ -1622,7 +1743,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1622
1743
  for (const a of accounts) {
1623
1744
  const c = a.constraints;
1624
1745
  const refs = [
1625
- ...c.hasOne.map((e) => e.split("=").at(-1)),
1746
+ ...c.hasOne.map((e) => (e.includes("=") ? e.split("=").at(-1) : (c.hasOneParams?.get(e) ?? e))),
1626
1747
  ...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).split(".")[0]),
1627
1748
  ...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
1628
1749
  ...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
@@ -1695,9 +1816,24 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1695
1816
  /** Peel HasOne / Seeds / CloseTo wrappers off a parameter type, recording what they ask for. */
1696
1817
  function unwrapConstraints(node, reporter, imports, out) {
1697
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
+ }
1698
1835
  if (!["HasOne", "TokenOf", "MintOf", "Seeds", "CloseTo", "Address", "Ata", "Owner", "Executable", "Dup", "Signed"].includes(name ?? ""))
1699
1836
  return node;
1700
- const args = node.typeArguments ?? [];
1701
1837
  const lit = (t) => {
1702
1838
  if (!t)
1703
1839
  return [];
@@ -1707,8 +1843,12 @@ function unwrapConstraints(node, reporter, imports, out) {
1707
1843
  return t.types.flatMap(lit);
1708
1844
  reporter.fail(t, "expected a string literal type");
1709
1845
  };
1710
- if (name === "HasOne")
1711
- 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
+ }
1712
1852
  // Anchor's `token::mint = m, token::authority = a` / `mint::authority = a, mint::freeze_authority = f` naming the
1713
1853
  // parameters: recorded as "field=param" (`never` leaves one out).
1714
1854
  if (name === "TokenOf" || name === "MintOf") {
@@ -1734,19 +1874,23 @@ function unwrapConstraints(node, reporter, imports, out) {
1734
1874
  if (!bytes)
1735
1875
  reporter.fail(args[1] ?? node, `Owner<…, "base58">: "${text}" is not a valid base58 Solana address`);
1736
1876
  out.owner = { base58: text, bytes: [...bytes] };
1877
+ customError("owner", args[2]);
1737
1878
  }
1738
1879
  if (name === "Executable")
1739
1880
  out.executable = true;
1740
1881
  if (name === "Dup")
1741
1882
  out.dup = true;
1742
- if (name === "Signed")
1883
+ if (name === "Signed") {
1743
1884
  out.signed = true;
1885
+ customError("signer", args[1]);
1886
+ }
1744
1887
  if (name === "Address") {
1745
1888
  const text = lit(args[1])[0];
1746
1889
  const bytes = text === undefined ? undefined : decodeAddress(text);
1747
1890
  if (!bytes)
1748
1891
  reporter.fail(args[1] ?? node, `Address<…, "base58">: "${text}" is not a valid base58 Solana address`);
1749
1892
  out.address = { base58: text, bytes: [...bytes] };
1893
+ customError("address", args[2]);
1750
1894
  }
1751
1895
  if (name === "Ata") {
1752
1896
  const [owner] = lit(args[1]);
@@ -1903,7 +2047,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
1903
2047
  return { kind: "zeroed", struct: s };
1904
2048
  }
1905
2049
  case "Mut": {
1906
- 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();
1907
2052
  const s = structOf(t);
1908
2053
  if (s)
1909
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;
@@ -125,6 +129,7 @@ export declare abstract class EmitterBase {
125
129
  protected abstract createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
126
130
  protected abstract systemTransfer(node: ts.CallExpression): undefined;
127
131
  protected abstract createAccount(node: ts.CallExpression, system: AccountParam): undefined;
132
+ protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
128
133
  protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
129
134
  protected abstract ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
130
135
  protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;