@typesol/cli 0.43.0 → 0.44.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 (64) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/NOTICE +71 -0
  3. package/README.md +25 -11
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +4 -0
  9. package/dist/compiler/emit/alias.d.ts +1 -1
  10. package/dist/compiler/emit/alias.js +10 -4
  11. package/dist/compiler/emit/base.d.ts +3 -1
  12. package/dist/compiler/emit/base.js +20 -3
  13. package/dist/compiler/emit/borsh.js +11 -5
  14. package/dist/compiler/emit/calls.d.ts +13 -0
  15. package/dist/compiler/emit/calls.js +91 -8
  16. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  17. package/dist/compiler/emit/cpi-core.js +35 -7
  18. package/dist/compiler/emit/create.js +3 -0
  19. package/dist/compiler/emit/expressions.js +6 -1
  20. package/dist/compiler/emit/function.js +10 -0
  21. package/dist/compiler/emit/shared.d.ts +17 -0
  22. package/dist/compiler/emit/shared.js +36 -3
  23. package/dist/compiler/emit/statements.js +17 -4
  24. package/dist/compiler/emit/storage.d.ts +2 -0
  25. package/dist/compiler/emit/storage.js +16 -8
  26. package/dist/compiler/index.d.ts +15 -1
  27. package/dist/compiler/index.js +40 -3
  28. package/dist/compiler/toolchain.d.ts +41 -1
  29. package/dist/compiler/toolchain.js +102 -3
  30. package/dist/testing-stake.d.ts +2 -1
  31. package/dist/testing-stake.js +2 -1
  32. package/dist/testing.js +6 -4
  33. package/dist/tools/clientgen.d.ts +15 -0
  34. package/dist/tools/clientgen.js +173 -7
  35. package/dist/tools/cpigen.d.ts +0 -15
  36. package/dist/tools/cpigen.js +19 -8
  37. package/dist/tools/doctor.d.ts +17 -2
  38. package/dist/tools/doctor.js +64 -4
  39. package/dist/tools/portgen.js +43 -18
  40. package/dist/workspace.d.ts +20 -0
  41. package/dist/workspace.js +173 -6
  42. package/docs/ai.md +10 -5
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +63 -17
  45. package/docs/case-study-escrow.md +1 -1
  46. package/docs/case-study-phoenix.md +10 -10
  47. package/docs/case-study-raydium-amm.md +3 -3
  48. package/docs/case-study-spl-stake-pool.md +5 -5
  49. package/docs/cli.md +17 -8
  50. package/docs/client.md +11 -3
  51. package/docs/errors.md +1 -1
  52. package/docs/language.md +10 -5
  53. package/docs/mainnet.md +21 -10
  54. package/docs/migrate-from-anchor.md +2 -1
  55. package/docs/runtime.md +11 -1
  56. package/docs/security-model.md +38 -6
  57. package/docs/stability.md +21 -2
  58. package/docs/testing.md +25 -0
  59. package/docs/troubleshooting.md +12 -0
  60. package/llms-full.txt +168 -52
  61. package/llms.txt +1 -1
  62. package/package.json +3 -1
  63. package/runtime/typesol_rt.h +22 -13
  64. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/dist/cli.js CHANGED
@@ -5,16 +5,18 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { parseArgs } from "node:util";
8
- import { build, CompileError, COMPILER_VERSION, generate, SBPF_VERSIONS, verifyBinary } from "./compiler/index.js";
8
+ import { createHash } from "node:crypto";
9
+ import { build, CompileError, COMPILER_VERSION, describeToolchain, elfLength, generate, SBPF_VERSIONS, toolchainDifferences, verifyBinary, } from "./compiler/index.js";
10
+ import { setToolchainStrict } from "./compiler/toolchain.js";
9
11
  import { generateCpi } from "./tools/cpigen.js";
10
12
  import { generatePort } from "./tools/portgen.js";
11
13
  import { generateClient, writeClient } from "./tools/clientgen.js";
12
14
  import { buildIdl } from "./compiler/idl.js";
13
- import { decodeAddress, loadOrCreateKeypair, readKeypair } from "./keys.js";
15
+ import { base58, decodeAddress, loadOrCreateKeypair, readKeypair } from "./keys.js";
14
16
  import { formatProfile, profileLogs } from "./tools/profile.js";
15
17
  import { TEMPLATE_NAMES } from "./templates.js";
16
18
  import { addProgram, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, } from "./workspace.js";
17
- import { clusterUrl, deployPreflight, doctorChecks, formatChecks, INSTALL_AGAVE, solanaConfig as readSolanaConfig, toolchainCheck } from "./tools/doctor.js";
19
+ import { cliRpc, clusterUrl, deployPreflight, doctorChecks, formatChecks, INSTALL_AGAVE, rpcHost, solanaConfig as readSolanaConfig, toolchainCheck, } from "./tools/doctor.js";
18
20
  const ASSETS = fileURLToPath(new URL("../assets/", import.meta.url));
19
21
  /** A usage problem: printed with the command's help, exit code 2. */
