@typesol/cli 0.43.0 → 0.44.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +173 -0
- package/NOTICE +71 -0
- package/README.md +25 -11
- package/SECURITY.md +32 -5
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +5 -5
- package/dist/cli.js +196 -72
- package/dist/compiler/analyze.js +4 -0
- package/dist/compiler/emit/alias.d.ts +16 -2
- package/dist/compiler/emit/alias.js +70 -6
- package/dist/compiler/emit/base.d.ts +3 -1
- package/dist/compiler/emit/base.js +20 -3
- package/dist/compiler/emit/borsh.js +11 -5
- package/dist/compiler/emit/calls.d.ts +13 -0
- package/dist/compiler/emit/calls.js +105 -14
- package/dist/compiler/emit/cpi-core.d.ts +9 -1
- package/dist/compiler/emit/cpi-core.js +51 -10
- package/dist/compiler/emit/create.js +22 -11
- package/dist/compiler/emit/expressions.js +6 -1
- package/dist/compiler/emit/function.js +15 -5
- package/dist/compiler/emit/metaplex.js +17 -4
- package/dist/compiler/emit/shared.d.ts +17 -0
- package/dist/compiler/emit/shared.js +36 -3
- package/dist/compiler/emit/statements.js +17 -4
- package/dist/compiler/emit/storage.d.ts +2 -0
- package/dist/compiler/emit/storage.js +16 -8
- package/dist/compiler/emit/token.js +64 -39
- package/dist/compiler/index.d.ts +15 -1
- package/dist/compiler/index.js +40 -3
- package/dist/compiler/toolchain.d.ts +41 -1
- package/dist/compiler/toolchain.js +102 -3
- package/dist/testing-stake.d.ts +2 -1
- package/dist/testing-stake.js +2 -1
- package/dist/testing.js +6 -4
- package/dist/tools/clientgen.d.ts +15 -0
- package/dist/tools/clientgen.js +173 -7
- package/dist/tools/cpigen.d.ts +0 -15
- package/dist/tools/cpigen.js +19 -8
- package/dist/tools/doctor.d.ts +17 -2
- package/dist/tools/doctor.js +64 -4
- package/dist/tools/portgen.js +43 -18
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +173 -6
- package/docs/ai.md +10 -5
- package/docs/architecture.md +1 -1
- package/docs/audit.md +103 -18
- package/docs/case-study-escrow.md +1 -1
- package/docs/case-study-phoenix.md +10 -10
- package/docs/case-study-raydium-amm.md +3 -3
- package/docs/case-study-spl-stake-pool.md +5 -5
- package/docs/cli.md +17 -8
- package/docs/client.md +11 -3
- package/docs/errors.md +2 -2
- package/docs/language.md +16 -9
- package/docs/mainnet.md +21 -10
- package/docs/migrate-from-anchor.md +2 -1
- package/docs/runtime.md +11 -1
- package/docs/security-model.md +79 -12
- package/docs/stability.md +21 -2
- package/docs/testing.md +25 -0
- package/docs/troubleshooting.md +12 -0
- package/llms-full.txt +216 -63
- package/llms.txt +1 -1
- package/package.json +3 -1
- package/runtime/typesol_rt.h +30 -18
- 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 {
|
|
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: {
|
|
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
|
|
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
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
-
|
|
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
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
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: {
|
|
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
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
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(
|
|
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(
|
|
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(
|
|
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 =
|
|
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
|
-
/**
|
|
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);
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -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
|
}
|
|
@@ -15,7 +15,9 @@ import { EmitterBase } from "./base.js";
|
|
|
15
15
|
* assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
|
|
16
16
|
*
|
|
17
17
|
* Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
|
|
18
|
-
* unless `Dup<…>` allows it for in-place accounts.
|
|
18
|
+
* unless `Dup<…>` allows it for in-place accounts. Where data moves (a Vec resized, an account given to a helper:
|
|
19
|
+
* `moves`), `assertNotAliased` also treats the names that may be one account (`maySharePlace`: a Dup pair, a
|
|
20
|
+
* read-only and a writable account of one type, a loaded struct) as one, since the data moves under each of them.
|
|
19
21
|
*/
|
|
20
22
|
export declare abstract class AliasEmitter extends EmitterBase {
|
|
21
23
|
/**
|
|
@@ -38,7 +40,19 @@ export declare abstract class AliasEmitter extends EmitterBase {
|
|
|
38
40
|
* to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
|
|
39
41
|
* value. Refuse when a live reference into the replaced place is still used afterwards.
|
|
40
42
|
*/
|
|
41
|
-
protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string): void;
|
|
43
|
+
protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string, inPlace?: boolean, moves?: boolean): void;
|
|
44
|
+
/**
|
|
45
|
+
* A reference path (`a.entries[]`) inside one of the `replaced` places named through another root that may be the
|
|
46
|
+
* same account (`b.entries` when `a` and `b` may be one account): the path, the two roots and why.
|
|
47
|
+
*/
|
|
48
|
+
private sharedPlace;
|
|
49
|
+
/**
|
|
50
|
+
* Whether two reference roots may name one account's data, read in place: both structs of one type (a struct
|
|
51
|
+
* account parameter or group field not `@layout borsh`, or a struct loaded with loadAccount / loadAccountMut), and
|
|
52
|
+
* accounts the entry checks do not keep apart (`mayBeSameAccount`: a Dup<…> or read-only one, a helper's). Returns
|
|
53
|
+
* why, for the message.
|
|
54
|
+
*/
|
|
55
|
+
protected maySharePlace(a: string, b: string): string | undefined;
|
|
42
56
|
/**
|
|
43
57
|
* Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
|
|
44
58
|
* A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
|
|
@@ -17,7 +17,9 @@ const TREE_NODE_METHODS = new Set(["min", "max", "nodeAt", "remove", "removeAt"]
|
|
|
17
17
|
* assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
|
|
18
18
|
*
|
|
19
19
|
* Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
|
|
20
|
-
* unless `Dup<…>` allows it for in-place accounts.
|
|
20
|
+
* unless `Dup<…>` allows it for in-place accounts. Where data moves (a Vec resized, an account given to a helper:
|
|
21
|
+
* `moves`), `assertNotAliased` also treats the names that may be one account (`maySharePlace`: a Dup pair, a
|
|
22
|
+
* read-only and a writable account of one type, a loaded struct) as one, since the data moves under each of them.
|
|
21
23
|
*/
|
|
22
24
|
export class AliasEmitter extends EmitterBase {
|
|
23
25
|
/**
|
|
@@ -69,21 +71,79 @@ export class AliasEmitter extends EmitterBase {
|
|
|
69
71
|
* to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
|
|
70
72
|
* value. Refuse when a live reference into the replaced place is still used afterwards.
|
|
71
73
|
*/
|
|
72
|
-
assertNotAliased(replaced, at, helper) {
|
|
74
|
+
assertNotAliased(replaced, at, helper, inPlace = false, moves = false) {
|
|
73
75
|
if (!replaced)
|
|
74
76
|
return;
|
|
75
77
|
for (const scope of this.scopes)
|
|
76
78
|
for (const [name, l] of scope) {
|
|
77
79
|
if (!l.paths || !l.decl)
|
|
78
80
|
continue;
|
|
79
|
-
|
|
80
|
-
|
|
81
|
+
// A helper given an account changes it in place (`inPlace`): a local naming the whole account (a struct loaded
|
|
82
|
+
// with loadAccountMut) then reads what JS's object would. Only references into it are stale.
|
|
83
|
+
const inside = (p, r) => (p === r && !inPlace) || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`);
|
|
84
|
+
const hit = replaced.find((r) => l.paths.some((p) => inside(p, r)));
|
|
85
|
+
// Data that moves (`moves`: a Vec resized, so the Vecs after it shift; an account a helper may resize) moves
|
|
86
|
+
// under every name of the account: a reference made through another parameter (or loaded struct) that may be
|
|
87
|
+
// this account is stale too.
|
|
88
|
+
const shared = !hit && moves ? this.sharedPlace(replaced, l.paths, inside) : undefined;
|
|
89
|
+
if ((!hit && !shared) || !this.usedAfter(l.decl, at))
|
|
81
90
|
continue;
|
|
91
|
+
if (shared)
|
|
92
|
+
this.fail(at, `"${name}" still refers to ${this.showPath(shared.path)}, and ${this.showPath(shared.root)} may be the same account as ${this.showPath(shared.other)} (${shared.why}): ${helper ? `${helper}() may move` : "this moves"} that data, so "${name}" would then reach another record. Copy the fields you need into locals first`);
|
|
82
93
|
this.fail(at, helper
|
|
83
94
|
? `"${name}" still refers to data in ${this.showPath(hit)}, and ${helper}() may replace it (then "${name}" would read the new value; in JS it keeps the old one). Copy the fields you need into locals first`
|
|
84
95
|
: `"${name}" still refers to ${this.showPath(hit)}; replacing it here would change what "${name}" reads (in JS it keeps the old value). Copy the fields you need into locals first`);
|
|
85
96
|
}
|
|
86
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* A reference path (`a.entries[]`) inside one of the `replaced` places named through another root that may be the
|
|
100
|
+
* same account (`b.entries` when `a` and `b` may be one account): the path, the two roots and why.
|
|
101
|
+
*/
|
|
102
|
+
sharedPlace(replaced, paths, inside) {
|
|
103
|
+
const rootOf = (p) => p.split(/[.[]/)[0];
|
|
104
|
+
for (const r of replaced)
|
|
105
|
+
for (const p of paths) {
|
|
106
|
+
const [R, P] = [rootOf(r), rootOf(p)];
|
|
107
|
+
if (R === P)
|
|
108
|
+
continue;
|
|
109
|
+
const why = this.maySharePlace(R, P);
|
|
110
|
+
if (why && inside(p, P + r.slice(R.length)))
|
|
111
|
+
return { path: p, root: P, other: R, why };
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Whether two reference roots may name one account's data, read in place: both structs of one type (a struct
|
|
117
|
+
* account parameter or group field not `@layout borsh`, or a struct loaded with loadAccount / loadAccountMut), and
|
|
118
|
+
* accounts the entry checks do not keep apart (`mayBeSameAccount`: a Dup<…> or read-only one, a helper's). Returns
|
|
119
|
+
* why, for the message.
|
|
120
|
+
*/
|
|
121
|
+
maySharePlace(a, b) {
|
|
122
|
+
const struct = (root) => {
|
|
123
|
+
if (root.startsWith("@")) {
|
|
124
|
+
for (const s of this.scopes)
|
|
125
|
+
for (const l of s.values())
|
|
126
|
+
if (`@${l.c}` === root && l.loaded)
|
|
127
|
+
return l.loaded.struct;
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
const k = this.accounts.get(root)?.kind;
|
|
131
|
+
return k?.kind === "account" && k.struct.layout !== "borsh" ? k.struct.name : undefined;
|
|
132
|
+
};
|
|
133
|
+
const s = struct(a);
|
|
134
|
+
if (!s || s !== struct(b))
|
|
135
|
+
return undefined;
|
|
136
|
+
if (a.startsWith("@") || b.startsWith("@"))
|
|
137
|
+
return "a struct loaded from an account";
|
|
138
|
+
if (!this.mayBeSameAccount(a, b))
|
|
139
|
+
return undefined;
|
|
140
|
+
const [x, y] = [this.accounts.get(a), this.accounts.get(b)];
|
|
141
|
+
if (x.constraints.dup || y.constraints.dup)
|
|
142
|
+
return "Dup<…>";
|
|
143
|
+
if (!isWritable(x.kind) || !isWritable(y.kind))
|
|
144
|
+
return "a read-only account may be a writable one";
|
|
145
|
+
return "the entry checks do not keep them apart";
|
|
146
|
+
}
|
|
87
147
|
/**
|
|
88
148
|
* Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
|
|
89
149
|
* A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
|
|
@@ -198,8 +258,12 @@ export class AliasEmitter extends EmitterBase {
|
|
|
198
258
|
}
|
|
199
259
|
/** A storage path as the source names it: `@<C local>.x` becomes `<its name>.x` (`@p_rec.items[]` → `rec.items[]`). */
|
|
200
260
|
showPath(path) {
|
|
201
|
-
if (!path.startsWith("@"))
|
|
202
|
-
|
|
261
|
+
if (!path.startsWith("@")) {
|
|
262
|
+
// A field of an account group, as the source names it: `g__pool.b[]` → `g.pool.b[]`.
|
|
263
|
+
const root = path.split(/[.[]/)[0];
|
|
264
|
+
const g = this.accounts.get(root)?.group;
|
|
265
|
+
return g ? [...g.path, g.field].join(".") + path.slice(root.length) : path;
|
|
266
|
+
}
|
|
203
267
|
// A @heap local is named through its pointer: `@(*l_x)`.
|
|
204
268
|
const c = /^@(\(\*\w+\)|\w+)/.exec(path)?.[1];
|
|
205
269
|
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;
|