@typesol/cli 0.42.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 (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  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 +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/dist/ai.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** The rules every TypeSOL program follows that a model trained on ordinary TypeScript gets wrong first. */
2
- export declare const AGENT_RULES = "## Writing TypeSOL\n\nTypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live\nin `programs/`, tests in `tests/`; `typesol.json` lists the programs.\n\n- Exported functions are instructions; their parameters are the accounts (`Signer`, `Account<T>`, `Mut<T>`,\n `Init<T>`, token accounts, programs) and then the arguments. Account data types are exported interfaces.\n- Integers are bigint: `u8` \u2026 `u128`, `i8` \u2026 `i128` (write `1n`, never `1`; take `u64`, never `number`).\n Arithmetic is checked: an overflow fails the instruction. There is no floating point.\n- Import everything from `\"typesol\"`: types, and functions such as `require`, `log`, `min`, `max`,\n `fixedArray`, `emit`, `invoke`.\n- Fail with `require(condition, MyError.Name)` (an exported string enum of messages) or `require(condition, \"message\")`.\n There is no `throw`, `try`, `async`, `class`, `console` or `Math`.\n- An account the instruction changes is `Mut<T>`; one it creates is `Init<T>` (`acct.create(payer, seeds)`).\n- Lists: `FixedArray<T, N>`, `FixedVec<T, N>`, `Vec<T>`; read with `.get(i)` and write with `.set(i, v)`\n (`i` a bigint), not `xs[i]`. `map`, `filter`, `find`, `some`, `reduce` work on them.\n- Strings are `FixedString<N>` in account data; `Option<T>` (`T | null`) for optional values.\n\n## Checking your work\n\n- `npx typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a\n `hint` that says what to write instead. Fix those first; they are faster than a build.\n- `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx typesol build`\n writes `target/<name>/`: the `.so`, the IDL and a typed client.\n- The MCP server (`npx typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,\n the IDL and the docs as tools.\n- The language reference: `node_modules/typesol/docs/language.md`, or https://typesol.com/llms-full.txt.\n";
2
+ export declare const AGENT_RULES = "## Writing TypeSOL\n\nTypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live\nin `programs/`, tests in `tests/`; `typesol.json` lists the programs.\n\n- Exported functions are instructions; their parameters are the accounts (`Signer`, `Account<T>`, `Mut<T>`,\n `Init<T>`, token accounts, programs) and then the arguments. Account data types are exported interfaces.\n- Integers are bigint: `u8` \u2026 `u128`, `i8` \u2026 `i128` (write `1n`, never `1`; take `u64`, never `number`).\n Arithmetic is checked: an overflow fails the instruction. There is no floating point.\n- Import everything from `\"typesol\"`: types, and functions such as `require`, `log`, `min`, `max`,\n `fixedArray`, `emit`, `invoke`.\n- Fail with `require(condition, MyError.Name)` (an exported string enum of messages) or `require(condition, \"message\")`.\n There is no `throw`, `try`, `async`, `class`, `console` or `Math`.\n- An account the instruction changes is `Mut<T>`; one it creates is `Init<T>` (`acct.create(payer, seeds)`).\n- Lists: `FixedArray<T, N>`, `FixedVec<T, N>`, `Vec<T>`; read with `.get(i)` and write with `.set(i, v)`\n (`i` a bigint), not `xs[i]`. `map`, `filter`, `find`, `some`, `reduce` work on them.\n- Strings are `FixedString<N>` in account data; `Option<T>` (`T | null`) for optional values.\n\n## Checking your work\n\n- `npx --no-install typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a\n `hint` that says what to write instead. Fix those first; they are faster than a build.\n- `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx --no-install typesol build`\n writes `target/<name>/`: the `.so`, the IDL and a typed client.\n- The MCP server (`npx --no-install typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,\n the IDL and the docs as tools.\n- The language reference: `node_modules/typesol/docs/language.md` (after `npm install`), or https://typesol.com/llms-full.txt.\n";
3
3
  /** AGENTS.md for a new project (Codex, Cursor, Zed, and other agents that read it). */
4
4
  export declare function agentsMd(name: string): string;
5
5
  /** Claude Code reads CLAUDE.md, which imports AGENTS.md so the rules are kept in one place. */
package/dist/ai.js CHANGED
@@ -21,13 +21,13 @@ in \`programs/\`, tests in \`tests/\`; \`typesol.json\` lists the programs.
21
21
 
22
22
  ## Checking your work
23
23
 
24
- - \`npx typesol check\` (or \`--json\`) type-checks every program and lists what TypeSOL refuses, each error with a
24
+ - \`npx --no-install typesol check\` (or \`--json\`) type-checks every program and lists what TypeSOL refuses, each error with a
25
25
  \`hint\` that says what to write instead. Fix those first; they are faster than a build.
26
- - \`npm test\` builds the programs and runs \`tests/\` in LiteSVM (an in-process Solana runtime). \`npx typesol build\`
26
+ - \`npm test\` builds the programs and runs \`tests/\` in LiteSVM (an in-process Solana runtime). \`npx --no-install typesol build\`
27
27
  writes \`target/<name>/\`: the \`.so\`, the IDL and a typed client.
28
- - The MCP server (\`npx typesol mcp\`, configured in \`.mcp.json\` and \`.cursor/mcp.json\`) gives the same check,
28
+ - The MCP server (\`npx --no-install typesol mcp\`, configured in \`.mcp.json\` and \`.cursor/mcp.json\`) gives the same check,
29
29
  the IDL and the docs as tools.
30
- - The language reference: \`node_modules/typesol/docs/language.md\`, or https://typesol.com/llms-full.txt.
30
+ - The language reference: \`node_modules/typesol/docs/language.md\` (after \`npm install\`), or https://typesol.com/llms-full.txt.
31
31
  `;
32
32
  /** AGENTS.md for a new project (Codex, Cursor, Zed, and other agents that read it). */
33
33
  export function agentsMd(name) {
@@ -40,4 +40,4 @@ export function cursorRule() {
40
40
  return `---\ndescription: TypeSOL, a TypeScript subset compiled to Solana programs\nglobs: programs/**/*.ts, tests/**/*.ts\nalwaysApply: true\n---\n\n${AGENT_RULES}`;
41
41
  }
42
42
  /** The MCP server configuration Claude Code (.mcp.json) and Cursor (.cursor/mcp.json) read. */
43
- export const MCP_JSON = JSON.stringify({ mcpServers: { typesol: { command: "npx", args: ["typesol", "mcp"] } } }, null, 2) + "\n";
43
+ export const MCP_JSON = JSON.stringify({ mcpServers: { typesol: { command: "npx", args: ["--no-install", "typesol", "mcp"] } } }, null, 2) + "\n";
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);