@typesol/cli 0.44.1 → 0.46.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 (80) hide show
  1. package/CHANGELOG.md +343 -0
  2. package/NOTICE +14 -1
  3. package/README.md +115 -26
  4. package/SECURITY.md +10 -8
  5. package/dist/bin.d.ts +2 -0
  6. package/dist/bin.js +9 -0
  7. package/dist/cli.js +226 -62
  8. package/dist/compiler/analyze.js +57 -6
  9. package/dist/compiler/diagnostics.d.ts +4 -3
  10. package/dist/compiler/diagnostics.js +10 -6
  11. package/dist/compiler/emit/base.d.ts +1 -1
  12. package/dist/compiler/emit/calls.js +18 -5
  13. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  14. package/dist/compiler/emit/cpi-core.js +8 -4
  15. package/dist/compiler/emit/expressions.d.ts +14 -0
  16. package/dist/compiler/emit/expressions.js +52 -4
  17. package/dist/compiler/emit/shared.d.ts +8 -1
  18. package/dist/compiler/emit/shared.js +8 -1
  19. package/dist/compiler/emit/statements.d.ts +8 -3
  20. package/dist/compiler/emit/statements.js +68 -3
  21. package/dist/compiler/emit/storage.js +5 -1
  22. package/dist/compiler/hints.d.ts +7 -0
  23. package/dist/compiler/hints.js +58 -9
  24. package/dist/compiler/index.d.ts +56 -1
  25. package/dist/compiler/index.js +27 -3
  26. package/dist/compiler/model.js +3 -2
  27. package/dist/compiler/toolchain.d.ts +73 -2
  28. package/dist/compiler/toolchain.js +222 -17
  29. package/dist/node-version.d.ts +4 -0
  30. package/dist/node-version.js +12 -0
  31. package/dist/tools/docker.d.ts +183 -0
  32. package/dist/tools/docker.js +442 -0
  33. package/dist/tools/doctor.d.ts +44 -0
  34. package/dist/tools/doctor.js +108 -14
  35. package/dist/workspace.d.ts +11 -3
  36. package/dist/workspace.js +46 -9
  37. package/docker/Dockerfile +163 -0
  38. package/docker/deps/0.43.0.lock.json +1206 -0
  39. package/docker/deps/0.44.0.lock.json +1206 -0
  40. package/docker/deps/0.44.1.lock.json +1206 -0
  41. package/docker/deps/0.45.0.lock.json +1206 -0
  42. package/docker/deps/0.46.0.lock.json +1206 -0
  43. package/docs/ai.md +2 -1
  44. package/docs/architecture.md +18 -6
  45. package/docs/audit.md +15 -7
  46. package/docs/case-study-phoenix.md +1 -1
  47. package/docs/case-study-raydium-amm.md +1 -1
  48. package/docs/case-study-spl-stake-pool.md +1 -1
  49. package/docs/cli.md +71 -6
  50. package/docs/errors.md +22 -8
  51. package/docs/glossary.md +210 -0
  52. package/docs/language-accounts.md +499 -0
  53. package/docs/language-basics.md +389 -0
  54. package/docs/language-builtins.md +411 -0
  55. package/docs/language-chain.md +198 -0
  56. package/docs/language-cpi.md +470 -0
  57. package/docs/language-errors-events.md +184 -0
  58. package/docs/language-native.md +493 -0
  59. package/docs/language-pdas.md +198 -0
  60. package/docs/language-statements.md +620 -0
  61. package/docs/language-types.md +601 -0
  62. package/docs/language.md +190 -467
  63. package/docs/mainnet.md +103 -8
  64. package/docs/migrate-from-anchor.md +7 -6
  65. package/docs/security-model.md +4 -4
  66. package/docs/stability.md +64 -3
  67. package/docs/test-your-program.md +52 -15
  68. package/docs/testing.md +49 -2
  69. package/docs/troubleshooting.md +210 -42
  70. package/lib/typesol.d.ts +67 -22
  71. package/llms-full.txt +5084 -591
  72. package/llms.txt +12 -1
  73. package/package.json +4 -2
  74. package/releases/0.43.0.json +669 -0
  75. package/releases/0.44.0.json +672 -0
  76. package/releases/0.44.1.json +672 -0
  77. package/releases/0.45.0.json +732 -0
  78. package/runtime/LICENSE-compiler-builtins.txt +275 -0
  79. package/runtime/typesol_builtins.c +484 -0
  80. package/ts-plugin/index.js +16 -5
package/dist/cli.js CHANGED
@@ -6,8 +6,8 @@ import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { parseArgs } from "node:util";
8
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
+ import { build, CompileError, COMPILER_VERSION, describeToolchain, elfLength, generate, MEASURED_HOSTS, SBPF_VERSIONS, toolchainDifferences, verifyBinary, } from "./compiler/index.js";
10
+ import { setToolchainStrict, shortClang } from "./compiler/toolchain.js";
11
11
  import { generateCpi } from "./tools/cpigen.js";
12
12
  import { generatePort } from "./tools/portgen.js";
13
13
  import { generateClient, writeClient } from "./tools/clientgen.js";
@@ -15,8 +15,9 @@ import { buildIdl } from "./compiler/idl.js";
15
15
  import { base58, decodeAddress, loadOrCreateKeypair, readKeypair } from "./keys.js";
16
16
  import { formatProfile, profileLogs } from "./tools/profile.js";
17
17
  import { TEMPLATE_NAMES } from "./templates.js";