20
22
  class UsageError extends Error {
@@ -39,6 +41,7 @@ function banner() {
39
41
  return `\n${art}\n TypeScript in, SBF out. v${COMPILER_VERSION}\n`;
40
42
  }
41
43
  const SBPF = `--sbpf v0|v1|v2 SBPF version (default v0, or "sbpf" in ${CONFIG}); v1/v2 need clusters that enabled them`;
44
+ const TOOLCHAIN_STRICT = "--toolchain-strict refuse to build with platform-tools other than the tested ones (default: one warning); also TYPESOL_TOOLCHAIN=strict";
42
45
  const COMMANDS = {
43
46
  new: {
44
47
  usage: "typesol new <program> [--template counter|vault|escrow]",
@@ -96,25 +99,35 @@ const COMMANDS = {
96
99
  log(`\n ! The Solana platform-tools are not installed yet; npm test compiles with them. Install once:\n` +
97
100
  (tools.fix ?? []).map((f) => ` ${f}`).join("\n"));
98
101
  log(`\n next:\n` +
99
- (rel === "." ? "" : ` cd ${rel}\n`) +
102
+ (rel === "." ? "" : ` cd ${shellQuote(rel)}\n`) +
100
103
  ` npm install\n` +
101
104
  ` npm test # builds ${name} and runs its test in LiteSVM, a Solana runtime in-process\n` +
102
- ` npx typesol doctor # checks the toolchain, keypair and RPC before a deploy` +
105
+ ` npx --no-install typesol doctor # checks the toolchain, keypair and RPC before a deploy` +
103
106
  (template === "counter" ? `\n\n other starters: typesol init <dir> --template vault (SOL at a PDA) or --template escrow (SPL token escrow)` : ""));
104
107
  return 0;
105
108
  },
106
109
  },
107
110
  build: {
108
- usage: "typesol build [<program>…] [--sbpf v0|v1|v2] [--profile]\n typesol build <program.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile]",
111
+ usage: "typesol build [<program>…] [--sbpf v0|v1|v2] [--profile] [--toolchain-strict]\n typesol build <program.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict]",
109
112
  help: [
110
113
  `In a project (${CONFIG}): build every program, or the ones named, into <out>/<name>/ (.so, IDL .json, .client.ts, .c, .build.json).`,
111
114
  "Outside a project, or with a .ts file: build that file (its keypair is created next to the output if needed).",
112
115
  SBPF,
113
116
  "--profile log a marker and the remaining compute units before every statement (for `typesol profile`; not for release)",
117
+ TOOLCHAIN_STRICT,
114
118
  "--quiet no banner",
115
119
  ].join("\n "),
116
- options: { sbpf: { type: "string" }, profile: { type: "boolean" }, out: { type: "string" }, "program-id": { type: "string" }, quiet: { type: "boolean" } },
120
+ options: {
121
+ sbpf: { type: "string" },
122
+ profile: { type: "boolean" },
123
+ out: { type: "string" },
124
+ "program-id": { type: "string" },
125
+ quiet: { type: "boolean" },
126
+ "toolchain-strict": { type: "boolean" },
127
+ },
117
128
  run(v, args) {
129
+ if (v["toolchain-strict"])
130
+ setToolchainStrict();
118
131
  const sbpf = sbpfOf(v);
119
132
  const profile = !!v.profile;
120
133
  const ws = findWorkspace(process.cwd());
@@ -139,7 +152,11 @@ const COMMANDS = {
139
152
  log(banner());
140
153
  const outDir = v.out ?? path.join(path.dirname(file), "target");
141
154
  const { model } = generate(file);
142
- const keyFile = v["program-id"] ?? path.join(outDir, `${model.name}-keypair.json`);
155
+ const given = v["program-id"];
156
+ // A keypair given by name must be there: creating one in its place would give the program a new address.
157
+ if (given !== undefined && !existsSync(given))
158
+ throw new UsageError(`--program-id ${given} does not exist (leave --program-id out to create a keypair next to the output)`);
159
+ const keyFile = given ?? path.join(outDir, `${model.name}-keypair.json`);
143
160
  mkdirSync(path.dirname(keyFile), { recursive: true });
144
161
  const { address, created } = loadOrCreateKeypair(keyFile);
145
162
  const res = build(file, outDir, address, { sbpf: sbpf ?? "v0", profile });
@@ -150,7 +167,7 @@ const COMMANDS = {
150
167
  log(` idl ${res.idlPath}`);
151
168
  log(` client ${client.path}`);
152
169
  log(` manifest ${res.manifestPath}`);
153
- log(`\n deploy: solana program deploy ${res.soPath} --program-id ${keyFile}`);
170
+ log(`\n deploy: solana program deploy ${shellQuote(res.soPath)} --program-id ${shellQuote(keyFile)}`);
154
171
  return 0;
155
172
  },
156
173
  },
@@ -164,51 +181,19 @@ const COMMANDS = {
164
181
  ].join("\n "),
165
182
  options: { json: { type: "boolean" }, stdin: { type: "boolean" }, files: { type: "boolean" } },
166
183
  run(v, args) {
167
- // In a project: the named programs, or all of them.
168
- const ws = !v.stdin && !v.files && !args.some((a) => a.endsWith(".ts")) ? findWorkspace(process.cwd()) : undefined;
169
- if (ws) {
170
- const diagnostics = [];
171
- for (const name of names(ws, args)) {
172
- try {
173
- const { model } = generate(programPaths(ws, name).entry);
174
- if (!v.json)
175
- log(`ok ${name}: ${model.instructions.length} instruction(s), ${model.accountStructs.size} account type(s), ${model.events.size} event(s)`);
176
- }
177
- catch (e) {
178
- if (!(e instanceof CompileError))
179
- throw e;
180
- diagnostics.push(...e.diagnostics);
181
- if (!v.json)
182
- console.error(`${name}:\n${showDiagnostics(e.diagnostics)}`);
183
- }
184
- }
185
- if (v.json)
186
- log(JSON.stringify({ ok: !diagnostics.length, diagnostics }));
187
- return diagnostics.length ? 1 : 0;
188
- }
189
- const file = path.resolve(one(args, "<program.ts>"));
190
- let files;
191
- if (v.stdin)
192
- files = new Map([[file, readFileSync(0, "utf8")]]);
193
- else if (v.files) {
194
- const given = JSON.parse(readFileSync(0, "utf8")).files ?? {};
195
- files = new Map(Object.entries(given).map(([p, t]) => [path.resolve(p), t]));
196
- }
184
+ if (!v.json)
185
+ return check(v, args);
186
+ // --json is read by programs (the editor plugin, agents): every outcome is one JSON object, never a usage text.
197
187
  try {
198
- if (!files?.has(file))
199
- mustExist(file);
200
- const { model } = generate(file, { files });
201
- if (v.json)
202
- log(JSON.stringify({ ok: true, diagnostics: [] }));
203
- else
204
- log(`ok ${model.name}: ${model.instructions.length} instruction(s), ${model.accountStructs.size} account type(s), ${model.events.size} event(s)`);
205
- return 0;
188
+ return check(v, args);
206
189
  }
207
190
  catch (e) {
208
- if (!v.json || !(e instanceof CompileError))
209
- throw e;
210
- log(JSON.stringify({ ok: false, diagnostics: e.diagnostics }));
211
- return 1;
191
+ const message = e instanceof Error ? e.message : String(e);
192
+ if (e instanceof CompileError)
193
+ log(JSON.stringify({ ok: false, diagnostics: e.diagnostics }));
194
+ else
195
+ log(JSON.stringify({ ok: false, diagnostics: [], error: message }));
196
+ return e instanceof UsageError ? 2 : 1;
212
197
  }
213
198
  },
214
199
  },
@@ -230,7 +215,7 @@ const COMMANDS = {
230
215
  help: [
231
216
  "Serve the Model Context Protocol on stdio for AI coding agents: tools to check a program (errors with hints), read",
232
217
  "its IDL, search the docs, and read the rules a TypeSOL program follows. `typesol init` writes .mcp.json (Claude",
233
- "Code) and .cursor/mcp.json (Cursor) that start it as `npx typesol mcp`.",
218
+ "Code) and .cursor/mcp.json (Cursor) that start it as `npx --no-install typesol mcp`.",
234
219
  ].join("\n "),
235
220
  options: {},
236
221
  async run() {
@@ -248,32 +233,48 @@ const COMMANDS = {
248
233
  ].join("\n "),
249
234
  options: { url: { type: "string" }, config: { type: "string" } },
250
235
  async run(v) {
236
+ if (v.config !== undefined)
237
+ solanaConfig(v.config); // a --config that does not exist is a usage error, as elsewhere
251
238
  const checks = await doctorChecks({ cwd: process.cwd(), url: v.url, config: v.config });
252
239
  log(formatChecks(checks));
253
240
  return checks.some((c) => !c.ok && !c.optional) ? 1 : 0;
254
241
  },
255
242
  },
256
243
  deploy: {
257
- usage: "typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <solana cli config>] [--sbpf v0|v1|v2] [--dry-run]",
244
+ usage: "typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <solana cli config>] [--sbpf v0|v1|v2] [--dry-run] [--toolchain-strict]",
258
245
  help: [
259
246
  `In a project: build, then \`solana program deploy\` each program at its <out>/deploy/<name>-keypair.json address.`,
260
247
  "Deploying again upgrades it (the payer must be the upgrade authority). --dry-run builds and prints the commands.",
261
248
  "Needs the Agave CLI (`solana`) on PATH.",
249
+ TOOLCHAIN_STRICT,
262
250
  ].join("\n "),
263
- options: { url: { type: "string" }, keypair: { type: "string" }, config: { type: "string" }, "dry-run": { type: "boolean" }, sbpf: { type: "string" } },
251
+ options: {
252
+ url: { type: "string" },
253
+ keypair: { type: "string" },
254
+ config: { type: "string" },
255
+ "dry-run": { type: "boolean" },
256
+ sbpf: { type: "string" },
257
+ "toolchain-strict": { type: "boolean" },
258
+ },
264
259
  async run(v, args) {
260
+ if (v["toolchain-strict"])
261
+ setToolchainStrict();
265
262
  const ws = needWorkspace("deploy");
263
+ const cfg = solanaConfig(v.config);
264
+ const url = v.url ?? cfg.url;
265
+ // Without either, `solana program deploy` would pick its own default cluster (mainnet-beta): never silently.
266
+ if (!url && !v["dry-run"])
267
+ throw new Error("no cluster: pass --url (devnet, mainnet-beta, localhost or an RPC URL), or set json_rpc_url in the Solana CLI config (`solana config set --url devnet`)");
266
268
  const built = buildWorkspace(ws, names(ws, args), { sbpf: sbpfOf(v), needKeypair: true });
267
- if (!v["dry-run"]) {
269
+ if (url && !v["dry-run"]) {
268
270
  // Before any transaction: the RPC answers and the payer can afford it, with what to do if not.
269
- const cfg = solanaConfig(v.config);
270
- const url = v.url ?? cfg.url;
271
- if (url)
272
- await deployPreflight({
273
- url: clusterUrl(url),
274
- payer: v.keypair ?? cfg.keypair ?? path.join(os.homedir(), ".config/solana/id.json"),
275
- programs: built.map((b) => ({ soPath: b.result.soPath, address: b.address, name: b.paths.name })),
276
- });
271
+ const payer = v.keypair ?? cfg.keypair ?? path.join(os.homedir(), ".config/solana/id.json");
272
+ await deployPreflight({
273
+ url: clusterUrl(url),
274
+ payer,
275
+ programs: built.map((b) => ({ soPath: b.result.soPath, address: b.address, name: b.paths.name })),
276
+ });
277
+ log(` cluster ${rpcHost(clusterUrl(url))}, payer ${payerAddress(payer)}`);
277
278
  }
278
279
  for (const b of built) {
279
280
  const cliArgs = deployArgs(b.result.soPath, b.paths.keypair, { url: v.url, payer: v.keypair, config: v.config });
@@ -317,7 +318,8 @@ const COMMANDS = {
317
318
  const kit = await import("@solana/kit");
318
319
  const { publishIdl, rpcChain } = await import("./tools/idlpublish.js");
319
320
  const signer = await kit.createKeyPairSignerFromBytes(readKeypair(keyFile));
320
- const chain = rpcChain(kit.createSolanaRpc(clusterUrl(rpcUrl)));
321
+ const chain = rpcChain(await cliRpc(clusterUrl(rpcUrl)));
322
+ log(` cluster ${rpcHost(clusterUrl(rpcUrl))}, payer ${signer.address}`);
321
323
  for (const name of names(ws, args)) {
322
324
  // The IDL only needs the compiled model and the program address: the deployed binary is left alone.
323
325
  const { address } = programAddress(ws, name);
@@ -349,9 +351,8 @@ const COMMANDS = {
349
351
  const rpcUrl = v.url ?? solanaConfig(v.config).url;
350
352
  if (!rpcUrl)
351
353
  throw new Error("no RPC: pass --url, or set json_rpc_url in the Solana CLI config");
352
- const kit = await import("@solana/kit");
353
354
  const { cloneAccounts } = await import("./tools/clone.js");
354
- const lines = await cloneAccounts(kit.createSolanaRpc(clusterUrl(rpcUrl)), [...new Set(addresses)], dir);
355
+ const lines = await cloneAccounts((await cliRpc(clusterUrl(rpcUrl))), [...new Set(addresses)], dir);
355
356
  for (const l of lines)
356
357
  log(` ${l}`);
357
358
  log(` ${lines.length} written to ${path.relative(process.cwd(), dir) || "."}`);
@@ -426,7 +427,7 @@ const COMMANDS = {
426
427
  // Loaded only here: the other commands do not need an RPC client.
427
428
  const kit = await import("@solana/kit");
428
429
  const { fetchProgramIdl } = await import("./tools/idlpublish.js");
429
- const found = await fetchProgramIdl(kit.createSolanaRpc(clusterUrl(rpcUrl)), kit.address(v.address));
430
+ const found = await fetchProgramIdl(await cliRpc(clusterUrl(rpcUrl)), kit.address(v.address));
430
431
  console.error(` IDL from ${found.source === "anchor" ? "Anchor's IDL account" : "the Program Metadata program"}`);
431
432
  idl = found.idl;
432
433
  }
@@ -448,7 +449,7 @@ const COMMANDS = {
448
449
  },
449
450
  },
450
451
  verify: {
451
- usage: "typesol verify <program.ts | program> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <solana cli config>] [--sbpf v0|v1|v2]",
452
+ usage: "typesol verify <program.ts | program> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <solana cli config>] [--sbpf v0|v1|v2] [--manifest <name.build.json>]",
452
453
  help: [
453
454
  "Rebuild and compare with what is deployed. Exit 0 on a match, 3 on a mismatch.",
454
455
  "With a .so (e.g. from `solana program dump`): compare with that file.",
@@ -457,8 +458,12 @@ const COMMANDS = {
457
458
  "on chain (`typesol idl publish`) with the one the source builds; a published IDL that differs is a mismatch.",
458
459
  "The SBPF version is read from the deployed binary unless --sbpf is given. Reproducible builds need the same",
459
460
  "TypeSOL version and platform-tools as the original (see its <name>.build.json).",
461
+ "On a mismatch, the toolchain of each side that is known: the rebuild's, and the deployed binary's from a build",
462
+ "manifest whose binary hash is the deployed one's (--manifest, <deployed>.build.json next to a given .so, or the",
463
+ "local build's). A program on chain carries no record of what built it: keep the .build.json with the deployment.",
464
+ "--manifest <file> the <name>.build.json of the build that was deployed",
460
465
  ].join("\n "),
461
- options: { sbpf: { type: "string" }, address: { type: "string" }, url: { type: "string" }, config: { type: "string" } },
466
+ options: { sbpf: { type: "string" }, address: { type: "string" }, url: { type: "string" }, config: { type: "string" }, manifest: { type: "string" } },
462
467
  async run(v, args) {
463
468
  if (args.length < 1 || args.length > 2)
464
469
  throw new UsageError("verify takes the program and, optionally, the deployed .so");
@@ -467,6 +472,8 @@ const COMMANDS = {
467
472
  throw new UsageError("give either a deployed .so or --address/--url, not both");
468
473
  if (v.address && !decodeAddress(v.address))
469
474
  throw new UsageError(`--address "${v.address}" is not a base58 Solana address`);
475
+ if (v.manifest !== undefined && !existsSync(v.manifest))
476
+ throw new UsageError(`${v.manifest} does not exist`);
470
477
  const ws = findWorkspace(process.cwd());
471
478
  const name = ws && (ws.programs[target] ? target : programForEntry(ws, target));
472
479
  const entry = ws && name ? programPaths(ws, name).entry : target;
@@ -487,9 +494,8 @@ const COMMANDS = {
487
494
  if (!rpcUrl)
488
495
  throw new Error("no RPC: pass --url, or set json_rpc_url in the Solana CLI config");
489
496
  // Loaded only here: the other commands do not need an RPC client.
490
- const kit = await import("@solana/kit");
491
497
  const { fetchDeployed } = await import("./tools/onchain.js");
492
- const rpc = kit.createSolanaRpc(clusterUrl(rpcUrl));
498
+ const rpc = await cliRpc(clusterUrl(rpcUrl));
493
499
  const info = await fetchDeployed(rpc, address);
494
500
  onChain = { address, info, rpc };
495
501
  deployed = info.elf;
@@ -511,6 +517,17 @@ const COMMANDS = {
511
517
  log(same
512
518
  ? ` match ${res.manifest.binary} (sbpf ${sbpf})`
513
519
  : ` MISMATCH ${what} is not what ${entry} builds to (${res.manifest.binary}, sbpf ${sbpf})`);
520
+ if (!same) {
521
+ // The rebuild's own output directory was temporary; the local build's manifest sits in the usual place.
522
+ const local = ws && name ? programPaths(ws, name).outDir : path.join(path.dirname(entry), "target");
523
+ const candidates = [
524
+ v.manifest,
525
+ deployedPath ? deployedPath.replace(/\.so$/, "") + ".build.json" : undefined,
526
+ path.join(local, `${res.manifest.program}.build.json`),
527
+ ].filter((f) => !!f);
528
+ for (const line of toolchainHint(res.manifest, deployed, candidates, !!v.manifest))
529
+ log(line);
530
+ }
514
531
  if (!onChain)
515
532
  return same ? 0 : 3;
516
533
  const { info } = onChain;
@@ -600,11 +617,108 @@ function showDiagnostics(diagnostics, sources) {
600
617
  })
601
618
  .join("\n\n");
602
619
  }
620
+ /** `typesol check`: diagnostics as text, or (--json) as JSON; CompileErrors from a single file are thrown. */
621
+ function check(v, args) {
622
+ // In a project: the named programs, or all of them.
623
+ const ws = !v.stdin && !v.files && !args.some((a) => a.endsWith(".ts")) ? findWorkspace(process.cwd()) : undefined;
624
+ if (ws) {
625
+ const diagnostics = [];
626
+ for (const name of names(ws, args)) {
627
+ try {
628
+ const { model } = generate(programPaths(ws, name).entry);
629
+ if (!v.json)
630
+ log(`ok ${name}: ${model.instructions.length} instruction(s), ${model.accountStructs.size} account type(s), ${model.events.size} event(s)`);
631
+ }
632
+ catch (e) {
633
+ if (!(e instanceof CompileError))
634
+ throw e;
635
+ diagnostics.push(...e.diagnostics);
636
+ if (!v.json)
637
+ console.error(`${name}:\n${showDiagnostics(e.diagnostics)}`);
638
+ }
639
+ }
640
+ if (v.json)
641
+ log(JSON.stringify({ ok: !diagnostics.length, diagnostics }));
642
+ return diagnostics.length ? 1 : 0;
643
+ }
644
+ const file = path.resolve(one(args, "<program.ts>"));
645
+ let files;
646
+ if (v.stdin)
647
+ files = new Map([[file, readFileSync(0, "utf8")]]);
648
+ else if (v.files) {
649
+ let given;
650
+ try {
651
+ given = JSON.parse(readFileSync(0, "utf8"))?.files ?? {};
652
+ }
653
+ catch (e) {
654
+ throw new UsageError(`--files: stdin is not JSON (${e.message})`);
655
+ }
656
+ if (typeof given !== "object" || given === null || Object.values(given).some((t) => typeof t !== "string"))
657
+ throw new UsageError('--files: expected { "files": { "<absolute path>": "<text>", … } } on stdin');
658
+ files = new Map(Object.entries(given).map(([p, t]) => [path.resolve(p), t]));
659
+ }
660
+ if (!files?.has(file))
661
+ mustExist(file);
662
+ const { model } = generate(file, { files });
663
+ if (v.json)
664
+ log(JSON.stringify({ ok: true, diagnostics: [] }));
665
+ else
666
+ log(`ok ${model.name}: ${model.instructions.length} instruction(s), ${model.accountStructs.size} account type(s), ${model.events.size} event(s)`);
667
+ return 0;
668
+ }
603
669
  function mustExist(file) {
604
670
  if (!existsSync(file))
605
671
  throw new UsageError(`${file} does not exist`);
606
672
  return file;
607
673
  }
674
+ /**
675
+ * After a verify mismatch: the toolchain of the rebuild and, when a build manifest describes the deployed bytes (its
676
+ * binary hash is theirs), of the deployed build, and what differs. A manifest that describes other bytes (an older
677
+ * local build) is only mentioned: its toolchain says nothing about the deployed binary.
678
+ */
679
+ function toolchainHint(rebuilt, deployed, candidates, explicit) {
680
+ const lines = [` rebuilt ${describeToolchain(rebuilt)}`];
681
+ const deployedHash = createHash("sha256")
682
+ .update(deployed.subarray(0, elfLength(deployed)))
683
+ .digest("hex");
684
+ let other;
685
+ const unrelated = [];
686
+ for (const file of [...new Set(candidates.map((c) => path.resolve(c)))]) {
687
+ if (!existsSync(file))
688
+ continue;
689
+ let manifest;
690
+ try {
691
+ manifest = JSON.parse(readFileSync(file, "utf8"));
692
+ }
693
+ catch {
694
+ continue;
695
+ }
696
+ if (typeof manifest?.clang !== "string" || typeof manifest.binary !== "string")
697
+ continue;
698
+ if (manifest.binary === deployedHash) {
699
+ other = { file, manifest };
700
+ break;
701
+ }
702
+ unrelated.push({ file, manifest });
703
+ }
704
+ const rel = (f) => path.relative(process.cwd(), f) || f;
705
+ if (other) {
706
+ lines.push(` deployed ${describeToolchain(other.manifest)} (${rel(other.file)}, whose binary hash is the deployed one's)`);
707
+ const diff = toolchainDifferences(rebuilt, other.manifest);
708
+ lines.push(diff.length
709
+ ? ` differs ${diff.join(", ")}: ${diff.includes("clang") ? "another clang can compile the same C to other bytes; " : ""}rebuild with the deployed side's ${diff.join(" and ")} to compare like with like`
710
+ : " same toolchain and compiler versions on both sides: the sources (or an import, or the runtime header) differ");
711
+ return lines;
712
+ }
713
+ lines.push(" deployed toolchain unknown: a deployed program records nothing about what built it" +
714
+ (explicit ? "" : "; pass --manifest <name>.build.json, kept from the build that was deployed"));
715
+ for (const u of unrelated) {
716
+ const diff = toolchainDifferences(rebuilt, u.manifest);
717
+ lines.push(` note ${rel(u.file)} describes another binary (${u.manifest.binary.slice(0, 12)}…, ${describeToolchain(u.manifest)})` +
718
+ (diff.length ? `; it differs from the rebuild in ${diff.join(", ")}` : ""));
719
+ }
720
+ return lines;
721
+ }
608
722
  /** Quote a command-line word for a POSIX shell when it needs it. */
609
723
  function shellQuote(s) {
610
724
  return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
@@ -642,7 +756,17 @@ function readJson(file) {
642
756
  throw new Error(`${file}: not valid JSON (${e.message})`);
643
757
  }
644
758
  }
645
- /** Make the compiler read `text` for `file` (instead of the disk) until the returned function is called. */
759
+ /** The address of a payer keypair file, for the line printed before a deploy (or why there is none). */
760
+ function payerAddress(file) {
761
+ if (!existsSync(file))
762
+ return `none at ${file} (the Solana CLI will refuse)`;
763
+ try {
764
+ return base58(readKeypair(file).subarray(32));
765
+ }
766
+ catch (e) {
767
+ return `unreadable ${file} (${e.message})`;
768
+ }
769
+ }
646
770
  /** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
647
771
  function solanaConfig(file) {
648
772
  const cfg = readSolanaConfig(file);
@@ -2566,6 +2566,10 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
2566
2566
  const dest = accounts.find((o) => o.name === c.closeTo);
2567
2567
  if (!dest)
2568
2568
  reporter.fail(a.node, `CloseTo<…, "${c.closeTo}">: add an account parameter named "${c.closeTo}"`);
2569
+ // Closing into itself would zero the account and then hand its own lamports back to it: the runtime refuses the
2570
+ // instruction (unbalanced), after everything else ran.
2571
+ if (dest === a)
2572
+ reporter.fail(a.node, `CloseTo<…, "${c.closeTo}">: the destination is the account being closed; name another writable account`);
2569
2573
  }
2570
2574
  });
2571
2575
  }
@@ -38,7 +38,7 @@ export declare abstract class AliasEmitter extends EmitterBase {
38
38
  * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
39
39
  * value. Refuse when a live reference into the replaced place is still used afterwards.
40
40
  */
41
- protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string): void;
41
+ protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string, inPlace?: boolean): void;
42
42
  /**
43
43
  * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
44
44
  * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
@@ -69,14 +69,16 @@ export class AliasEmitter extends EmitterBase {
69
69
  * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
70
70
  * value. Refuse when a live reference into the replaced place is still used afterwards.
71
71
  */
72
- assertNotAliased(replaced, at, helper) {
72
+ assertNotAliased(replaced, at, helper, inPlace = false) {
73
73
  if (!replaced)
74
74
  return;
75
75
  for (const scope of this.scopes)
76
76
  for (const [name, l] of scope) {
77
77
  if (!l.paths || !l.decl)
78
78
  continue;
79
- const hit = replaced.find((r) => l.paths.some((p) => p === r || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
79
+ // A helper given an account changes it in place (`inPlace`): a local naming the whole account (a struct loaded
80
+ // with loadAccountMut) then reads what JS's object would. Only references into it are stale.
81
+ const hit = replaced.find((r) => l.paths.some((p) => (p === r && !inPlace) || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
80
82
  if (!hit || !this.usedAfter(l.decl, at))
81
83
  continue;
82
84
  this.fail(at, helper
@@ -198,8 +200,12 @@ export class AliasEmitter extends EmitterBase {
198
200
  }
199
201
  /** A storage path as the source names it: `@<C local>.x` becomes `<its name>.x` (`@p_rec.items[]` → `rec.items[]`). */
200
202
  showPath(path) {
201
- if (!path.startsWith("@"))
202
- return path;
203
+ if (!path.startsWith("@")) {
204
+ // A field of an account group, as the source names it: `g__pool.b[]` → `g.pool.b[]`.
205
+ const root = path.split(/[.[]/)[0];
206
+ const g = this.accounts.get(root)?.group;
207
+ return g ? [...g.path, g.field].join(".") + path.slice(root.length) : path;
208
+ }
203
209
  // A @heap local is named through its pointer: `@(*l_x)`.
204
210
  const c = /^@(\(\*\w+\)|\w+)/.exec(path)?.[1];
205
211
  for (const s of [...this.scopes].reverse().concat(this.args))
@@ -105,6 +105,8 @@ export declare abstract class EmitterBase {
105
105
  * copy an earlier operand that reads storage into a temporary just before them, so it sees the old state.
106
106
  */
107
107
  protected settle(v: Value, mark: number): Value;
108
+ /** Whether a C line emitted from `mark` on assigns, increments or takes the address of the C variable `name`. */
109
+ protected writtenSince(name: string, mark: number): boolean;
108
110
  /** A string that stays valid when account data changes: views of account text are copied to the heap. */
109
111
  protected ownedString(v: Value): Value;
110
112
  /** Reject `a?.b` / `f?.()`: there is no undefined in TypeSOL. */
@@ -171,7 +173,7 @@ export declare abstract class EmitterBase {
171
173
  protected abstract accountChoice(node: ts.ConditionalExpression): Value;
172
174
  protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
173
175
  protected abstract isTxIx(node: ts.Expression): boolean;
174
- protected abstract seeds(node: ts.Expression, extra: number): {
176
+ protected abstract seeds(node: ts.Expression, extra: number, bound?: boolean): {
175
177
  name: string;
176
178
  count: number;
177
179
  idl: IdlSeed[] | undefined;
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { calleeName, resolveScalarType, structNameOf } from "../analyze.js";
3
3
  import { isScalar, } from "../model.js";
4
- import { isStable, cString, valueC, fixedVecC, } from "./shared.js";
4
+ import { isStable, cString, valueC, fixedVecC, passedByPointer, } from "./shared.js";
5
5
  /**
6
6
  * State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
7
7
  * scopes, evaluation-order snapshots and account lookups.
@@ -122,6 +122,9 @@ export class EmitterBase {
122
122
  this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type.array, mutable: false, readonly: true, ...owned });
123
123
  else if (p.type.kind === "dataEnumArg")
124
124
  this.args.set(p.name, { c: `p_${p.name}`, type: { kind: "enumRef", name: p.type.name, writable: false }, mutable: false, ...owned });
125
+ // A Pubkey, Option, string or u256 comes as a const pointer (see passedByPointer): read through it.
126
+ else if (passedByPointer(p.type))
127
+ this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type, mutable: false });
125
128
  else
126
129
  this.args.set(p.name, { c: `p_${p.name}`, type: p.type, mutable: false, ...(p.type.kind === "structRef" ? owned : {}) });
127
130
  }
@@ -265,8 +268,13 @@ export class EmitterBase {
265
268
  settle(v, mark) {
266
269
  if (this.lines.length === mark || v.isNull || v.literal !== undefined || v.stringLiteral !== undefined)
267
270
  return v;
268
- if (isStable(v.c))
269
- return v;
271
+ // A local (or a temporary) is stable unless what was emitted since writes it: a closure or list callback expanded
272
+ // in the later operand (`x + bump()` with `bump` doing `x += 1n`), or an outlined loop given its address.
273
+ if (isStable(v.c)) {
274
+ const name = /^(?:\w+|\(&(\w+)\))$/.exec(v.c) ? (/^\w+$/.test(v.c) ? v.c : v.c.slice(2, -1)) : undefined;
275
+ if (!name || !this.writtenSince(name, mark))
276
+ return v;
277
+ }
270
278
  const t = this.tmp("snap");
271
279
  const pad = " ".repeat(this.indent);
272
280
  const decl = [];
@@ -297,6 +305,15 @@ export class EmitterBase {
297
305
  this.lines.splice(mark, 0, ...decl.map((l) => pad + l));
298
306
  return out;
299
307
  }
308
+ /** Whether a C line emitted from `mark` on assigns, increments or takes the address of the C variable `name`. */
309
+ writtenSince(name, mark) {
310
+ const n = name.replace(/\W/g, "");
311
+ const w = new RegExp(`(?:\\b${n}(?:\\.\\w+|\\[[^\\]]*\\])*\\s*(?:[-+*/%&|^]|<<|>>)?=(?!=)|&\\s*\\(?\\s*${n}\\b|\\b${n}\\s*(?:\\+\\+|--)|(?:\\+\\+|--)\\s*${n}\\b)`);
312
+ for (let i = mark; i < this.lines.length; i++)
313
+ if (this.lines[i].includes(n) && w.test(this.lines[i]))
314
+ return true;
315
+ return false;
316
+ }
300
317
  /** A string that stays valid when account data changes: views of account text are copied to the heap. */
301
318
  ownedString(v) {
302
319
  if (v.type.kind !== "string" || !v.c.startsWith("ts_fstr_view"))
@@ -184,8 +184,11 @@ function codec(s, model, o) {
184
184
  ? borshMinSize(variableStruct(t, model), model)
185
185
  : fixedBytes(t, model);
186
186
  const minAfter = s.fields.map((_, i) => s.fields.slice(i + 1).reduce((n, f) => n + minOf(f.type), 0));
187
- const need = (n, rest, pad) => `${pad}if (${n} > len - at - ${rest}) ${DESER};`;
188
- const room = (n, rest, pad) => `${pad}if (${n} > cap - at - ${rest}) ${SER};`;
187
+ // Compared without a subtraction that could wrap: `at` may already be within `rest` of the end (a Some tag or a
188
+ // list element reserves only its own smallest form), and `len - at - rest` would then pass anything. `n` is at
189
+ // most 2^32 elements of at most a few KiB, `at` and `rest` stay near `len`: the sum cannot overflow 64 bits.
190
+ const need = (n, rest, pad) => `${pad}if ((uint64_t)(${n}) + at + ${rest} > len) ${DESER};`;
191
+ const room = (n, rest, pad) => `${pad}if ((uint64_t)(${n}) + at + ${rest} > cap) ${SER};`;
189
192
  // A String / Vec / Option field, `rest` bytes of later fields still to come.
190
193
  const unpackVar = (t, lv, rest, pad) => {
191
194
  switch (t.kind) {
@@ -227,12 +230,13 @@ function codec(s, model, o) {
227
230
  ...(check.length ? [`${pad}for (uint64_t ${i} = 0; ${i} < ${l}; ${i}++) {`, ...check, `${pad}}`] : []),
228
231
  ];
229
232
  }
230
- // Strings: each element's length prefix is checked as it is reached.
233
+ // Strings and structs holding Options: each element's smallest form is checked as it is reached (its length
234
+ // prefix, or its fixed fields and tags), before anything of it is read.
231
235
  const i = tmp("i");
232
236
  return [
233
237
  ...head,
234
238
  `${pad}for (uint64_t ${i} = 0; ${i} < ${l}; ${i}++) {`,
235
- need("4", rest, `${pad} `),
239
+ need(String(minOf(t.elem)), rest, `${pad} `),
236
240
  ...unpackVar(t.elem, `${lv}.items[${i}]`, rest, `${pad} `),
237
241
  `${pad}}`,
238
242
  ];
@@ -263,6 +267,8 @@ function codec(s, model, o) {
263
267
  `${pad}if (${tag} > 1) ${DESER};`,
264
268
  `${pad}${lv}.some = ${tag};`,
265
269
  `${pad}if (${tag}) {`,
270
+ // The tag reserved one byte: the struct's smallest form must be there before its fields are read.
271
+ need(String(minOf(t.inner)), rest, `${pad} `),
266
272
  ...unpackVar(t.inner, `${lv}.v`, rest, `${pad} `),
267
273
  `${pad}}`,
268
274
  ];
@@ -305,7 +311,7 @@ function codec(s, model, o) {
305
311
  for (const f of v.fields) {
306
312
  const flv = `${lv}.v.${v.name}.${f.name}`;
307
313
  if (f.type.kind === "string") {
308
- lines.push(`${pad} if (4 > len - at - ${rest}) ${DESER};`, ...unpackVar(f.type, flv, rest, `${pad} `));
314
+ lines.push(need("4", rest, `${pad} `), ...unpackVar(f.type, flv, rest, `${pad} `));
309
315
  continue;
310
316
  }
311
317
  const n = fixedBytes(f.type, model);
@@ -185,6 +185,12 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
185
185
  protected migrate(node: ts.CallExpression, a: AccountParam, topLevel: boolean): Value | undefined;
186
186
  /** Whether a helper (or one it calls) grows a Vec, which needs the instruction's SystemProgram for rent. */
187
187
  private helperGrows;
188
+ /**
189
+ * After close(acct, dest) the account holds no data and belongs to the System Program: reading or writing it later in
190
+ * the function (or on a later turn of a loop around the close) would read zeros or write bytes that are dropped. The
191
+ * same holds for a reference into it read later. Refused, like a view used after closeRaw (assertNoViewAfter).
192
+ */
193
+ protected assertNotUsedAfterClose(a: AccountParam, at: ts.CallExpression): void;
188
194
  /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
189
195
  private helperResizes;
190
196
  /** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
@@ -209,6 +215,13 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
209
215
  /** A function given for a function parameter of an expanded helper or closure, as something to expand. */
210
216
  protected closureOf(arg: ts.Expression): Closure;
211
217
  protected callHelper(node: ts.CallExpression, h: Helper): Value | undefined;
218
+ /**
219
+ * A Pubkey, Option, string or u256 helper argument, passed as a pointer (see passedByPointer). When the helper can
220
+ * write (it takes accounts or Inout places) and the argument is not a named C object nothing passed can reach (see
221
+ * unreachableArg), the pointer is to a copy taken here: JS gives the helper the value as it is at the call. A
222
+ * helper that writes nothing reads the caller's value in place.
223
+ */
224
+ protected pointerArg(v: Value, mayWrite: boolean): string;
212
225
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
213
226
  protected helperArg(h: Helper, p: Helper["params"][number], n: ts.Expression): Value | string;
214
227
  /**