@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/tools/cpigen.js
CHANGED
|
@@ -12,7 +12,12 @@
|
|
|
12
12
|
* Call it with `signer([...])` for a PDA of the calling program that must sign, or `signer([])`.
|
|
13
13
|
* Argument types without a Borsh-identical TypeSOL type (strings or Options inside structs, data-carrying
|
|
14
14
|
* enums, nested Vecs, generics) are reported and the instruction is left out.
|
|
15
|
+
*
|
|
16
|
+
* The IDL is checked as `typesol client` checks it (checkIdl): names, addresses and byte lists reach the generated
|
|
17
|
+
* source only when well-formed, and text from the IDL (docs, the program's name) only inside comments, escaped.
|
|
15
18
|
*/
|
|
19
|
+
import { checkIdl, commentText, printable } from "./clientgen.js";
|
|
20
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
16
21
|
const INTS = new Set(["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128"]);
|
|
17
22
|
const RESERVED = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await program seeds".split(" "));
|
|
18
23
|
class Unsupported extends Error {
|
|
@@ -60,13 +65,16 @@ const camel = (s) => s.replace(/[_-]+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase())
|
|
|
60
65
|
const pascal = (s) => camel(s).replace(/^[a-z]/, (c) => c.toUpperCase());
|
|
61
66
|
const safe = (s) => (RESERVED.has(s) ? `${s}_` : s);
|
|
62
67
|
export function generateCpi(idl, opts = {}) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const address = opts.address ?? idl.address;
|
|
68
|
+
const address = opts.address ?? (typeof idl === "object" && idl !== null ? idl.address : undefined);
|
|
69
|
+
checkIdl(idl, { address, instructions: "required" });
|
|
66
70
|
if (!address)
|
|
67
71
|
throw new Error("the IDL has no program address; pass --address <base58>");
|
|
68
|
-
|
|
69
|
-
|
|
72
|
+
if (opts.prefix !== undefined && !IDENT.test(opts.prefix))
|
|
73
|
+
throw new Error("the prefix must be an identifier");
|
|
74
|
+
const rawName = idl.metadata?.name;
|
|
75
|
+
// The program's name in comments as written (escaped); in the helpers' names only when it is an identifier.
|
|
76
|
+
const programName = typeof rawName === "string" && rawName ? commentText(rawName) : "program";
|
|
77
|
+
const prefix = opts.prefix ?? (typeof rawName === "string" && IDENT.test(rawName) ? camel(rawName) : "program");
|
|
70
78
|
const typeDefs = new Map((idl.types ?? []).map((t) => [t.name, t]));
|
|
71
79
|
const typeImports = new Set(["Program", "SignerSeeds"]);
|
|
72
80
|
const valueImports = new Set(["invoke", "hex"]);
|
|
@@ -230,7 +238,8 @@ export function generateCpi(idl, opts = {}) {
|
|
|
230
238
|
}
|
|
231
239
|
const name = `${prefix}${pascal(ix.name)}`;
|
|
232
240
|
const disc = Buffer.from(ix.discriminator).toString("hex");
|
|
233
|
-
const
|
|
241
|
+
const docs = Array.isArray(ix.docs) ? ix.docs.filter((l) => typeof l === "string") : [];
|
|
242
|
+
const doc = [...docs, `${programName}.${ix.name} through CPI.`, ...notes].map((l) => ` * ${commentText(l)}`).join("\n");
|
|
234
243
|
functions.push([
|
|
235
244
|
`/**\n${doc}\n */`,
|
|
236
245
|
`export function ${name}(${params.join(", ")}): ${returns} {`,
|
|
@@ -243,13 +252,15 @@ export function generateCpi(idl, opts = {}) {
|
|
|
243
252
|
catch (e) {
|
|
244
253
|
if (!(e instanceof Unsupported))
|
|
245
254
|
throw e;
|
|
246
|
-
skipped.push({ instruction: ix.name, reason: e.message });
|
|
255
|
+
skipped.push({ instruction: ix.name, reason: printable(e.message) });
|
|
247
256
|
}
|
|
248
257
|
}
|
|
249
258
|
const imports = [...[...typeImports].sort().map((t) => `type ${t}`), ...[...valueImports].sort()];
|
|
250
259
|
const header = [
|
|
251
260
|
`// Generated by \`typesol cpi\` from the ${programName} IDL (${address}). Edit freely.`,
|
|
252
|
-
...(skipped.length
|
|
261
|
+
...(skipped.length
|
|
262
|
+
? [`// Left out (no Borsh-identical TypeSOL type): ${commentText(skipped.map((s) => `${s.instruction} (${s.reason})`).join("; "))}.`]
|
|
263
|
+
: []),
|
|
253
264
|
`import { ${imports.join(", ")} } from "typesol";`,
|
|
254
265
|
];
|
|
255
266
|
const body = [...[...declarations.values()].filter(Boolean), ...functions];
|
package/dist/tools/doctor.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import type { Rpc, SolanaRpcApi } from "@solana/kit";
|
|
2
|
+
/** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
|
|
3
|
+
export declare const INSTALL_AGAVE: "sh -c \"$(curl -sSfL https://release.anza.xyz/v3.1.10/install)\"";
|
|
2
4
|
export interface Check {
|
|
3
5
|
ok: boolean;
|
|
4
6
|
/** A missing optional piece (the Solana CLI is only needed to deploy). */
|
|
@@ -9,6 +11,11 @@ export interface Check {
|
|
|
9
11
|
}
|
|
10
12
|
/** The platform-tools the compiler needs: found, or what to run. */
|
|
11
13
|
export declare function toolchainCheck(): Check;
|
|
14
|
+
/**
|
|
15
|
+
* Whether the active platform-tools are the ones TypeSOL is tested with. An untested one is a warning, or an error
|
|
16
|
+
* under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
|
|
17
|
+
*/
|
|
18
|
+
export declare function testedToolchainCheck(): Check | undefined;
|
|
12
19
|
/** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
|
|
13
20
|
export declare function solanaConfig(file?: string): {
|
|
14
21
|
url?: string;
|
|
@@ -22,7 +29,15 @@ export declare function clusterUrl(url: string): string;
|
|
|
22
29
|
export declare function rpcHost(url: string): string;
|
|
23
30
|
export declare function rpc<T>(url: string, method: string, params?: unknown[]): Promise<T>;
|
|
24
31
|
/** fetch's "fetch failed" says little: the cause's code (ECONNREFUSED, ENOTFOUND, a timeout) says more. */
|
|
25
|
-
export declare const errText: (e: unknown) => string;
|
|
32
|
+
export declare const errText: (e: unknown, timeoutSeconds?: number) => string;
|
|
33
|
+
/** How long one RPC request of the kit-based commands may take: TYPESOL_RPC_TIMEOUT seconds, default 30. */
|
|
34
|
+
export declare function rpcTimeoutSeconds(): number;
|
|
35
|
+
/**
|
|
36
|
+
* A kit RPC client for `clone`, `client --address`, `verify` and `idl publish`: each request gives up after
|
|
37
|
+
* rpcTimeoutSeconds(), and a request that fails on the way names only the host and the cause, as `doctor` and
|
|
38
|
+
* `deploy` do (the URL can carry an API key).
|
|
39
|
+
*/
|
|
40
|
+
export declare function cliRpc(url: string): Promise<Rpc<SolanaRpcApi>>;
|
|
26
41
|
/**
|
|
27
42
|
* Before `solana program deploy`: the RPC answers, and the payer holds enough for the program's rent (a first deploy
|
|
28
43
|
* holds about twice the binary's rent while the buffer exists; an upgrade, the buffer's). Throws with what to do.
|
package/dist/tools/doctor.js
CHANGED
|
@@ -5,10 +5,11 @@ import { execFileSync } from "node:child_process";
|
|
|
5
5
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
6
6
|
import os from "node:os";
|
|
7
7
|
import path from "node:path";
|
|
8
|
-
import { findToolchain } from "../compiler/toolchain.js";
|
|
8
|
+
import { findToolchain, INSTALL_TESTED_TOOLCHAIN, shortClang, TESTED_TOOLCHAIN, toolchainInfo, toolchainStrict } from "../compiler/toolchain.js";
|
|
9
9
|
import { base58, readKeypair } from "../keys.js";
|
|
10
10
|
import { findWorkspace } from "../workspace.js";
|
|
11
|
-
|
|
11
|
+
/** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
|
|
12
|
+
export const INSTALL_AGAVE = INSTALL_TESTED_TOOLCHAIN[0];
|
|
12
13
|
const MIN_NODE = [22, 12];
|
|
13
14
|
/** The platform-tools the compiler needs: found, or what to run. */
|
|
14
15
|
export function toolchainCheck() {
|
|
@@ -34,6 +35,36 @@ export function toolchainCheck() {
|
|
|
34
35
|
};
|
|
35
36
|
}
|
|
36
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Whether the active platform-tools are the ones TypeSOL is tested with. An untested one is a warning, or an error
|
|
40
|
+
* under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
|
|
41
|
+
*/
|
|
42
|
+
export function testedToolchainCheck() {
|
|
43
|
+
let info;
|
|
44
|
+
try {
|
|
45
|
+
info = toolchainInfo();
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined; // the platform-tools row says what is missing
|
|
49
|
+
}
|
|
50
|
+
const tested = `${shortClang(TESTED_TOOLCHAIN.clang)}, platform-tools ${TESTED_TOOLCHAIN.platformTools}`;
|
|
51
|
+
if (info.tested)
|
|
52
|
+
return { ok: true, what: "toolchain", detail: `tested: ${shortClang(info.clang)}, platform-tools ${info.platformTools ?? "unknown"}` };
|
|
53
|
+
let strict = true;
|
|
54
|
+
try {
|
|
55
|
+
strict = toolchainStrict();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
/* a bad TYPESOL_TOOLCHAIN value fails the build itself; here it counts as strict */
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
optional: !strict,
|
|
63
|
+
what: "toolchain",
|
|
64
|
+
detail: `untested: ${shortClang(info.clang)}, platform-tools ${info.platformTools ?? "unknown"}; TypeSOL is tested with ${tested} (Agave ${TESTED_TOOLCHAIN.agave}): binaries from another toolchain are not covered by its tests${strict ? " (TYPESOL_TOOLCHAIN=strict refuses it)" : ""}`,
|
|
65
|
+
fix: [`${INSTALL_TESTED_TOOLCHAIN[1]} # the tested platform-tools`],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
37
68
|
/** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
|
|
38
69
|
export function solanaConfig(file) {
|
|
39
70
|
const configPath = file ?? path.join(os.homedir(), ".config/solana/cli/config.yml");
|
|
@@ -91,10 +122,36 @@ export async function rpc(url, method, params = []) {
|
|
|
91
122
|
return body.result;
|
|
92
123
|
}
|
|
93
124
|
/** fetch's "fetch failed" says little: the cause's code (ECONNREFUSED, ENOTFOUND, a timeout) says more. */
|
|
94
|
-
export const errText = (e) => {
|
|
125
|
+
export const errText = (e, timeoutSeconds = 10) => {
|
|
95
126
|
const err = e;
|
|
96
|
-
return err.cause?.code ?? err.cause?.message ?? (err.name === "TimeoutError" ?
|
|
127
|
+
return err.cause?.code ?? err.cause?.message ?? (err.name === "TimeoutError" ? `no answer in ${timeoutSeconds} s` : err.message);
|
|
97
128
|
};
|
|
129
|
+
/** How long one RPC request of the kit-based commands may take: TYPESOL_RPC_TIMEOUT seconds, default 30. */
|
|
130
|
+
export function rpcTimeoutSeconds() {
|
|
131
|
+
const s = Number(process.env.TYPESOL_RPC_TIMEOUT);
|
|
132
|
+
return Number.isFinite(s) && s > 0 ? s : 30;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* A kit RPC client for `clone`, `client --address`, `verify` and `idl publish`: each request gives up after
|
|
136
|
+
* rpcTimeoutSeconds(), and a request that fails on the way names only the host and the cause, as `doctor` and
|
|
137
|
+
* `deploy` do (the URL can carry an API key).
|
|
138
|
+
*/
|
|
139
|
+
export async function cliRpc(url) {
|
|
140
|
+
const kit = await import("@solana/kit");
|
|
141
|
+
const host = rpcHost(url);
|
|
142
|
+
const seconds = rpcTimeoutSeconds();
|
|
143
|
+
const base = kit.createDefaultRpcTransport({ url });
|
|
144
|
+
const transport = (async (config) => {
|
|
145
|
+
const timeout = AbortSignal.timeout(seconds * 1000);
|
|
146
|
+
try {
|
|
147
|
+
return await base({ ...config, signal: config.signal ? AbortSignal.any([config.signal, timeout]) : timeout });
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
throw new Error(`cannot reach ${host} (${errText(e, seconds)}): check --url, or json_rpc_url in the Solana CLI config`, { cause: e });
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
return kit.createSolanaRpcFromTransport(transport);
|
|
154
|
+
}
|
|
98
155
|
const sol = (lamports) => lamports === 0 ? "0 SOL" : lamports < 100_000 ? `${lamports} lamports` : `${(lamports / 1e9).toFixed(lamports < 1e7 ? 4 : 2)} SOL`;
|
|
99
156
|
/** A cost, rounded up so the advice is enough. */
|
|
100
157
|
const solUp = (lamports) => `${(Math.ceil(lamports / 1e7) / 100).toFixed(2)} SOL`;
|
|
@@ -144,6 +201,9 @@ export async function doctorChecks(opts) {
|
|
|
144
201
|
fix: nodeOk ? undefined : [`install Node.js ${MIN_NODE.join(".")} or later (https://nodejs.org)`],
|
|
145
202
|
});
|
|
146
203
|
checks.push(toolchainCheck());
|
|
204
|
+
const tested = testedToolchainCheck();
|
|
205
|
+
if (tested)
|
|
206
|
+
checks.push(tested);
|
|
147
207
|
let solanaVersion;
|
|
148
208
|
try {
|
|
149
209
|
solanaVersion = execFileSync("solana", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
|
package/dist/tools/portgen.js
CHANGED
|
@@ -7,9 +7,13 @@
|
|
|
7
7
|
* so existing clients keep working. Account structs holding a String, Vec or Option get `@layout borsh`, so they keep
|
|
8
8
|
* Anchor's bytes (existing accounts stay readable); where a layout still differs (a String or Vec nested in a struct, a
|
|
9
9
|
* data enum, a COption) it says so in a note and a comment.
|
|
10
|
+
*
|
|
11
|
+
* The IDL is checked as `typesol client` checks it (checkIdl): names, addresses and byte lists reach the skeleton only
|
|
12
|
+
* when well-formed, and text from the IDL (docs, relations, the program's name) only inside comments, escaped.
|
|
10
13
|
*/
|
|
11
14
|
import { createHash } from "node:crypto";
|
|
12
15
|
import { ACCOUNT_MEMBERS, cNameProblem, fieldIdlName } from "../compiler/analyze.js";
|
|
16
|
+
import { checkIdl, commentText, printable } from "./clientgen.js";
|
|
13
17
|
const RESERVED = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await".split(" "));
|
|
14
18
|
const camel = (s) => s.replace(/[_-]+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase()).replace(/^[A-Z]/, (c) => c.toLowerCase());
|
|
15
19
|
const pascal = (s) => camel(s).replace(/^[a-z]/, (c) => c.toUpperCase());
|
|
@@ -38,6 +42,13 @@ const PROGRAMS = {
|
|
|
38
42
|
ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL: "AssociatedTokenProgram",
|
|
39
43
|
};
|
|
40
44
|
export function generatePort(idl) {
|
|
45
|
+
// An IDL with an empty instructions list still ports its types (a skeleton to add instructions to).
|
|
46
|
+
checkIdl(idl);
|
|
47
|
+
const res = port(idl);
|
|
48
|
+
return { ...res, notes: res.notes.map(printable) };
|
|
49
|
+
}
|
|
50
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
51
|
+
function port(idl) {
|
|
41
52
|
const notes = [];
|
|
42
53
|
const imports = new Set();
|
|
43
54
|
const use = (n) => (imports.add(n), n);
|
|
@@ -263,12 +274,15 @@ export function generatePort(idl) {
|
|
|
263
274
|
return undefined;
|
|
264
275
|
return quiet ? "x" : tsType(t, "account", at);
|
|
265
276
|
};
|
|
266
|
-
const esc = (s) => s
|
|
267
|
-
const docs = (
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
? `${pad}
|
|
271
|
-
:
|
|
277
|
+
const esc = (s) => commentText(String(s));
|
|
278
|
+
const docs = (given, pad = "", tags = []) => {
|
|
279
|
+
const lines = Array.isArray(given) ? given.filter((l) => typeof l === "string") : undefined;
|
|
280
|
+
return tags.length
|
|
281
|
+
? `${pad}/**\n${lines?.length ? `${pad} * ${esc(lines.join(" "))}\n` : ""}${tags.map((t) => `${pad} * ${t}\n`).join("")}${pad} */\n`
|
|
282
|
+
: lines?.length
|
|
283
|
+
? `${pad}/** ${esc(lines.join(" "))} */\n`
|
|
284
|
+
: "";
|
|
285
|
+
};
|
|
272
286
|
// What an Anchor IDL says of a zero-copy type (repr, serialization), kept as tags so the port's IDL says it too.
|
|
273
287
|
const metaTags = (def) => [
|
|
274
288
|
...(def.serialization ? [`@serialization ${def.serialization}`] : []),
|
|
@@ -276,15 +290,25 @@ export function generatePort(idl) {
|
|
|
276
290
|
];
|
|
277
291
|
const out = [];
|
|
278
292
|
// Constants: integer literals and strings; expressions are left to port by hand.
|
|
279
|
-
for (const c of idl.constants
|
|
280
|
-
const ty = typeof c
|
|
281
|
-
const
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
293
|
+
for (const c of Array.isArray(idl.constants) ? idl.constants : []) {
|
|
294
|
+
const ty = typeof c?.type === "string" && INTS.has(c.type) ? c.type : undefined;
|
|
295
|
+
const value = typeof c?.value === "string" ? c.value.trim() : undefined;
|
|
296
|
+
// A string constant is copied only as the string it parses to, re-quoted: the IDL's text never becomes code.
|
|
297
|
+
let text;
|
|
298
|
+
try {
|
|
299
|
+
text = c?.type === "string" && value?.startsWith('"') ? JSON.parse(value) : undefined;
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
text = undefined;
|
|
303
|
+
}
|
|
304
|
+
if (typeof c?.name !== "string" || !IDENT.test(c.name))
|
|
305
|
+
notes.push(`constant ${JSON.stringify(c?.name)}: not an identifier; port it by hand`);
|
|
306
|
+
else if (ty && value !== undefined && /^-?\d[\d_]*$/.test(value))
|
|
307
|
+
out.push(`export const ${c.name}: ${use(ty)} = ${value.replace(/_/g, "")}n;`);
|
|
308
|
+
else if (typeof text === "string")
|
|
309
|
+
out.push(`export const ${c.name} = ${JSON.stringify(text)};`);
|
|
286
310
|
else
|
|
287
|
-
notes.push(`constant ${c.name} = ${c.value}: not a literal; port it by hand`);
|
|
311
|
+
notes.push(`constant ${c.name} = ${String(c.value)}: not a literal; port it by hand`);
|
|
288
312
|
}
|
|
289
313
|
if (out.length)
|
|
290
314
|
out.push("");
|
|
@@ -348,7 +372,8 @@ export function generatePort(idl) {
|
|
|
348
372
|
// Errors: TypeSOL numbers them from 6000 in order; `/** @code N */` keeps an IDL code that skips ahead. NotPorted,
|
|
349
373
|
// last, marks the instructions still to write, so the codes of the program's own errors do not move.
|
|
350
374
|
const errors = [...(idl.errors ?? [])].sort((a, b) => a.code - b.code);
|
|
351
|
-
const
|
|
375
|
+
const rawName = idl.metadata?.name;
|
|
376
|
+
const program = typeName(pascal(typeof rawName === "string" && IDENT.test(rawName) ? rawName : "program"));
|
|
352
377
|
const errorEnum = `${program}Error`;
|
|
353
378
|
if (errors.some((e, i) => e.code < 6000 || (i > 0 && e.code === errors[i - 1].code)))
|
|
354
379
|
notes.push(`errors: codes below 6000 or repeated in the IDL (${errors.map((e) => e.code).join(", ")}) cannot be kept, so clients see other codes`);
|
|
@@ -408,8 +433,8 @@ export function generatePort(idl) {
|
|
|
408
433
|
: `@${camel(s.path ?? "")}`);
|
|
409
434
|
comments.push(`${ident(a.name)}: PDA [${seeds.join(", ")}]`);
|
|
410
435
|
}
|
|
411
|
-
if (a.relations
|
|
412
|
-
comments.push(`${ident(a.name)}: has_one ${a.relations.map(camel).join(", ")}`);
|
|
436
|
+
if (Array.isArray(a.relations) && a.relations.length)
|
|
437
|
+
comments.push(`${ident(a.name)}: has_one ${a.relations.map((r) => camel(String(r))).join(", ")}`);
|
|
413
438
|
}
|
|
414
439
|
for (const g of ix.args)
|
|
415
440
|
params.push(`${unique(ident(g.name), "Arg")}: ${tsType(g.type, "arg", `${ix.name}(${g.name})`)}`);
|
|
@@ -436,7 +461,7 @@ export function generatePort(idl) {
|
|
|
436
461
|
notes.push(`account ${a.name}: its discriminator is not sha256("account:${a.name}"); TypeSOL derives that one, so existing accounts would not load`);
|
|
437
462
|
}
|
|
438
463
|
const header = [
|
|
439
|
-
`// Ported from the ${
|
|
464
|
+
`// Ported from the ${typeof rawName === "string" && rawName ? commentText(rawName) : "program"} IDL by \`typesol port\`. Fill in the instruction bodies;`,
|
|
440
465
|
"// pick Account<T> / Mut<T> / Init<T> for the AccountInfo parameters that hold one of the structs below.",
|
|
441
466
|
`import { ${[
|
|
442
467
|
...[...imports]
|
package/dist/workspace.d.ts
CHANGED
|
@@ -53,6 +53,26 @@ export declare function buildWorkspace(ws: Workspace, names?: string[], opts?: {
|
|
|
53
53
|
result: BuildResult;
|
|
54
54
|
clientPath: string;
|
|
55
55
|
}[];
|
|
56
|
+
/** What a test needs of a built program. */
|
|
57
|
+
export interface BuiltProgram {
|
|
58
|
+
address: string;
|
|
59
|
+
soPath: string;
|
|
60
|
+
idl: BuildResult["idl"];
|
|
61
|
+
/** False when the existing build was up to date and was loaded instead of rebuilt. */
|
|
62
|
+
rebuilt: boolean;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The program built for a test: the existing build when it is up to date (same sources, runtime header, TypeSOL,
|
|
66
|
+
* TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records),
|
|
67
|
+
* else a fresh one. Concurrent callers (parallel test workers) wait for each other instead of building over each other.
|
|
68
|
+
*/
|
|
69
|
+
export declare function buildForTest(ws: Workspace, name: string): BuiltProgram;
|
|
70
|
+
/**
|
|
71
|
+
* Run `fn` holding `<dir>/.typesol-build.lock`, created exclusively: one build of a program at a time across processes.
|
|
72
|
+
* The lock records its holder's host and pid; a lock whose process is gone (on this host) or that is older than
|
|
73
|
+
* LOCK_STALE_MS is taken over, so a crashed or killed build does not block the next one.
|
|
74
|
+
*/
|
|
75
|
+
export declare function withBuildLock<T>(dir: string, fn: () => T): T;
|
|
56
76
|
/** The `solana program deploy` arguments for one built program (deploying again upgrades it). */
|
|
57
77
|
export declare function deployArgs(soPath: string, keypair: string, opts: {
|
|
58
78
|
url?: string;
|
package/dist/workspace.js
CHANGED
|
@@ -12,10 +12,14 @@
|
|
|
12
12
|
* The address is recorded in typesol.json on first build, so a lost or swapped keypair is caught before deploying.
|
|
13
13
|
*/
|
|
14
14
|
import { agentsMd, CLAUDE_MD, cursorRule, MCP_JSON } from "./ai.js";
|
|
15
|
-
import {
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
16
18
|
import path from "node:path";
|
|
19
|
+
import ts from "typescript";
|
|
17
20
|
import { writeClient } from "./tools/clientgen.js";
|
|
18
21
|
import { build, COMPILER_VERSION, SBPF_VERSIONS } from "./compiler/index.js";
|
|
22
|
+
import { checkToolchain, RUNTIME_DIR, toolchainInfo } from "./compiler/toolchain.js";
|
|
19
23
|
import { loadOrCreateKeypair } from "./keys.js";
|
|
20
24
|
import { TEMPLATES } from "./templates.js";
|
|
21
25
|
export const CONFIG = "typesol.json";
|
|
@@ -104,13 +108,176 @@ export function programAddress(ws, name, opts = {}) {
|
|
|
104
108
|
export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {}) {
|
|
105
109
|
return names.map((name) => {
|
|
106
110
|
const paths = programPaths(ws, name);
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
111
|
+
// Every build of a program writes the same files (<name>.c, .o, .so, …), and the first one creates its keypair:
|
|
112
|
+
// another process building it at the same time (vitest runs test files in parallel workers) would overwrite them.
|
|
113
|
+
return withBuildLock(paths.outDir, () => {
|
|
114
|
+
const { address, created, keyless } = programAddress(ws, name, { needKeypair: opts.needKeypair });
|
|
115
|
+
const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile });
|
|
116
|
+
// The TypeScript client (docs/client.md) is written with the build, from the same IDL.
|
|
117
|
+
const clientPath = writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`)).path;
|
|
118
|
+
return { paths, address, created, keyless, result, clientPath };
|
|
119
|
+
});
|
|
112
120
|
});
|
|
113
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* The program built for a test: the existing build when it is up to date (same sources, runtime header, TypeSOL,
|
|
124
|
+
* TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records),
|
|
125
|
+
* else a fresh one. Concurrent callers (parallel test workers) wait for each other instead of building over each other.
|
|
126
|
+
*/
|
|
127
|
+
export function buildForTest(ws, name) {
|
|
128
|
+
const paths = programPaths(ws, name);
|
|
129
|
+
return withBuildLock(paths.outDir, () => {
|
|
130
|
+
const { address } = programAddress(ws, name);
|
|
131
|
+
const current = upToDateBuild(paths, address, ws.sbpf);
|
|
132
|
+
if (current)
|
|
133
|
+
return { ...current, rebuilt: false };
|
|
134
|
+
const result = build(paths.entry, paths.outDir, address, { sbpf: ws.sbpf });
|
|
135
|
+
writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`));
|
|
136
|
+
return { address, soPath: result.soPath, idl: result.idl, rebuilt: true };
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
|
140
|
+
/** The existing build of a program if building it again would give the same files, else undefined. */
|
|
141
|
+
function upToDateBuild(paths, address, sbpf) {
|
|
142
|
+
// The compiler names a program's files after its entry file (programs/counter.ts → counter.so).
|
|
143
|
+
const base = path.join(paths.outDir, path.basename(paths.entry).replace(/\.ts$/, ""));
|
|
144
|
+
const files = { manifest: `${base}.build.json`, so: `${base}.so`, idl: `${base}.json`, client: `${base}.client.ts` };
|
|
145
|
+
if (!Object.values(files).every((f) => existsSync(f)))
|
|
146
|
+
return undefined;
|
|
147
|
+
let manifest;
|
|
148
|
+
let idl;
|
|
149
|
+
try {
|
|
150
|
+
manifest = JSON.parse(readFileSync(files.manifest, "utf8"));
|
|
151
|
+
idl = JSON.parse(readFileSync(files.idl, "utf8"));
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
if (manifest.compiler !== COMPILER_VERSION || manifest.typescript !== ts.version || manifest.sbpf !== sbpf || manifest.profile)
|
|
157
|
+
return undefined;
|
|
158
|
+
if (idl.address !== address || !manifest.sources || typeof manifest.sources !== "object")
|
|
159
|
+
return undefined;
|
|
160
|
+
if (sha256(readFileSync(files.so)) !== manifest.binary)
|
|
161
|
+
return undefined;
|
|
162
|
+
const root = path.dirname(paths.entry);
|
|
163
|
+
for (const [rel, hash] of Object.entries(manifest.sources)) {
|
|
164
|
+
const file = rel === "<runtime>/typesol_rt.h" ? path.join(RUNTIME_DIR, "typesol_rt.h") : path.resolve(root, rel);
|
|
165
|
+
if (!existsSync(file) || sha256(readFileSync(file)) !== hash)
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
// A new import changes the importing file, so every source of the current program is in the list; the runtime and
|
|
169
|
+
// the entry must be there too (a manifest from another layout).
|
|
170
|
+
if (!manifest.sources["<runtime>/typesol_rt.h"] || !manifest.sources[path.basename(paths.entry)])
|
|
171
|
+
return undefined;
|
|
172
|
+
// A manifest from before 0.44.0 has no host: rebuild once to record the toolchain in full.
|
|
173
|
+
if (!manifest.host || manifest.host.os !== process.platform || manifest.host.arch !== process.arch)
|
|
174
|
+
return undefined;
|
|
175
|
+
// Last, as it runs clang: updated platform-tools may compile the same C differently.
|
|
176
|
+
const toolchain = toolchainInfo();
|
|
177
|
+
if (manifest.clang !== toolchain.clang || manifest.platformTools !== toolchain.platformTools)
|
|
178
|
+
return undefined;
|
|
179
|
+
// A reused build came from this toolchain too: the same warning (or refusal) as building it.
|
|
180
|
+
checkToolchain(toolchain);
|
|
181
|
+
return { address, soPath: files.so, idl };
|
|
182
|
+
}
|
|
183
|
+
/** How long a build lock may be held before a waiter treats it as abandoned (a build takes seconds to a few minutes). */
|
|
184
|
+
const LOCK_STALE_MS = 15 * 60 * 1000;
|
|
185
|
+
const LOCK_POLL_MS = 100;
|
|
186
|
+
/**
|
|
187
|
+
* Run `fn` holding `<dir>/.typesol-build.lock`, created exclusively: one build of a program at a time across processes.
|
|
188
|
+
* The lock records its holder's host and pid; a lock whose process is gone (on this host) or that is older than
|
|
189
|
+
* LOCK_STALE_MS is taken over, so a crashed or killed build does not block the next one.
|
|
190
|
+
*/
|
|
191
|
+
export function withBuildLock(dir, fn) {
|
|
192
|
+
mkdirSync(dir, { recursive: true });
|
|
193
|
+
const lock = path.join(dir, ".typesol-build.lock");
|
|
194
|
+
const me = `${os.hostname()} ${process.pid} ${Date.now()}`;
|
|
195
|
+
const deadline = Date.now() + LOCK_STALE_MS + 60_000;
|
|
196
|
+
for (;;) {
|
|
197
|
+
let fd;
|
|
198
|
+
try {
|
|
199
|
+
fd = openSync(lock, "wx");
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
if (e.code !== "EEXIST")
|
|
203
|
+
throw e;
|
|
204
|
+
}
|
|
205
|
+
if (fd !== undefined) {
|
|
206
|
+
try {
|
|
207
|
+
writeSync(fd, me);
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
closeSync(fd);
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
return fn();
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
// Only our own lock: a waiter may have taken it over after LOCK_STALE_MS.
|
|
217
|
+
try {
|
|
218
|
+
if (readFileSync(lock, "utf8") === me)
|
|
219
|
+
unlinkSync(lock);
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
// Already gone.
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const holder = readLock(lock);
|
|
227
|
+
if (holder !== undefined && isStale(holder, lock)) {
|
|
228
|
+
// Read again just before removing it: another waiter may have replaced the stale lock with its own meanwhile.
|
|
229
|
+
if (readLock(lock) === holder)
|
|
230
|
+
try {
|
|
231
|
+
unlinkSync(lock);
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
// Removed by another waiter.
|
|
235
|
+
}
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (Date.now() > deadline)
|
|
239
|
+
throw new Error(`timed out waiting for ${lock} (held by ${holder ?? "?"}); delete it if no build is running`);
|
|
240
|
+
sleepSync(LOCK_POLL_MS);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function readLock(lock) {
|
|
244
|
+
try {
|
|
245
|
+
return readFileSync(lock, "utf8");
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function isStale(holder, lock) {
|
|
252
|
+
const [host, pid] = holder.split(" ");
|
|
253
|
+
let age;
|
|
254
|
+
try {
|
|
255
|
+
age = Date.now() - statSync(lock).mtimeMs;
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
if (age > LOCK_STALE_MS)
|
|
261
|
+
return true;
|
|
262
|
+
// An empty or partly written lock: its writer is between open and write, unless it died there.
|
|
263
|
+
if (!host || !pid || !/^\d+$/.test(pid))
|
|
264
|
+
return age > 10_000;
|
|
265
|
+
if (host !== os.hostname())
|
|
266
|
+
return false;
|
|
267
|
+
try {
|
|
268
|
+
process.kill(Number(pid), 0);
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
catch (e) {
|
|
272
|
+
// EPERM: the process exists but belongs to another user.
|
|
273
|
+
return e.code === "ESRCH";
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
277
|
+
/** Block this thread (builds are synchronous, so waiting for one is too). */
|
|
278
|
+
function sleepSync(ms) {
|
|
279
|
+
Atomics.wait(sleeper, 0, 0, ms);
|
|
280
|
+
}
|
|
114
281
|
/** The `solana program deploy` arguments for one built program (deploying again upgrades it). */
|
|
115
282
|
export function deployArgs(soPath, keypair, opts) {
|
|
116
283
|
const args = ["program", "deploy", soPath, "--program-id", keypair, "--use-rpc"];
|
package/docs/ai.md
CHANGED
|
@@ -23,7 +23,8 @@ own project notes below them in AGENTS.md.
|
|
|
23
23
|
([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
|
|
24
24
|
and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
|
|
25
25
|
in one file, to paste into a chat or give to a model as context. Both also ship in the npm package
|
|
26
|
-
(`node_modules/typesol/llms-full.txt`
|
|
26
|
+
(`node_modules/typesol/llms-full.txt` in a project `typesol init` created, which installs `@typesol/cli` under the
|
|
27
|
+
name `typesol`; `node_modules/@typesol/cli/llms-full.txt` where it is installed under its own name).
|
|
27
28
|
|
|
28
29
|
## Errors an agent can fix by itself
|
|
29
30
|
|
|
@@ -34,13 +35,17 @@ in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on ch
|
|
|
34
35
|
## The MCP server
|
|
35
36
|
|
|
36
37
|
`typesol mcp` serves the [Model Context Protocol](https://modelcontextprotocol.io) on stdio. `typesol init` writes
|
|
37
|
-
`.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx typesol mcp
|
|
38
|
-
|
|
38
|
+
`.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx --no-install typesol mcp`: the
|
|
39
|
+
project's own copy, after `npm install`. `--no-install` matters: `typesol` is not the npm package's name, and without
|
|
40
|
+
it npx would fetch whatever package is published as `typesol` when the project's copy is missing. Other clients take
|
|
41
|
+
the same command, run in the project directory:
|
|
39
42
|
|
|
40
43
|
```json
|
|
41
|
-
{ "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
|
|
44
|
+
{ "mcpServers": { "typesol": { "command": "npx", "args": ["--no-install", "typesol", "mcp"] } } }
|
|
42
45
|
```
|
|
43
46
|
|
|
47
|
+
Outside a project, start it from the published package by its full name: `npx -y @typesol/cli mcp`.
|
|
48
|
+
|
|
44
49
|
| Tool | What it does |
|
|
45
50
|
| --- | --- |
|
|
46
51
|
| `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
|
|
@@ -48,5 +53,5 @@ same command:
|
|
|
48
53
|
| `docs` | searches the docs and returns the best-matching sections |
|
|
49
54
|
| `rules` | the rules above |
|
|
50
55
|
|
|
51
|
-
Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
|
|
56
|
+
Building and testing stay in the shell (`npm test`, `npx --no-install typesol build`): they need the platform-tools and write
|
|
52
57
|
files, which an agent should do in the open.
|
package/docs/architecture.md
CHANGED
|
@@ -103,7 +103,7 @@ representation in between. We reviewed this on 2026-10-30 and kept it that way f
|
|
|
103
103
|
named in the source, see `alias.ts`), a second backend (SBF without clang), and optimizations clang cannot see
|
|
104
104
|
because they depend on account semantics (dropping a repeated check, packing a `@layout borsh` account only where
|
|
105
105
|
it changed).
|
|
106
|
-
- **What it would cost now:** rewriting most of the compiler's
|
|
106
|
+
- **What it would cost now:** rewriting most of the compiler's 20,000 lines, and losing the property every release
|
|
107
107
|
relies on: programs that do not use a change compile to the same binaries. Audit scope and differential results
|
|
108
108
|
would start over.
|
|
109
109
|
- **What we have instead:** the layers above, each owning one concern; `Ref` / `Value` as the typed place and value
|