18
- import { addProgram, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, } from "./workspace.js";
19
- import { cliRpc, clusterUrl, deployPreflight, doctorChecks, formatChecks, INSTALL_AGAVE, rpcHost, solanaConfig as readSolanaConfig, toolchainCheck, } from "./tools/doctor.js";
18
+ import { addProgram, AGENT_FILES, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, withBuildLock, } from "./workspace.js";
19
+ import { chooseTypesolVersion, containerBuild, ensureImage, findReleaseRecord, needDocker, repeatCommand, shellQuote, sourceRevision, } from "./tools/docker.js";
20
+ import { cliRpc, clusterUrl, deployPreflight, doctorChecks, doctorSummary, formatChecks, isSignerUri, keypairFile, requirePayer, requireSolanaCli, rpcHost, solanaNotFound, solanaConfig as readSolanaConfig, toolchainCheck, } from "./tools/doctor.js";
20
21
  const ASSETS = fileURLToPath(new URL("../assets/", import.meta.url));
21
22
  /** A usage problem: printed with the command's help, exit code 2. */
22
23
  class UsageError extends Error {
@@ -42,6 +43,13 @@ function banner() {
42
43
  }
43
44
  const SBPF = `--sbpf v0|v1|v2 SBPF version (default v0, or "sbpf" in ${CONFIG}); v1/v2 need clusters that enabled them`;
44
45
  const TOOLCHAIN_STRICT = "--toolchain-strict refuse to build with platform-tools other than the tested ones (default: one warning); also TYPESOL_TOOLCHAIN=strict";
46
+ const DOCKER_HELP = [
47
+ "--docker build in the pinned container (docker/Dockerfile: linux/amd64, Agave 3.1.10 platform-tools v1.52,",
48
+ " the TypeSOL tarball checked against releases/<version>.json); the image is built locally the first time",
49
+ "--typesol-version <v> the TypeSOL version inside the container (default: this one; for verify, the deployed build's manifest's)",
50
+ "--release-record <file> the releases/<v>.json to check that version's tarball against (default: this package's, else the repository's)",
51
+ ].join("\n ");
52
+ const DOCKER_OPTIONS = { docker: { type: "boolean" }, "typesol-version": { type: "string" }, "release-record": { type: "string" } };
45
53
  const COMMANDS = {
46
54
  new: {
47
55
  usage: "typesol new <program> [--template counter|vault|escrow]",
@@ -67,15 +75,16 @@ const COMMANDS = {
67
75
  },
68
76
  },
69
77
  init: {
70
- usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
78
+ usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow] [--no-agent-files]",
71
79
  help: [
72
80
  "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors), AGENTS.md / CLAUDE.md / .cursor/rules (the rules for AI coding agents) and .mcp.json / .cursor/mcp.json (the TypeSOL MCP server).",
73
81
  "Refuses to overwrite files. <name> must be snake_case (default: derived from <dir>).",
74
82
  "--template counter a PDA counter per user (default)",
75
83
  "--template vault a SOL vault at a PDA: deposit, withdraw above rent, close",
76
84
  "--template escrow an SPL token escrow: make, take, refund, with the offer PDA signing for its vault",
85
+ "--no-agent-files leave out the files for AI coding agents (AGENTS.md, CLAUDE.md, .cursor/, .mcp.json)",
77
86
  ].join("\n "),
78
- options: { name: { type: "string" }, template: { type: "string" } },
87
+ options: { name: { type: "string" }, template: { type: "string" }, "no-agent-files": { type: "boolean" } },
79
88
  run(v, args) {
80
89
  if (args.length > 1)
81
90
  throw new UsageError("init takes at most one directory");
@@ -92,29 +101,39 @@ const COMMANDS = {
92
101
  .toLowerCase();
93
102
  const name = v.name ?? (/^[a-z]/.test(derived) ? derived : `p_${derived || "program"}`);
94
103
  const rel = path.relative(process.cwd(), root) || ".";
95
- for (const f of scaffold(root, name, template))
104
+ const agentFiles = !v["no-agent-files"];
105
+ for (const f of scaffold(root, name, template, { agentFiles }))
96
106
  log(` created ${path.join(rel, f)}`);
107
+ if (agentFiles)
108
+ log(` (${AGENT_FILES.join(", ")}: rules and the TypeSOL MCP server for AI coding agents; --no-agent-files leaves them out)`);
97
109
  const tools = toolchainCheck();
98
- if (!tools.ok)
99
- log(`\n ! The Solana platform-tools are not installed yet; npm test compiles with them. Install once:\n` +
100
- (tools.fix ?? []).map((f) => ` ${f}`).join("\n"));
110
+ if (!tools.ok) {
111
+ // With install commands: what is missing, then the commands. Without (TYPESOL_SBF_SDK names a directory that is
112
+ // not an SDK): the reason alone, which says what to fix.
113
+ const missing = tools.fix?.length ? tools.detail.replace(/ \(.*$/, "") : tools.detail;
114
+ log(`\n ! ${missing[0].toUpperCase()}${missing.slice(1)}; npm test compiles with the platform-tools.` +
115
+ (tools.fix?.length ? ` Install once:\n${tools.fix.map((f) => ` ${f}`).join("\n")}` : ""));
116
+ }
117
+ // No comment after a command: an interactive zsh would pass it to the command (it reads no comments by default).
101
118
  log(`\n next:\n` +
102
119
  (rel === "." ? "" : ` cd ${shellQuote(rel)}\n`) +
103
120
  ` npm install\n` +
104
- ` npm test # builds ${name} and runs its test in LiteSVM, a Solana runtime in-process\n` +
105
- ` npx --no-install typesol doctor # checks the toolchain, keypair and RPC before a deploy` +
121
+ ` npm test\n` +
122
+ ` npx --no-install typesol doctor\n\n` +
123
+ ` npm test builds ${name} and runs its test in LiteSVM, a Solana runtime in-process; doctor checks the toolchain, keypair and RPC before a deploy.` +
106
124
  (template === "counter" ? `\n\n other starters: typesol init <dir> --template vault (SOL at a PDA) or --template escrow (SPL token escrow)` : ""));
107
125
  return 0;
108
126
  },
109
127
  },
110
128
  build: {
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]",
129
+ usage: "typesol build [<program>…] [--sbpf v0|v1|v2] [--profile] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]]\n typesol build <program.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--docker …]",
112
130
  help: [
113
131
  `In a project (${CONFIG}): build every program, or the ones named, into <out>/<name>/ (.so, IDL .json, .client.ts, .c, .build.json).`,
114
132
  "Outside a project, or with a .ts file: build that file (its keypair is created next to the output if needed).",
115
133
  SBPF,
116
134
  "--profile log a marker and the remaining compute units before every statement (for `typesol profile`; not for release)",
117
135
  TOOLCHAIN_STRICT,
136
+ DOCKER_HELP,
118
137
  "--quiet no banner",
119
138
  ].join("\n "),
120
139
  options: {
@@ -124,8 +143,9 @@ const COMMANDS = {
124
143
  "program-id": { type: "string" },
125
144
  quiet: { type: "boolean" },
126
145
  "toolchain-strict": { type: "boolean" },
146
+ ...DOCKER_OPTIONS,
127
147
  },
128
- run(v, args) {
148
+ async run(v, args) {
129
149
  if (v["toolchain-strict"])
130
150
  setToolchainStrict();
131
151
  const sbpf = sbpfOf(v);
@@ -134,11 +154,28 @@ const COMMANDS = {
134
154
  const file = args.length === 1 && args[0].endsWith(".ts") ? args[0] : undefined;
135
155
  // A .ts that is one of the project's programs builds as that program (same keypair, output and settings).
136
156
  const inProject = ws && (file ? programForEntry(ws, file) : undefined);
157
+ dockerOptions(v);
137
158
  if (ws && (!file || inProject)) {
138
159
  if (v.out || v["program-id"])
139
160
  throw new UsageError(`--out and --program-id do not apply to programs of ${CONFIG} (use "out" there; keypairs live in <out>/deploy/)`);
140
161
  if (!v.quiet && process.stdout.isTTY)
141
162
  log(banner());
163
+ if (v.docker) {
164
+ const image = await buildImage(v, ws.root);
165
+ const progs = (inProject ? [inProject] : names(ws, args)).map((name) => programPaths(ws, name));
166
+ // The same locks as a local build: another process building one of these programs would write the same files.
167
+ const { jobs, built } = withBuildLocks(progs.map((p) => p.outDir), () => {
168
+ const jobs = progs.map((paths) => ({ paths, ...programAddress(ws, paths.name) }));
169
+ const built = containerBuild(image, ws.root, jobs.map((j) => ({ entry: j.paths.entry, outDir: j.paths.outDir, address: j.address, sbpf: sbpf ?? ws.sbpf, profile })));
170
+ return { jobs, built };
171
+ });
172
+ built.forEach((r, i) => {
173
+ const j = jobs[i];
174
+ log(` ${j.paths.name.padEnd(12)} ${j.address}${j.created ? " (new keypair)" : j.keyless ? " (no keypair here: deploying needs it)" : ""} ${path.relative(process.cwd(), r.soPath)}`);
175
+ });
176
+ log(containerLine(image));
177
+ return 0;
178
+ }
142
179
  for (const b of buildWorkspace(ws, inProject ? [inProject] : names(ws, args), { sbpf, profile }))
143
180
  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)}`);
144
181
  return 0;
@@ -151,23 +188,36 @@ const COMMANDS = {
151
188
  if (!v.quiet && process.stdout.isTTY)
152
189
  log(banner());
153
190
  const outDir = v.out ?? path.join(path.dirname(file), "target");
154
- const { model } = generate(file);
191
+ // The program is named after its entry file. With --docker the container's TypeSOL compiles it, not this one.
192
+ const name = v.docker ? path.basename(file).replace(/\.ts$/, "") : generate(file).model.name;
155
193
  const given = v["program-id"];
156
194
  // A keypair given by name must be there: creating one in its place would give the program a new address.
157
195
  if (given !== undefined && !existsSync(given))
158
196
  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`);
197
+ const keyFile = given ?? path.join(outDir, `${name}-keypair.json`);
198
+ const image = v.docker ? await buildImage(v, ws?.root) : undefined;
160
199
  mkdirSync(path.dirname(keyFile), { recursive: true });
161
200
  const { address, created } = loadOrCreateKeypair(keyFile);
162
- const res = build(file, outDir, address, { sbpf: sbpf ?? "v0", profile });
163
- const client = writeClient(res.idl, path.join(outDir, `${model.name}.client.ts`));
164
- log(` program ${model.name}`);
201
+ let res;
202
+ if (image) {
203
+ // The container sees the entry's directory: the program and the files it imports from there.
204
+ const [r] = containerBuild(image, path.dirname(path.resolve(file)), [{ entry: file, outDir, address, sbpf: sbpf ?? "v0", profile }]);
205
+ res = { soPath: r.soPath, idlPath: path.join(outDir, `${name}.json`), manifestPath: r.manifestPath };
206
+ }
207
+ else {
208
+ const local = build(file, outDir, address, { sbpf: sbpf ?? "v0", profile });
209
+ writeClient(local.idl, path.join(outDir, `${name}.client.ts`));
210
+ res = local;
211
+ }
212
+ log(` program ${name}`);
165
213
  log(` address ${address}${created ? " (new keypair: keep it, it is the program's address)" : ""}`);
166
214
  log(` binary ${res.soPath}`);
167
215
  log(` idl ${res.idlPath}`);
168
- log(` client ${client.path}`);
216
+ log(` client ${path.join(outDir, `${name}.client.ts`)}`);
169
217
  log(` manifest ${res.manifestPath}`);
170
218
  log(`\n deploy: solana program deploy ${shellQuote(res.soPath)} --program-id ${shellQuote(keyFile)}`);
219
+ if (image)
220
+ log(containerLine(image));
171
221
  return 0;
172
222
  },
173
223
  },
@@ -236,7 +286,7 @@ const COMMANDS = {
236
286
  if (v.config !== undefined)
237
287
  solanaConfig(v.config); // a --config that does not exist is a usage error, as elsewhere
238
288
  const checks = await doctorChecks({ cwd: process.cwd(), url: v.url, config: v.config });
239
- log(formatChecks(checks));
289
+ log(`${formatChecks(checks)}\n\n ${doctorSummary(checks)}`);
240
290
  return checks.some((c) => !c.ok && !c.optional) ? 1 : 0;
241
291
  },
242
292
  },
@@ -265,10 +315,15 @@ const COMMANDS = {
265
315
  // Without either, `solana program deploy` would pick its own default cluster (mainnet-beta): never silently.
266
316
  if (!url && !v["dry-run"])
267
317
  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`)");
318
+ const payer = v.keypair ?? cfg.keypair ?? path.join(os.homedir(), ".config/solana/id.json");
319
+ if (url && !v["dry-run"]) {
320
+ // Before the build: the Solana CLI that sends it, then a payer keypair file (with the command that creates one).
321
+ requireSolanaCli();
322
+ requirePayer(clusterUrl(url), payer, v.keypair !== undefined ? { from: "flag" } : cfg.keypair !== undefined ? { from: "config", config: cfg.file } : { from: "default" });
323
+ }
268
324
  const built = buildWorkspace(ws, names(ws, args), { sbpf: sbpfOf(v), needKeypair: true });
269
325
  if (url && !v["dry-run"]) {
270
326
  // Before any transaction: the RPC answers and the payer can afford it, with what to do if not.
271
- const payer = v.keypair ?? cfg.keypair ?? path.join(os.homedir(), ".config/solana/id.json");
272
327
  await deployPreflight({
273
328
  url: clusterUrl(url),
274
329
  payer,
@@ -288,7 +343,7 @@ const COMMANDS = {
288
343
  }
289
344
  catch (e) {
290
345
  if (e.code === "ENOENT")
291
- throw new Error(`\`solana\` was not found on PATH. Install the Agave CLI: ${INSTALL_AGAVE}`);
346
+ throw new Error(solanaNotFound());
292
347
  throw new Error(`solana program deploy failed for ${b.paths.name} (see its output above)`);
293
348
  }
294
349
  }
@@ -449,7 +504,7 @@ const COMMANDS = {
449
504
  },
450
505
  },
451
506
  verify: {
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>]",
507
+ 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>] [--docker [--typesol-version <v>] [--release-record <file>]]",
453
508
  help: [
454
509
  "Rebuild and compare with what is deployed. Exit 0 on a match, 3 on a mismatch.",
455
510
  "With a .so (e.g. from `solana program dump`): compare with that file.",
@@ -462,9 +517,20 @@ const COMMANDS = {
462
517
  "manifest whose binary hash is the deployed one's (--manifest, <deployed>.build.json next to a given .so, or the",
463
518
  "local build's). A program on chain carries no record of what built it: keep the .build.json with the deployment.",
464
519
  "--manifest <file> the <name>.build.json of the build that was deployed",
520
+ "With --docker the rebuild runs in the pinned container, with the TypeSOL version of the deployed build's manifest",
521
+ "(when one is known) unless --typesol-version is given; on a match it prints what was verified, for anyone to repeat.",
522
+ DOCKER_HELP,
465
523
  ].join("\n "),
466
- options: { sbpf: { type: "string" }, address: { type: "string" }, url: { type: "string" }, config: { type: "string" }, manifest: { type: "string" } },
524
+ options: {
525
+ sbpf: { type: "string" },
526
+ address: { type: "string" },
527
+ url: { type: "string" },
528
+ config: { type: "string" },
529
+ manifest: { type: "string" },
530
+ ...DOCKER_OPTIONS,
531
+ },
467
532
  async run(v, args) {
533
+ dockerOptions(v);
468
534
  if (args.length < 1 || args.length > 2)
469
535
  throw new UsageError("verify takes the program and, optionally, the deployed .so");
470
536
  const [target, deployedPath] = args;
@@ -503,31 +569,48 @@ const COMMANDS = {
503
569
  // ELF e_flags (offset 0x30) hold the SBPF version: 0 for v0, 1 for v1, 2 for v2.
504
570
  const flags = deployed.length > 0x34 && deployed.readUInt32BE(0) === 0x7f454c46 ? deployed.readUInt32LE(0x30) : 0;
505
571
  const sbpf = sbpfOf(v) ?? SBPF_VERSIONS[flags] ?? "v0";
572
+ const programName = path.basename(entry).replace(/\.ts$/, "");
573
+ // The rebuild's own output directory is temporary; the local build's manifest sits in the usual place.
574
+ const local = ws && name ? programPaths(ws, name).outDir : path.join(path.dirname(entry), "target");
575
+ const candidates = [
576
+ v.manifest,
577
+ deployedPath ? deployedPath.replace(/\.so$/, "") + ".build.json" : undefined,
578
+ path.join(local, `${programName}.build.json`),
579
+ ].filter((f) => !!f);
580
+ const known = buildManifests(deployed, candidates);
581
+ const address = onChain?.address ?? "11111111111111111111111111111111";
506
582
  const dir = mkdtempSync(path.join(os.tmpdir(), "typesol-verify-"));
507
- let res, same;
583
+ let rebuilt, idl, same;
584
+ let image;
585
+ let root;
508
586
  try {
509
- res = build(entry, dir, onChain?.address ?? "11111111111111111111111111111111", { sbpf });
510
- same = verifyBinary(deployed, readFileSync(res.soPath));
587
+ if (v.docker) {
588
+ image = await buildImage(v, ws?.root, known.deployed ? { version: known.deployed.manifest.compiler, from: relPath(known.deployed.file) } : undefined);
589
+ root = ws && name ? ws.root : path.dirname(path.resolve(entry));
590
+ const [r] = containerBuild(image, root, [{ entry, outDir: dir, address, sbpf }]);
591
+ rebuilt = r.manifest;
592
+ idl = JSON.parse(readFileSync(path.join(dir, `${r.name}.json`), "utf8"));
593
+ same = verifyBinary(deployed, readFileSync(r.soPath));
594
+ }
595
+ else {
596
+ const res = build(entry, dir, address, { sbpf });
597
+ rebuilt = res.manifest;
598
+ idl = res.idl;
599
+ same = verifyBinary(deployed, readFileSync(res.soPath));
600
+ }
511
601
  }
512
602
  finally {
513
603
  rmSync(dir, { recursive: true, force: true });
514
604
  }
515
605
  const what = deployedPath ??
516
606
  `${onChain.address} (${onChain.info.dataAccount === onChain.address ? "" : `data ${onChain.info.dataAccount}, `}loader ${onChain.info.loader})`;
517
- log(same
518
- ? ` match ${res.manifest.binary} (sbpf ${sbpf})`
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))
607
+ log(same ? ` match ${rebuilt.binary} (sbpf ${sbpf})` : ` MISMATCH ${what} is not what ${entry} builds to (${rebuilt.binary}, sbpf ${sbpf})`);
608
+ if (same && image && root)
609
+ for (const line of verifiedLines({ what, entry, root, rebuilt, image, args, v }))
610
+ log(line);
611
+ if (!same)
612
+ for (const line of toolchainHint(rebuilt, known, !!v.manifest))
529
613
  log(line);
530
- }
531
614
  if (!onChain)
532
615
  return same ? 0 : 3;
533
616
  const { info } = onChain;
@@ -549,7 +632,7 @@ const COMMANDS = {
549
632
  log(` IDL ERROR the IDL at ${at} could not be read: ${e.message}`);
550
633
  return 3;
551
634
  }
552
- const idlSame = canonicalJson(published) === canonicalJson(res.idl);
635
+ const idlSame = canonicalJson(published) === canonicalJson(idl);
553
636
  log(idlSame
554
637
  ? " idl match: the published IDL is the one the source builds"
555
638
  : " IDL MISMATCH the published IDL differs from the one the source builds");
@@ -672,16 +755,13 @@ function mustExist(file) {
672
755
  return file;
673
756
  }
674
757
  /**
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.
758
+ * The build manifests among `candidates` (files that may not exist): the one whose binary hash is the deployed bytes'
759
+ * (it describes the deployed build), and the others, which describe other binaries (an older local build).
678
760
  */
679
- function toolchainHint(rebuilt, deployed, candidates, explicit) {
680
- const lines = [` rebuilt ${describeToolchain(rebuilt)}`];
761
+ function buildManifests(deployed, candidates) {
681
762
  const deployedHash = createHash("sha256")
682
763
  .update(deployed.subarray(0, elfLength(deployed)))
683
764
  .digest("hex");
684
- let other;
685
765
  const unrelated = [];
686
766
  for (const file of [...new Set(candidates.map((c) => path.resolve(c)))]) {
687
767
  if (!existsSync(file))
@@ -695,33 +775,114 @@ function toolchainHint(rebuilt, deployed, candidates, explicit) {
695
775
  }
696
776
  if (typeof manifest?.clang !== "string" || typeof manifest.binary !== "string")
697
777
  continue;
698
- if (manifest.binary === deployedHash) {
699
- other = { file, manifest };
700
- break;
701
- }
778
+ if (manifest.binary === deployedHash)
779
+ return { deployed: { file, manifest }, unrelated };
702
780
  unrelated.push({ file, manifest });
703
781
  }
704
- const rel = (f) => path.relative(process.cwd(), f) || f;
782
+ return { unrelated };
783
+ }
784
+ /** A path as the user would type it here: relative below the working directory, absolute elsewhere. */
785
+ const relPath = (f) => {
786
+ const rel = path.relative(process.cwd(), f);
787
+ return !rel ? f : rel.startsWith("..") || path.isAbsolute(rel) ? path.resolve(f) : rel;
788
+ };
789
+ /**
790
+ * After a verify mismatch: the toolchain of the rebuild and, when a build manifest describes the deployed bytes (its
791
+ * binary hash is theirs), of the deployed build, and what differs. A manifest that describes other bytes (an older
792
+ * local build) is only mentioned: its toolchain says nothing about the deployed binary.
793
+ */
794
+ function toolchainHint(rebuilt, known, explicit) {
795
+ const lines = [` rebuilt ${describeToolchain(rebuilt)}`];
796
+ const other = known.deployed;
705
797
  if (other) {
706
- lines.push(` deployed ${describeToolchain(other.manifest)} (${rel(other.file)}, whose binary hash is the deployed one's)`);
798
+ lines.push(` deployed ${describeToolchain(other.manifest)} (${relPath(other.file)}, whose binary hash is the deployed one's)`);
707
799
  const diff = toolchainDifferences(rebuilt, other.manifest);
800
+ const why = diff.includes("clang")
801
+ ? "another clang can compile the same C to other bytes; "
802
+ : diff.includes("host")
803
+ ? "the host may be the cause if the program uses 128-bit or signed division: before 0.45.0 those linked platform-tools' compiler-builtins, laid out differently by each host package; "
804
+ : diff.includes("host (not measured)")
805
+ ? `the same bytes on another host were measured only on ${MEASURED_HOSTS.join(", ")}; `
806
+ : "";
807
+ const fix = diff.length === 1 && diff[0].startsWith("host")
808
+ ? other.manifest.container
809
+ ? "rebuild with --docker, as the deployed build was"
810
+ : `rebuild on a ${other.manifest.host.os}-${other.manifest.host.arch} host, or deploy a --docker build so that anyone can rebuild it`
811
+ : `rebuild with the deployed side's ${diff.join(" and ")} to compare like with like`;
708
812
  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`
813
+ ? ` differs ${diff.join(", ")}: ${why}${fix}`
710
814
  : " same toolchain and compiler versions on both sides: the sources (or an import, or the runtime header) differ");
711
815
  return lines;
712
816
  }
713
817
  lines.push(" deployed toolchain unknown: a deployed program records nothing about what built it" +
714
818
  (explicit ? "" : "; pass --manifest <name>.build.json, kept from the build that was deployed"));
715
- for (const u of unrelated) {
819
+ for (const u of known.unrelated) {
716
820
  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)})` +
821
+ lines.push(` note ${relPath(u.file)} describes another binary (${u.manifest.binary.slice(0, 12)}…, ${describeToolchain(u.manifest)})` +
718
822
  (diff.length ? `; it differs from the rebuild in ${diff.join(", ")}` : ""));
719
823
  }
720
824
  return lines;
721
825
  }
722
- /** Quote a command-line word for a POSIX shell when it needs it. */
723
- function shellQuote(s) {
724
- return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
826
+ /** After a container verify matched: what was verified, in terms a third party can repeat. */
827
+ function verifiedLines(o) {
828
+ const id = o.image.identity;
829
+ const rev = sourceRevision(o.root);
830
+ return [
831
+ ` verified ${o.what} is what ${relPath(path.resolve(o.entry))} builds to in the pinned build container:`,
832
+ ` source ${o.root}${rev ? ` (git ${rev.commit}${rev.clean ? "" : ", with uncommitted changes"})` : " (not a git checkout)"}`,
833
+ ` TypeSOL ${id.typesol.version}, npm tarball shasum ${id.typesol.shasum}, as releases/${id.typesol.version}.json records it (the record names commit ${id.typesol.commit})`,
834
+ ` record ${recordLine(id.typesol.record) ?? `releases/${id.typesol.version}.json`}`,
835
+ ...(id.deps
836
+ ? [
837
+ ` deps ${id.deps.path} sha256 ${id.deps.sha256} (${id.deps.source === "package" ? "this package's" : "the checked tarball's"}), installed with npm ci`,
838
+ ]
839
+ : []),
840
+ ` toolchain ${shortClang(o.rebuilt.clang)}, platform-tools ${o.rebuilt.platformTools ?? "unknown"}, TypeScript ${o.rebuilt.typescript}`,
841
+ ` container ${id.platform}, Dockerfile sha256 ${id.dockerfile}, local image ${id.image}`,
842
+ ...id.base.map((b) => ` base ${b}`),
843
+ ...id.downloads.map((d) => ` download ${d.url.split("/").pop()} sha256 ${d.sha256}`),
844
+ ` repeat ${repeatCommand(o.args, o.v, id.typesol.version)}`,
845
+ ];
846
+ }
847
+ /** Where a container build's release record came from, in one line. */
848
+ function recordLine(r) {
849
+ if (!r)
850
+ return undefined;
851
+ const where = r.kind === "package"
852
+ ? `${r.location} in this package`
853
+ : r.kind === "file"
854
+ ? `${r.location} (--release-record)`
855
+ : `${r.location} (the repository's main branch)`;
856
+ return `${where}, sha256 ${r.sha256}`;
857
+ }
858
+ /** --typesol-version and --release-record only mean something with --docker. */
859
+ function dockerOptions(v) {
860
+ for (const o of ["typesol-version", "release-record"])
861
+ if (v[o] !== undefined && !v.docker)
862
+ throw new UsageError(`--${o} applies to container builds: add --docker`);
863
+ }
864
+ /**
865
+ * The build image for --docker, built first if needed, with the TypeSOL version chosen for it (said on stderr). The
866
+ * version's release record is this package's, the --release-record file, or (a release newer than this package) the
867
+ * repository's.
868
+ */
869
+ async function buildImage(v, projectRoot, deployed) {
870
+ const { version, why } = chooseTypesolVersion({ given: v["typesol-version"], deployed, projectRoot, cliVersion: COMPILER_VERSION });
871
+ needDocker(); // before any download: without Docker there is nothing to check a record for
872
+ const found = await findReleaseRecord(version, { file: v["release-record"] });
873
+ const image = ensureImage(version, found);
874
+ console.error(` container ${image.tag}: TypeSOL ${version} (${why}), ${image.identity.platform}`);
875
+ return image;
876
+ }
877
+ /** The container build's environment in one line, for the build's report. */
878
+ function containerLine(image) {
879
+ const id = image.identity;
880
+ return ` built in ${id.platform} container ${image.tag} (Dockerfile sha256 ${id.dockerfile.slice(0, 16)}…, TypeSOL ${id.typesol.version} tarball ${id.typesol.shasum}${id.deps ? `, dependency lock ${id.deps.sha256.slice(0, 16)}…` : ""}); recorded in each .build.json`;
881
+ }
882
+ /** Hold the build lock of every directory while `fn` runs (one container builds them all). */
883
+ function withBuildLocks(dirs, fn) {
884
+ const [first, ...rest] = [...new Set(dirs)].sort();
885
+ return first === undefined ? fn() : withBuildLock(first, () => withBuildLocks(rest, fn));
725
886
  }
726
887
  function one(args, what) {
727
888
  if (args.length !== 1)
@@ -757,7 +918,10 @@ function readJson(file) {
757
918
  }
758
919
  }
759
920
  /** The address of a payer keypair file, for the line printed before a deploy (or why there is none). */
760
- function payerAddress(file) {
921
+ function payerAddress(payer) {
922
+ if (isSignerUri(payer))
923
+ return `${payer} (a signer the Solana CLI resolves)`;
924
+ const file = keypairFile(payer);
761
925
  if (!existsSync(file))
762
926
  return `none at ${file} (the Solana CLI will refuse)`;
763
927
  try {
@@ -772,7 +936,7 @@ function solanaConfig(file) {
772
936
  const cfg = readSolanaConfig(file);
773
937
  if (file && !cfg.exists)
774
938
  throw new UsageError(`${file} does not exist`);
775
- return { url: cfg.url, keypair: cfg.keypair };
939
+ return { url: cfg.url, keypair: cfg.keypair, file: cfg.file };
776
940
  }
777
941
  export async function main(argv) {
778
942
  const [cmd, ...rest] = argv;
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
5
5
  import { CompileError, Reporter, markAliasUse } from "./diagnostics.js";
6
6
  import { decodeAddress } from "../keys.js";
7
7
  import { borshIdentical } from "./emit/borsh.js";
8
- import { hintForTypeScript, unsupportedSyntax } from "./hints.js";
8
+ import { MAX_SEEDS } from "./emit/shared.js";
9
+ import { ASYNC_HINT, fieldTypeHint, hintForTypeScript, messageForTypeScript, unsupportedSyntax } from "./hints.js";
9
10
  import { optionKey, INT_INFO, INT_NAMES, scalarKey, fixedVecName, isScalar, scalarSize, typeName, } from "./model.js";
10
11
  export const LIB_PATH = fileURLToPath(new URL("../../lib/typesol.d.ts", import.meta.url));
11
12
  /** Names a struct field may not use because account parameters already expose them. */
@@ -272,7 +273,8 @@ function typecheck(entry, files) {
272
273
  const diagnostics = tsDiagnostics.map((d) => {
273
274
  const flat = ts.flattenDiagnosticMessageText(d.messageText, "\n");
274
275
  const hint = hintForTypeScript(d, flat, LIB_PATH);
275
- const message = hint ? `${flat}\nhint: ${hint}` : flat;
276
+ const shown = messageForTypeScript(d, flat);
277
+ const message = hint ? `${shown}\nhint: ${hint}` : shown;
276
278
  const extra = hint ? { hint } : {};
277
279
  if (!d.file || d.start === undefined)
278
280
  return { file: entry, line: 1, column: 1, message, ...extra };
@@ -443,6 +445,50 @@ export function analyze(entry, files) {
443
445
  if (isError) {
444
446
  // String enum: program errors, codes 6000+ in declaration order (imported files first).
445
447
  const members = new Map();
448
+ // A doc comment belongs to the member that starts on a later line. `A = "a", /** @code 6200 */ B = "b"`
449
+ // leaves the tag on no member (TypeScript reads it as trailing A's comma), so B would silently take the
450
+ // next code: refuse it instead, and a tag in a comment that is not a doc comment, or in a doc comment that
451
+ // another one follows (only the last is read). In a doc comment, as TypeScript reads it, a tag is any
452
+ // `@code` after the start, whitespace or `*` (`/** The second. @code 6200 */` is one); in a // or /* … */
453
+ // comment, only one first on a line of the comment is reported, so prose (`// see the @code docs`) is not.
454
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, file.text);
455
+ scanner.resetTokenState(stmt.members.pos);
456
+ const isDoc = (text) => text.startsWith("/**") && text !== "/**/";
457
+ const tagged = (text) => isDoc(text) ? /(?:^|[\s*])@code\b/.test(text) : /^\/[*/]\**\s*@code\b/.test(text) || /\n\s*\*?\s*@code\b/.test(text);
458
+ // A tag above the enum itself numbers no member: refused, not ignored.
459
+ for (const r of ts.getLeadingCommentRanges(file.text, stmt.pos) ?? []) {
460
+ const text = file.text.slice(r.pos, r.end);
461
+ if (r.kind === ts.SyntaxKind.MultiLineCommentTrivia && isDoc(text) && tagged(text)) {
462
+ const first = stmt.members[0] ? `, ${stmt.members[0].name.getText(file)}` : "";
463
+ reporter.fail(stmt.name, `this @code tag is not read: a tag above the enum numbers no member; put /** @code … */ above its first member${first}`);
464
+ }
465
+ }
466
+ for (let k = scanner.scan(); k !== ts.SyntaxKind.EndOfFileToken && scanner.getTokenStart() < stmt.end; k = scanner.scan()) {
467
+ if (k !== ts.SyntaxKind.MultiLineCommentTrivia && k !== ts.SyntaxKind.SingleLineCommentTrivia)
468
+ continue;
469
+ const text = scanner.getTokenText();
470
+ if (!tagged(text))
471
+ continue;
472
+ const at = scanner.getTokenStart();
473
+ const next = stmt.members.find((m) => m.getStart(file) > at);
474
+ const above = next ? `above ${next.name.getText(file)}` : "above the member it numbers";
475
+ const doc = k === ts.SyntaxKind.MultiLineCommentTrivia && isDoc(text);
476
+ if (!doc) {
477
+ reporter.fail(next ?? stmt, `this @code tag is not read: only a doc comment (/** … */) is, not a ${text.startsWith("//") ? "// comment" : "/* … */ comment"}; write /** @code … */ ${above}`);
478
+ continue;
479
+ }
480
+ const docs = next ? ts.getJSDocCommentsAndTags(next).filter((d) => ts.isJSDoc(d)) : [];
481
+ if (docs.some((d) => d.getStart(file) === at))
482
+ continue;
483
+ const lineStart = file.text.lastIndexOf("\n", at - 1) + 1;
484
+ reporter.fail(next ?? stmt, !next
485
+ ? "this @code tag is not read: it follows the last member; put /** @code … */ on its own line above the member it numbers"
486
+ : file.text.slice(lineStart, at).trim()
487
+ ? `this @code tag is not read: other code comes before it on its line; put /** @code … */ on its own line ${above}`
488
+ : docs.some((d) => d.getStart(file) > at)
489
+ ? `this @code tag is not read: another doc comment follows it, and only the last one above ${next.name.getText(file)} is read; put the tag in that one`
490
+ : `this @code tag is not read; put /** @code … */ on its own line ${above}`);
491
+ }
446
492
  for (const m of stmt.members) {
447
493
  if (!m.initializer || !ts.isStringLiteral(m.initializer))
448
494
  reporter.fail(m, 'error enum members need a string message: Name = "message"');
@@ -1587,7 +1633,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1587
1633
  }
1588
1634
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && names.has(node.typeName.text) && !targs.length)
1589
1635
  return { kind: "struct", name: node.typeName.text };
1590
- reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct");
1636
+ reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct", fieldTypeHint(node));
1591
1637
  };
1592
1638
  // `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
1593
1639
  // elements are the account's remaining bytes; T is a scalar or a fixed-size struct.
@@ -2071,9 +2117,9 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2071
2117
  if (!fn.body)
2072
2118
  reporter.fail(fn, "helper functions need a body");
2073
2119
  if (fn.asteriskToken)
2074
- reporter.fail(fn, "helper functions cannot be generators");
2120
+ reporter.fail(fn, "helper functions cannot be generators", ASYNC_HINT);
2075
2121
  if ((ts.getModifiers(fn) ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
2076
- reporter.fail(fn, "helper functions cannot be async");
2122
+ reporter.fail(fn, "helper functions cannot be async", ASYNC_HINT);
2077
2123
  if (!fn.type)
2078
2124
  reporter.fail(fn.name ?? fn, "helper functions need an explicit return type (void, an integer, boolean, Pubkey or a struct)");
2079
2125
  let returns = fn.type.kind === ts.SyntaxKind.VoidKeyword
@@ -2325,7 +2371,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
2325
2371
  if (fn.typeParameters?.length)
2326
2372
  reporter.fail(fn, "instructions cannot be generic");
2327
2373
  if (fn.asteriskToken || (ts.getModifiers(fn) ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
2328
- reporter.fail(fn, "instructions cannot be async or generators");
2374
+ reporter.fail(fn, "instructions cannot be async or generators", ASYNC_HINT);
2329
2375
  let returns;
2330
2376
  if (fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword) {
2331
2377
  returns = fn.type.kind === ts.SyntaxKind.StringKeyword ? { kind: "string" } : resolveScalarType(fn.type, scope);
@@ -2751,6 +2797,11 @@ function unwrapConstraints(node, reporter, imports, out) {
2751
2797
  const program = args[3] ? lit(args[3])[0] : undefined;
2752
2798
  if (program && !program.startsWith("@") && !decodeAddress(program))
2753
2799
  reporter.fail(args[3], `Seeds program: "${program}" is neither "@param" nor a base58 address`);
2800
+ // The same limits as a seed list in code: a stored bump ends the list, a canonical one the derivation adds.
2801
+ if (bump !== undefined && names.length + 1 > MAX_SEEDS)
2802
+ reporter.fail(tuple, `at most ${MAX_SEEDS} seeds, the bump included (Solana's limit)`);
2803
+ if (bump === undefined && names.length > MAX_SEEDS - 1)
2804
+ reporter.fail(tuple, `at most ${MAX_SEEDS - 1} seeds: the bump the derivation adds makes ${MAX_SEEDS}, Solana's limit`);
2754
2805
  out.seeds = { names, bump, program };
2755
2806
  }
2756
2807
  if (!args[0])
@@ -15,12 +15,13 @@ export declare class CompileError extends Error {
15
15
  }
16
16
  export declare function formatDiagnostic(d: Diagnostic): string;
17
17
  export declare function markAliasUse(copy: ts.Node, use: ts.Node): void;
18
- export declare function diagnosticAt(node: ts.Node, message: string): Diagnostic;
18
+ export declare function diagnosticAt(node: ts.Node, message: string, hint?: string): Diagnostic;
19
19
  /** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
20
20
  export declare class Reporter {
21
21
  readonly diagnostics: Diagnostic[];
22
- error(node: ts.Node, message: string): void;
23
- fail(node: ts.Node, message: string): never;
22
+ /** `hint`: what to write instead, shown as the message's last line ("hint: …") and given to tools as `hint`. */
23
+ error(node: ts.Node, message: string, hint?: string): void;
24
+ fail(node: ts.Node, message: string, hint?: string): never;
24
25
  /** Run `fn`, swallowing a `fail` so analysis can continue with the next construct. */
25
26
  guard<T>(fn: () => T): T | undefined;
26
27
  throwIfAny(): void;