@typesol/cli 0.29.0 → 0.31.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.
- package/CHANGELOG.md +27 -0
- package/README.md +5 -2
- package/dist/cli.js +13 -20
- package/dist/compiler/analyze.d.ts +3 -1
- package/dist/compiler/analyze.js +36 -8
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/diagnostics.js +3 -2
- package/dist/compiler/emit/calls.js +32 -0
- package/dist/compiler/emit/shared.d.ts +2 -0
- package/dist/compiler/index.js +1 -1
- package/dist/workspace.d.ts +1 -1
- package/dist/workspace.js +3 -1
- package/docs/architecture.md +1 -1
- package/docs/case-study-raydium-cp-swap.md +122 -0
- package/docs/cli.md +7 -4
- package/docs/language.md +1 -1
- package/lib/typesol.d.ts +15 -0
- package/package.json +1 -1
- package/runtime/typesol_rt.h +56 -0
- package/ts-plugin/index.js +75 -39
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,33 @@ codes, and says so here.
|
|
|
6
6
|
|
|
7
7
|
## Unreleased
|
|
8
8
|
|
|
9
|
+
## 0.31.0 — 2026-10-30
|
|
10
|
+
|
|
11
|
+
A second real program checked against its mainnet binary: Raydium CP-Swap's trading core, and the Token-2022 reads an
|
|
12
|
+
AMM needs. Programs that do not use the new reads compile to the same binaries as in 0.30.0.
|
|
13
|
+
|
|
14
|
+
- New: Token-2022 fee and extension reads: `transferFeeInverse(mint, amountReceived)` (spl-token-2022's
|
|
15
|
+
`calculate_inverse_epoch_fee`: what to send so the recipient gets that much), `transferFeeBasisPoints(mint)` and
|
|
16
|
+
`transferFeeMaximum(mint)` (this epoch's), and `extensionsWithin(account, [types…])` (accept only mints whose
|
|
17
|
+
extensions you handle).
|
|
18
|
+
- New: examples/raydium-cp-swap, Raydium CP-Swap's trading core (swaps both ways, deposit, withdraw, fee collection,
|
|
19
|
+
config and status admin; 9 of its 24 instructions), checked against the program deployed on mainnet on 59
|
|
20
|
+
transactions (creator fees, the price oracle's wrap and Token-2022 transfer fees included): same outcomes, account
|
|
21
|
+
bytes and events, 51–79% fewer compute units. docs/case-study-raydium-cp-swap.md.
|
|
22
|
+
|
|
23
|
+
## 0.30.0 — 2026-10-30
|
|
24
|
+
|
|
25
|
+
Editor errors that follow you through a program, faster. The compiler's output is the same as 0.29.0 for every
|
|
26
|
+
program.
|
|
27
|
+
|
|
28
|
+
- Changed: `typesol/ts-plugin` shows the compiler's refusals in every file of a program (a helper or state file the
|
|
29
|
+
entry imports, not only the entry), for the unsaved text of every open file, underlining the whole construct.
|
|
30
|
+
- Changed: the plugin runs the compiler inside the editor's TypeScript server once it has loaded (a check takes
|
|
31
|
+
milliseconds instead of starting a process), and `typesol init` writes `.vscode/settings.json` so VS Code offers the
|
|
32
|
+
workspace's TypeScript, which loads the plugin.
|
|
33
|
+
- New: `typesol check --files` reads `{ "files": { "<path>": "<text>" } }` from stdin (unsaved buffers of any file);
|
|
34
|
+
`--json` diagnostics carry a `length`. The compiler's `generate(entry, { files })` takes the same overrides.
|
|
35
|
+
|
|
9
36
|
## 0.29.0 — 2026-10-30
|
|
10
37
|
|
|
11
38
|
The remaining Anchor gaps: declarative constraints in Anchor's order, Anchor's unbounded `Vec` in Borsh accounts, and
|
package/README.md
CHANGED
|
@@ -176,7 +176,9 @@ program's address.
|
|
|
176
176
|
Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, `typesol port`
|
|
177
177
|
starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one complete Anchor
|
|
178
178
|
program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
|
|
179
|
-
checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units)
|
|
179
|
+
checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units), and
|
|
180
|
+
[docs/case-study-raydium-cp-swap.md](docs/case-study-raydium-cp-swap.md) does the same for Raydium CP-Swap's swaps and liquidity
|
|
181
|
+
(same outcomes, account bytes and events on 59 transactions; 51–79% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
|
|
180
182
|
mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
|
|
181
183
|
|
|
182
184
|
## How it works
|
|
@@ -225,7 +227,7 @@ The full reference, with every type, check and built-in, is in [docs/language.md
|
|
|
225
227
|
| `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
|
|
226
228
|
| `typesol client <idl.json>` | generate a typed TypeScript client from an Anchor IDL (`typesol build` writes one per program) |
|
|
227
229
|
| `typesol port` | a TypeSOL skeleton of an Anchor program from its IDL, keeping discriminators and error codes |
|
|
228
|
-
| `typesol/ts-plugin` | the compiler's errors in the editor as you type ([docs/cli.md](docs/cli.md#editor)) |
|
|
230
|
+
| `typesol/ts-plugin` | the compiler's errors in the editor as you type, in every file of a program ([docs/cli.md](docs/cli.md#editor)) |
|
|
229
231
|
| `typesol verify` | rebuild from source and compare with the program and IDL on chain (or a dumped `.so`) |
|
|
230
232
|
| `typesol profile` | compute units per TypeScript line, from a `--profile` build's logs |
|
|
231
233
|
| `typesol emit-c` | print the generated C |
|
|
@@ -324,6 +326,7 @@ Details are in [docs/testing.md](docs/testing.md).
|
|
|
324
326
|
| [`relay.ts`](examples/relay.ts), [`caller.ts`](examples/caller.ts) | generic `invoke`, PDA-signed transfers, return data |
|
|
325
327
|
| [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
|
|
326
328
|
| [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
|
|
329
|
+
| [`raydium-cp-swap/`](examples/raydium-cp-swap) | Raydium CP-Swap's trading core: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle |
|
|
327
330
|
| [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
|
|
328
331
|
|
|
329
332
|
## Status
|
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,6 @@ 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 ts from "typescript";
|
|
9
8
|
import { build, CompileError, COMPILER_VERSION, generate, SBPF_VERSIONS, verifyBinary } from "./compiler/index.js";
|
|
10
9
|
import { generateCpi } from "./tools/cpigen.js";
|
|
11
10
|
import { generatePort } from "./tools/portgen.js";
|
|
@@ -44,7 +43,7 @@ const COMMANDS = {
|
|
|
44
43
|
init: {
|
|
45
44
|
usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
|
|
46
45
|
help: [
|
|
47
|
-
"Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore.",
|
|
46
|
+
"Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors).",
|
|
48
47
|
"Refuses to overwrite files. <name> must be snake_case (default: derived from <dir>).",
|
|
49
48
|
"--template counter a PDA counter per user (default)",
|
|
50
49
|
"--template vault a SOL vault at a PDA: deposit, withdraw above rent, close",
|
|
@@ -132,20 +131,27 @@ const COMMANDS = {
|
|
|
132
131
|
},
|
|
133
132
|
},
|
|
134
133
|
check: {
|
|
135
|
-
usage: "typesol check <program.ts> [--json] [--stdin]",
|
|
134
|
+
usage: "typesol check <program.ts> [--json] [--stdin | --files]",
|
|
136
135
|
help: [
|
|
137
136
|
"Typecheck and validate the TypeSOL subset without building.",
|
|
138
137
|
"--json print { ok, diagnostics: [{ file, line, column, message }] } (exit 1 when there are diagnostics)",
|
|
139
138
|
"--stdin read <program.ts>'s text from stdin instead of the file (an editor's unsaved buffer); its imports are read from disk",
|
|
139
|
+
'--files read { "files": { "<absolute path>": "<text>", … } } from stdin: those files\' texts instead of the disk (unsaved buffers)',
|
|
140
140
|
].join("\n "),
|
|
141
|
-
options: { json: { type: "boolean" }, stdin: { type: "boolean" } },
|
|
141
|
+
options: { json: { type: "boolean" }, stdin: { type: "boolean" }, files: { type: "boolean" } },
|
|
142
142
|
run(v, args) {
|
|
143
143
|
const file = path.resolve(one(args, "<program.ts>"));
|
|
144
|
-
|
|
144
|
+
let files;
|
|
145
|
+
if (v.stdin)
|
|
146
|
+
files = new Map([[file, readFileSync(0, "utf8")]]);
|
|
147
|
+
else if (v.files) {
|
|
148
|
+
const given = JSON.parse(readFileSync(0, "utf8")).files ?? {};
|
|
149
|
+
files = new Map(Object.entries(given).map(([p, t]) => [path.resolve(p), t]));
|
|
150
|
+
}
|
|
145
151
|
try {
|
|
146
|
-
if (!
|
|
152
|
+
if (!files?.has(file))
|
|
147
153
|
mustExist(file);
|
|
148
|
-
const { model } = generate(file);
|
|
154
|
+
const { model } = generate(file, { files });
|
|
149
155
|
if (v.json)
|
|
150
156
|
log(JSON.stringify({ ok: true, diagnostics: [] }));
|
|
151
157
|
else
|
|
@@ -158,9 +164,6 @@ const COMMANDS = {
|
|
|
158
164
|
log(JSON.stringify({ ok: false, diagnostics: e.diagnostics }));
|
|
159
165
|
return 1;
|
|
160
166
|
}
|
|
161
|
-
finally {
|
|
162
|
-
restore?.();
|
|
163
|
-
}
|
|
164
167
|
},
|
|
165
168
|
},
|
|
166
169
|
"emit-c": {
|
|
@@ -517,16 +520,6 @@ function readJson(file) {
|
|
|
517
520
|
}
|
|
518
521
|
}
|
|
519
522
|
/** Make the compiler read `text` for `file` (instead of the disk) until the returned function is called. */
|
|
520
|
-
function overrideFile(file, text) {
|
|
521
|
-
const sys = ts.sys;
|
|
522
|
-
const { readFile, fileExists } = sys;
|
|
523
|
-
sys.readFile = (p, enc) => (path.resolve(p) === file ? text : readFile.call(sys, p, enc));
|
|
524
|
-
sys.fileExists = (p) => path.resolve(p) === file || fileExists.call(sys, p);
|
|
525
|
-
return () => {
|
|
526
|
-
sys.readFile = readFile;
|
|
527
|
-
sys.fileExists = fileExists;
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
523
|
/** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
|
|
531
524
|
function solanaConfig(file) {
|
|
532
525
|
const cfg = readSolanaConfig(file);
|
|
@@ -47,9 +47,11 @@ export interface TypeScope {
|
|
|
47
47
|
}
|
|
48
48
|
export declare function snakeCase(name: string): string;
|
|
49
49
|
export declare function discriminator(preimage: string): number[];
|
|
50
|
+
/** Source text by absolute path: an editor's unsaved buffers, read instead of the files on disk. */
|
|
51
|
+
export type SourceOverrides = ReadonlyMap<string, string>;
|
|
50
52
|
/** Resolve a relative import to a `.ts` file next to `from`, or undefined. */
|
|
51
53
|
export declare function resolveRelative(from: string, spec: string): string | undefined;
|
|
52
|
-
export declare function analyze(entry: string): Analysis;
|
|
54
|
+
export declare function analyze(entry: string, files?: SourceOverrides): Analysis;
|
|
53
55
|
/**
|
|
54
56
|
* Instruction-argument types beyond scalars: a fixed-size struct (`p: Point`), `FixedArray<T, N>`, or
|
|
55
57
|
* `Vec<Struct>`. They are Borsh-identical to TypeSOL's fixed layouts, so they are copied as is and validated.
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -145,7 +145,12 @@ export function discriminator(preimage) {
|
|
|
145
145
|
return [...createHash("sha256").update(preimage).digest().subarray(0, 8)];
|
|
146
146
|
}
|
|
147
147
|
/** Run the TypeScript checker over the entry file with `typesol` mapped to our declarations. */
|
|
148
|
-
|
|
148
|
+
/**
|
|
149
|
+
* Library declarations (TypeScript's lib files, typesol.d.ts) parsed once per process: an editor checks the same
|
|
150
|
+
* program on every keystroke, and these never change.
|
|
151
|
+
*/
|
|
152
|
+
const libSourceFiles = new Map();
|
|
153
|
+
function typecheck(entry, files) {
|
|
149
154
|
const options = {
|
|
150
155
|
strict: true,
|
|
151
156
|
noEmit: true,
|
|
@@ -157,7 +162,30 @@ function typecheck(entry) {
|
|
|
157
162
|
paths: { typesol: [LIB_PATH] },
|
|
158
163
|
skipLibCheck: true,
|
|
159
164
|
};
|
|
160
|
-
const
|
|
165
|
+
const host = ts.createCompilerHost(options);
|
|
166
|
+
const getSourceFile = host.getSourceFile.bind(host);
|
|
167
|
+
host.getSourceFile = (fileName, language, onError, shouldCreate) => {
|
|
168
|
+
const text = files?.get(path.resolve(fileName));
|
|
169
|
+
if (text !== undefined)
|
|
170
|
+
return ts.createSourceFile(fileName, text, language, true);
|
|
171
|
+
const lib = fileName.endsWith(".d.ts") && (path.resolve(fileName) === LIB_PATH || fileName.includes(`${path.sep}typescript${path.sep}lib${path.sep}`));
|
|
172
|
+
if (!lib)
|
|
173
|
+
return getSourceFile(fileName, language, onError, shouldCreate);
|
|
174
|
+
let sf = libSourceFiles.get(fileName);
|
|
175
|
+
if (!sf) {
|
|
176
|
+
sf = getSourceFile(fileName, language, onError, shouldCreate);
|
|
177
|
+
if (sf)
|
|
178
|
+
libSourceFiles.set(fileName, sf);
|
|
179
|
+
}
|
|
180
|
+
return sf;
|
|
181
|
+
};
|
|
182
|
+
if (files) {
|
|
183
|
+
const readFile = host.readFile.bind(host);
|
|
184
|
+
const fileExists = host.fileExists.bind(host);
|
|
185
|
+
host.readFile = (f) => files.get(path.resolve(f)) ?? readFile(f);
|
|
186
|
+
host.fileExists = (f) => files.has(path.resolve(f)) || fileExists(f);
|
|
187
|
+
}
|
|
188
|
+
const program = ts.createProgram([entry], options, host);
|
|
161
189
|
const sourceFile = program.getSourceFile(entry);
|
|
162
190
|
if (!sourceFile)
|
|
163
191
|
throw new CompileError([{ file: entry, line: 1, column: 1, message: "cannot read source file" }]);
|
|
@@ -170,7 +198,7 @@ function typecheck(entry) {
|
|
|
170
198
|
if (!d.file || d.start === undefined)
|
|
171
199
|
return { file: entry, line: 1, column: 1, message };
|
|
172
200
|
const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
|
|
173
|
-
return { file: d.file.fileName, line: line + 1, column: character + 1, message };
|
|
201
|
+
return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length };
|
|
174
202
|
});
|
|
175
203
|
throw new CompileError(diagnostics);
|
|
176
204
|
}
|
|
@@ -190,14 +218,14 @@ export function resolveRelative(from, spec) {
|
|
|
190
218
|
* Reject foreign imports before typechecking so the user sees why, not "cannot find module".
|
|
191
219
|
* Follows relative imports so every file of the program is checked.
|
|
192
220
|
*/
|
|
193
|
-
function checkImports(entry) {
|
|
221
|
+
function checkImports(entry, files) {
|
|
194
222
|
const reporter = new Reporter();
|
|
195
223
|
const seen = new Set();
|
|
196
224
|
const visit = (file) => {
|
|
197
225
|
if (seen.has(file))
|
|
198
226
|
return;
|
|
199
227
|
seen.add(file);
|
|
200
|
-
const text = ts.sys.readFile(file);
|
|
228
|
+
const text = files?.get(file) ?? ts.sys.readFile(file);
|
|
201
229
|
if (text === undefined)
|
|
202
230
|
throw new CompileError([{ file, line: 1, column: 1, message: "cannot read source file" }]);
|
|
203
231
|
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, true);
|
|
@@ -241,10 +269,10 @@ function programFiles(program, entry) {
|
|
|
241
269
|
visit(entry);
|
|
242
270
|
return order;
|
|
243
271
|
}
|
|
244
|
-
export function analyze(entry) {
|
|
272
|
+
export function analyze(entry, files) {
|
|
245
273
|
const entryPath = path.resolve(entry);
|
|
246
|
-
checkImports(entryPath);
|
|
247
|
-
const { program, sourceFile } = typecheck(entryPath);
|
|
274
|
+
checkImports(entryPath, files);
|
|
275
|
+
const { program, sourceFile } = typecheck(entryPath, files);
|
|
248
276
|
const reporter = new Reporter();
|
|
249
277
|
const errorEnums = new Map();
|
|
250
278
|
const enums = new Map();
|
|
@@ -4,6 +4,8 @@ export interface Diagnostic {
|
|
|
4
4
|
line: number;
|
|
5
5
|
column: number;
|
|
6
6
|
message: string;
|
|
7
|
+
/** Characters the problem spans from line:column (the construct refused), when known. */
|
|
8
|
+
length?: number;
|
|
7
9
|
}
|
|
8
10
|
export declare class CompileError extends Error {
|
|
9
11
|
readonly diagnostics: Diagnostic[];
|
|
@@ -11,8 +11,9 @@ export function formatDiagnostic(d) {
|
|
|
11
11
|
}
|
|
12
12
|
export function diagnosticAt(node, message) {
|
|
13
13
|
const sf = node.getSourceFile();
|
|
14
|
-
const
|
|
15
|
-
|
|
14
|
+
const start = node.getStart(sf);
|
|
15
|
+
const { line, character } = sf.getLineAndCharacterOfPosition(start);
|
|
16
|
+
return { file: sf.fileName, line: line + 1, column: character + 1, message, length: Math.max(1, node.getEnd() - start) };
|
|
16
17
|
}
|
|
17
18
|
/** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
|
|
18
19
|
export class Reporter {
|
|
@@ -241,6 +241,38 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
241
241
|
this.line(`TS_TRY(ts_t22_transfer_fee(${m}, ${amt.c}, &${t}));`);
|
|
242
242
|
return { c: t, type: U64 };
|
|
243
243
|
}
|
|
244
|
+
case "transferFeeInverse": {
|
|
245
|
+
if (args.length !== 2)
|
|
246
|
+
this.fail(node, "transferFeeInverse(mint, amountReceived) takes the mint and the amount the recipient is to get");
|
|
247
|
+
const m = this.anyAccount(args[0], "the mint");
|
|
248
|
+
this.line(`TS_TRY(ts_t22_layout(${m}, 1));`);
|
|
249
|
+
const amt = this.expect(this.expr(args[1], U64), U64, args[1]);
|
|
250
|
+
const t = this.tmp("fee");
|
|
251
|
+
this.line(`uint64_t ${t};`);
|
|
252
|
+
this.line(`TS_TRY(ts_t22_transfer_fee_inverse(${m}, ${amt.c}, &${t}));`);
|
|
253
|
+
return { c: t, type: U64 };
|
|
254
|
+
}
|
|
255
|
+
case "transferFeeBasisPoints":
|
|
256
|
+
case "transferFeeMaximum": {
|
|
257
|
+
if (args.length !== 1)
|
|
258
|
+
this.fail(node, `${builtin}(mint) takes the mint`);
|
|
259
|
+
const m = this.anyAccount(args[0], "the mint");
|
|
260
|
+
this.line(`TS_TRY(ts_t22_layout(${m}, 1));`);
|
|
261
|
+
const t = this.tmp("tf");
|
|
262
|
+
this.line(`uint64_t ${t}b, ${t}m;`);
|
|
263
|
+
this.line(`TS_TRY(ts_t22_epoch_fee(${m}, &${t}b, &${t}m));`);
|
|
264
|
+
return builtin === "transferFeeBasisPoints" ? { c: `((uint16_t)${t}b)`, type: { kind: "int", name: "u16" } } : { c: `${t}m`, type: U64 };
|
|
265
|
+
}
|
|
266
|
+
case "extensionsWithin": {
|
|
267
|
+
if (args.length !== 2 || !ts.isArrayLiteralExpression(args[1]))
|
|
268
|
+
this.fail(node, "extensionsWithin(account, [types…]) takes a Token-2022 mint or account and a list of u16 extension types");
|
|
269
|
+
const m = this.anyAccount(args[0], "the account");
|
|
270
|
+
this.line(`TS_TRY(ts_t22_layout(${m}, 0));`);
|
|
271
|
+
const types = args[1].elements.map((e) => this.expect(this.expr(e, { kind: "int", name: "u16" }), { kind: "int", name: "u16" }, e).c);
|
|
272
|
+
const t = this.tmp("ext");
|
|
273
|
+
this.line(`const uint16_t ${t}[${Math.max(types.length, 1)}] = {${types.join(", ")}};`);
|
|
274
|
+
return { c: `ts_t22_extensions_within(${m}, ${t}, ${types.length})`, type: BOOL };
|
|
275
|
+
}
|
|
244
276
|
case "isTransferring": {
|
|
245
277
|
// TransferHookAccount (15) on a Token-2022 token account: set only while Token-2022 runs a transfer of it.
|
|
246
278
|
if (args.length !== 1)
|
|
@@ -128,6 +128,8 @@ export declare function helperSignature(h: Helper): string;
|
|
|
128
128
|
export interface EmitOptions {
|
|
129
129
|
/** Log a marker and the remaining compute units before every statement (`typesol build --profile`). */
|
|
130
130
|
profile?: boolean;
|
|
131
|
+
/** Source text by absolute path (an editor's unsaved buffers), read instead of the files on disk. */
|
|
132
|
+
files?: ReadonlyMap<string, string>;
|
|
131
133
|
}
|
|
132
134
|
/** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
|
|
133
135
|
export declare function laterVecC(s: string, field: string): string;
|
package/dist/compiler/index.js
CHANGED
|
@@ -12,7 +12,7 @@ export { CompileError, formatDiagnostic } from "./diagnostics.js";
|
|
|
12
12
|
export { SBPF_VERSIONS } from "./toolchain.js";
|
|
13
13
|
/** Typecheck, enforce the TypeSOL subset, and generate C. Throws CompileError with every diagnostic. */
|
|
14
14
|
export function generate(entry, opts = {}) {
|
|
15
|
-
const analysis = analyze(entry);
|
|
15
|
+
const analysis = analyze(entry, opts.files);
|
|
16
16
|
analysis.reporter.throwIfAny();
|
|
17
17
|
const c = emitProgram(analysis, opts);
|
|
18
18
|
analysis.reporter.throwIfAny();
|
package/dist/workspace.d.ts
CHANGED
|
@@ -48,5 +48,5 @@ export declare function deployArgs(soPath: string, keypair: string, opts: {
|
|
|
48
48
|
payer?: string;
|
|
49
49
|
config?: string;
|
|
50
50
|
}): string[];
|
|
51
|
-
/** Create a project: typesol.json, one program from a template, its LiteSVM test, configs. Refuses to overwrite files. */
|
|
51
|
+
/** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
|
|
52
52
|
export declare function scaffold(dir: string, name: string, template?: TemplateName): string[];
|
package/dist/workspace.js
CHANGED
|
@@ -105,7 +105,7 @@ export function deployArgs(soPath, keypair, opts) {
|
|
|
105
105
|
args.push("--keypair", opts.payer);
|
|
106
106
|
return args;
|
|
107
107
|
}
|
|
108
|
-
/** Create a project: typesol.json, one program from a template, its LiteSVM test, configs. Refuses to overwrite files. */
|
|
108
|
+
/** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
|
|
109
109
|
export function scaffold(dir, name, template = "counter") {
|
|
110
110
|
const t = TEMPLATES[template];
|
|
111
111
|
if (!/^[a-z][a-z0-9_]*$/.test(name))
|
|
@@ -146,6 +146,8 @@ export function scaffold(dir, name, template = "counter") {
|
|
|
146
146
|
...t.devDependencies,
|
|
147
147
|
},
|
|
148
148
|
}, null, 2) + "\n",
|
|
149
|
+
// VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
|
|
150
|
+
".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
|
|
149
151
|
// target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
|
|
150
152
|
".gitignore": "node_modules/\n# target/deploy/*-keypair.json are the programs' addresses (and upgrade keys): never commit them, but BACK THEM UP.\n# A fresh clone cannot build or deploy a program whose address is recorded in typesol.json without its keypair.\ntarget/\n",
|
|
151
153
|
"tsconfig.json": JSON.stringify({
|
package/docs/architecture.md
CHANGED
|
@@ -60,7 +60,7 @@ program.so + program.build.json (manifest: versions, sha256 of sources and binar
|
|
|
60
60
|
| `src/templates.ts` | The programs and tests `typesol init --template` writes (copies of `examples/`; a test checks they match). |
|
|
61
61
|
| `src/tools/svmrpc.ts` | `svmConnection`: a kit RPC and subscriptions pair answered by LiteSVM, so generated clients run in tests (exported by `typesol/testing`). |
|
|
62
62
|
| `src/keys.ts` | Base58 and program keypair helpers. |
|
|
63
|
-
| `ts-plugin/index.js` | `typesol/ts-plugin` (CommonJS, loaded by tsserver):
|
|
63
|
+
| `ts-plugin/index.js` | `typesol/ts-plugin` (CommonJS, loaded by tsserver): checks the program entries with the editor's texts (`generate(entry, { files })`, in-process once `dist/compiler` has loaded, `typesol check --json --files` before) and adds each diagnostic to the file it is in. |
|
|
64
64
|
| `src/testing.ts` | `typesol/testing`: LiteSVM test helpers for projects (accounts by name from the IDL, plain values). |
|
|
65
65
|
| `src/tools/onchain.ts` | `typesol verify --address`: a deployed program's ELF, authority and deploy slot under loader v2, v3 or v4. |
|
|
66
66
|
| `src/tools/profile.ts` | Turns `--profile` logs into compute units per source line. |
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Case study: Raydium CP-Swap
|
|
2
|
+
|
|
3
|
+
This page ports the trading core of a production AMM: [Raydium CP-Swap](https://github.com/raydium-io/raydium-cp-swap)
|
|
4
|
+
(`programs/cp-swap`, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
|
|
5
|
+
`CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`examples/raydium-cp-swap/`](../examples/raydium-cp-swap)
|
|
6
|
+
(`state.ts`, `curve.ts`, `raydium_cp_swap.ts`). As with [coral-xyz/multisig](case-study-multisig.md), it is checked
|
|
7
|
+
against the binary that runs on mainnet, not a rebuild.
|
|
8
|
+
|
|
9
|
+
## What is ported
|
|
10
|
+
|
|
11
|
+
The port covers 9 of the original's 24 instructions:
|
|
12
|
+
|
|
13
|
+
- the four trading instructions: `swap_base_input`, `swap_base_output`, `deposit` and `withdraw`;
|
|
14
|
+
- `collect_protocol_fee` and `collect_fund_fee`;
|
|
15
|
+
- the admin instructions `create_amm_config`, `update_amm_config` and `update_pool_status`.
|
|
16
|
+
|
|
17
|
+
The port keeps the original's account layouts:
|
|
18
|
+
|
|
19
|
+
- `AmmConfig` is a Borsh account of fixed size.
|
|
20
|
+
- `PoolState` and `ObservationState` are zero-copy `#[repr(C, packed)]` structs, which is TypeSOL's fixed layout.
|
|
21
|
+
|
|
22
|
+
It also keeps the original's names, argument order and error codes, and emits the same events (`SwapEvent`,
|
|
23
|
+
`LpChangeEvent`). Existing pools, clients and indexers work with it unchanged.
|
|
24
|
+
|
|
25
|
+
These are not ported yet:
|
|
26
|
+
|
|
27
|
+
- **`initialize` and `initialize_with_permission`.** They create a pool at either a PDA or a signer keypair, chosen at
|
|
28
|
+
run time, and allocate a program account by hand: transfer, allocate and assign when the address was pre-funded.
|
|
29
|
+
TypeSOL's `Init<T>` fixes the choice at compile time and reports an existing account with its own error.
|
|
30
|
+
- **The creator-fee instructions**: `collect_creator_fee`, `collect_creator_fee_permissionless`,
|
|
31
|
+
`create_creator_fee_share` and `close_creator_fee_share`.
|
|
32
|
+
- **The permission instructions**: `create_permission_pda` and `close_permission_pda`.
|
|
33
|
+
- **The support-mint instructions**: `create_support_mint_associated` and `close_support_mint_associated`.
|
|
34
|
+
- **`collect_excess_lamports`.**
|
|
35
|
+
|
|
36
|
+
The pool logic these depend on is in the port (fee booking, the creator-fee split in the swap math, tested below with
|
|
37
|
+
the creator fee on), so a pool the original created and configured is traded the same way.
|
|
38
|
+
|
|
39
|
+
## What it needed
|
|
40
|
+
|
|
41
|
+
Four Token-2022 reads, added to the compiler for this port (`test/integrations/t22ext.test.ts`):
|
|
42
|
+
|
|
43
|
+
- `transferFeeInverse(mint, amountReceived)`: spl-token-2022's `calculate_inverse_epoch_fee`, used for deposits and
|
|
44
|
+
exact-output swaps.
|
|
45
|
+
- `transferFeeBasisPoints(mint)` and `transferFeeMaximum(mint)`: the fee in force this epoch.
|
|
46
|
+
- `extensionsWithin(account, [types])`: the original's list of mint extensions a pool accepts.
|
|
47
|
+
|
|
48
|
+
The rest uses features TypeSOL already had:
|
|
49
|
+
|
|
50
|
+
- `constraint(…)`, for Anchor's `address = pool_state.load()?.amm_config` and `constraint = …` in Anchor's order;
|
|
51
|
+
- u128 arithmetic for the constant-product curve and the price oracle;
|
|
52
|
+
- token CPIs signed by the pool authority PDA;
|
|
53
|
+
- events.
|
|
54
|
+
|
|
55
|
+
## How it was checked
|
|
56
|
+
|
|
57
|
+
[`test/examples/raydium-cp-swap.test.ts`](../test/examples/raydium-cp-swap.test.ts) loads the binary dumped from
|
|
58
|
+
mainnet on 2026-10-30 (slot 452376460; sha256 in [`test/programs/SOURCES.md`](../test/programs/SOURCES.md)) into one
|
|
59
|
+
LiteSVM and the port into another. Both use the same program id and the same clock.
|
|
60
|
+
|
|
61
|
+
**Setup.**
|
|
62
|
+
|
|
63
|
+
- Mints and token accounts are made by the same SPL Token / Token-2022 instructions in both.
|
|
64
|
+
- The program's own accounts (an `AmmConfig`, a pool's `PoolState` and its `ObservationState`) are written in both as
|
|
65
|
+
the original lays them out, because creating a config needs Raydium's admin key.
|
|
66
|
+
|
|
67
|
+
**Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
|
|
68
|
+
code), the same lamports, owner and data for every account involved, and the same events byte for byte.
|
|
69
|
+
|
|
70
|
+
There are 59 transactions:
|
|
71
|
+
|
|
72
|
+
- **Swaps.** Both directions, by input and by output; the observation ring advancing as the clock moves; slippage
|
|
73
|
+
(6005); zero amounts.
|
|
74
|
+
- **Liquidity.** Deposit, a partial withdrawal, slippage both ways, withdrawing more LP than held, zero.
|
|
75
|
+
- **Fees.** Protocol and fund fees collected by their owners after trading, and refused for anyone else (6001).
|
|
76
|
+
- **Creator fees.** Pools with the creator fee on at 0.05%, taken from the input token, only token_0, or only
|
|
77
|
+
token_1: swaps both ways, by input and by output, booking the fee on the right side.
|
|
78
|
+
- **The price oracle.** A new point, a second swap within 15 seconds (added to the current point), and a ring at its
|
|
79
|
+
last slot whose cumulative price is 10 below `u128::MAX`: the next point wraps to slot 0 and the sum wraps around.
|
|
80
|
+
- **Token-2022.** A pool of two transfer-fee mints (1.5% and 0.37%): swaps both ways and by output, deposit and
|
|
81
|
+
withdrawal, through the inverse-fee path; and a pool of Token-2022 mints without a fee.
|
|
82
|
+
- **Refusals.**
|
|
83
|
+
- Another config (2012), another pool's vault (2003), another observation account (2012) or mint (2012).
|
|
84
|
+
- The same vault twice, a wrong pool authority (2006), another trader's account.
|
|
85
|
+
- Wrong vaults or LP mint on deposit (6004), the wrong token program.
|
|
86
|
+
- Swaps or deposits on a pool whose status disables them (6000).
|
|
87
|
+
- The admin instructions sent by anyone but the admin (2012, 6001).
|
|
88
|
+
|
|
89
|
+
## Cost
|
|
90
|
+
|
|
91
|
+
Compute units per transaction, mainnet original against the port, from that test:
|
|
92
|
+
|
|
93
|
+
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
94
|
+
| --- | ---: | ---: | ---: |
|
|
95
|
+
| `swap_base_input` | 24,142 | 7,478 | −69% |
|
|
96
|
+
| `swap_base_output` | 24,571 | 8,029 | −67% |
|
|
97
|
+
| `deposit` | 25,004 | 6,594 | −74% |
|
|
98
|
+
| `withdraw` | 25,211 | 6,451 | −74% |
|
|
99
|
+
| `collect_protocol_fee` | 20,205 | 4,200 | −79% |
|
|
100
|
+
| `swap_base_input`, Token-2022 transfer fees | 31,334 | 13,813 | −56% |
|
|
101
|
+
| `swap_base_output`, Token-2022 transfer fees | 32,511 | 15,935 | −51% |
|
|
102
|
+
| `deposit`, Token-2022 transfer fees | 33,206 | 14,834 | −55% |
|
|
103
|
+
|
|
104
|
+
The Token-2022 rows include the token program's own work, which is the same in both. Refusals cost far less. For
|
|
105
|
+
example, a swap through the wrong config costs 17,190 against 1,628.
|
|
106
|
+
|
|
107
|
+
On size, the port's binary is 105,952 bytes and the deployed original is 793,824 bytes. The original also contains the
|
|
108
|
+
15 instructions not ported here, so the size ratio overstates the gain for the same feature set.
|
|
109
|
+
|
|
110
|
+
## Where they differ
|
|
111
|
+
|
|
112
|
+
- **Panics.** Where the original calls `unwrap()` or `assert!`, it aborts with `ProgramFailedToComplete`. The port
|
|
113
|
+
fails with a numbered error instead:
|
|
114
|
+
- an overflow or underflow, 5100: an exact-output swap for more than the vault holds;
|
|
115
|
+
- a division by zero, 5101: the price of an empty side, or an exact-output swap for exactly what the vault holds;
|
|
116
|
+
- invalid input, 6003: a fee rate out of range in the admin instructions, which only the admin can reach.
|
|
117
|
+
|
|
118
|
+
The swaps and liquidity instructions reach none of these with the amounts a pool can hold.
|
|
119
|
+
- **Check order on double faults.** Account checks run in Anchor's order, so a transaction breaking one check gets the
|
|
120
|
+
same code. The port keeps the pool's `address = …` and `token::…` constraints as `constraint(…)` calls in Anchor's
|
|
121
|
+
order. A transaction that breaks a token check and an account-type check at once can still be reported differently.
|
|
122
|
+
- **Logs.** Error messages are TypeSOL's. Codes and events are the original's.
|
package/docs/cli.md
CHANGED
|
@@ -38,10 +38,13 @@ safe and out of git: it is each program's address and its first upgrade authorit
|
|
|
38
38
|
## Editor
|
|
39
39
|
|
|
40
40
|
`typesol init` projects load `typesol/ts-plugin` from `programs/tsconfig.json`: besides TypeScript's errors, the editor
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`typesol.json
|
|
44
|
-
|
|
41
|
+
underlines what the TypeSOL compiler refuses (an unsupported construct, a constraint that cannot hold…), for the text
|
|
42
|
+
being edited (unsaved changes in every open file), once TypeScript itself has nothing to report. It checks the program
|
|
43
|
+
entries listed in `typesol.json` and shows each problem in the file it is in, the entry or any file it imports. The
|
|
44
|
+
compiler runs inside the editor's TypeScript server once it has loaded (a check takes milliseconds; the first ones run
|
|
45
|
+
`typesol check --json --files` as a child process). Editors load tsconfig plugins from the project's own TypeScript:
|
|
46
|
+
`typesol init` writes `.vscode/settings.json` so VS Code offers to switch to it ("Use Workspace Version"). To add the
|
|
47
|
+
plugin to an existing project:
|
|
45
48
|
|
|
46
49
|
```json
|
|
47
50
|
{ "compilerOptions": { "plugins": [{ "name": "typesol/ts-plugin" }] } }
|
package/docs/language.md
CHANGED
|
@@ -51,7 +51,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
51
51
|
| `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
|
|
52
52
|
| Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent) |
|
|
53
53
|
| Account size | `realloc(account, newSize, payer)` on a `Mut<Struct>` — growing charges the payer the extra rent (at most 10 KiB per instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a growable `Vec` (its push / pop / clear size the account) |
|
|
54
|
-
| Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
|
|
54
|
+
| Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferFeeInverse(mint, amountReceived)` (the fee when the recipient is to get that much: spl-token-2022's `calculate_inverse_epoch_fee`), `transferFeeBasisPoints(mint)` / `transferFeeMaximum(mint)` (this epoch's; 0 without the extension), `extensionsWithin(account, [1n, 18n, …])` (every extension is one of those types), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
|
|
55
55
|
| Events through CPI | `emitCpi<Paid>({ … }, eventAuthority, self)` with `eventAuthority: EventAuthority, self: SelfProgram` parameters — Anchor `emit_cpi!`: the event rides in a self-CPI (inner instruction), not in logs; the program accepts Anchor's event instruction (2002 / 2006 otherwise) |
|
|
56
56
|
| Heap | 32 KiB by default; `const HEAP_SIZE_KIB = 64n` (32–256) lets the program use more, when clients add ComputeBudget `requestHeapFrame` |
|
|
57
57
|
| Docs | JSDoc on instructions, `@param`, structs, fields and data enums becomes `docs` in the IDL |
|
package/lib/typesol.d.ts
CHANGED
|
@@ -490,6 +490,21 @@ export declare function realloc(account: AccountMeta, newSize: u64, payer: Mut<S
|
|
|
490
490
|
* transferFee: the fee withheld when `amount` is sent now (TransferFeeConfig for the current epoch; 0 without it).
|
|
491
491
|
*/
|
|
492
492
|
export declare function transferFee(mint: AccountMeta | RemainingAccount, amount: u64): u64;
|
|
493
|
+
/**
|
|
494
|
+
* The fee withheld when the recipient is to get `amountReceived` (spl-token-2022's `calculate_inverse_epoch_fee`):
|
|
495
|
+
* send `amountReceived + transferFeeInverse(mint, amountReceived)`. 0 without TransferFeeConfig; fails (5100) where
|
|
496
|
+
* spl-token-2022 has no answer.
|
|
497
|
+
*/
|
|
498
|
+
export declare function transferFeeInverse(mint: AccountMeta | RemainingAccount, amountReceived: u64): u64;
|
|
499
|
+
/** The TransferFeeConfig in force this epoch: its basis points (0 without the extension). */
|
|
500
|
+
export declare function transferFeeBasisPoints(mint: AccountMeta | RemainingAccount): u16;
|
|
501
|
+
/** The TransferFeeConfig in force this epoch: its maximum fee (0 without the extension). */
|
|
502
|
+
export declare function transferFeeMaximum(mint: AccountMeta | RemainingAccount): u64;
|
|
503
|
+
/**
|
|
504
|
+
* Whether every Token-2022 extension of `account` is one of `types` (a list of u16 extension types, e.g.
|
|
505
|
+
* `[1n, 18n, 19n, 10n, 25n]`): a pool that accepts only mints it knows how to handle. True for legacy SPL Token accounts.
|
|
506
|
+
*/
|
|
507
|
+
export declare function extensionsWithin(account: AccountMeta | RemainingAccount, types: u16[]): boolean;
|
|
493
508
|
/** The TransferHook extension's program, if any. */
|
|
494
509
|
export declare function transferHookProgram(mint: AccountMeta | RemainingAccount): Option<Pubkey>;
|
|
495
510
|
/** The TransferHook extension's authority (who may change the hook program), if any. */
|
package/package.json
CHANGED
package/runtime/typesol_rt.h
CHANGED
|
@@ -1058,6 +1058,62 @@ static inline uint64_t ts_t22_transfer_fee(const TsAccount *mint, uint64_t amoun
|
|
|
1058
1058
|
return SUCCESS;
|
|
1059
1059
|
}
|
|
1060
1060
|
|
|
1061
|
+
/* The TransferFee in force this epoch (TransferFeeConfig, extension 1): basis points and maximum, both 0 without one. */
|
|
1062
|
+
static inline uint64_t ts_t22_epoch_fee(const TsAccount *mint, uint64_t *bps, uint64_t *maximum) {
|
|
1063
|
+
uint64_t off, len;
|
|
1064
|
+
*bps = 0;
|
|
1065
|
+
*maximum = 0;
|
|
1066
|
+
if (!ts_t22_ext(mint, 1, &off, &len) || len < 108) return SUCCESS;
|
|
1067
|
+
uint64_t epoch;
|
|
1068
|
+
TS_TRY(ts_clock_u64(2, &epoch));
|
|
1069
|
+
const uint8_t *newer = mint->data + off + 90;
|
|
1070
|
+
const uint8_t *fee = epoch >= ts_read_le(newer, 8) ? newer : mint->data + off + 72;
|
|
1071
|
+
*maximum = ts_read_le(fee + 8, 8);
|
|
1072
|
+
*bps = ts_read_le(fee + 16, 2);
|
|
1073
|
+
return SUCCESS;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/* The fee withheld when the recipient is to get `post` (spl-token-2022's calculate_inverse_epoch_fee): the amount to
|
|
1077
|
+
send, as calculate_pre_fee_amount finds it, then the fee on it. Fails (5100) where spl-token-2022 returns None. */
|
|
1078
|
+
static inline uint64_t ts_t22_transfer_fee_inverse(const TsAccount *mint, uint64_t post, uint64_t *out) {
|
|
1079
|
+
uint64_t bps, maximum, pre;
|
|
1080
|
+
*out = 0;
|
|
1081
|
+
TS_TRY(ts_t22_epoch_fee(mint, &bps, &maximum));
|
|
1082
|
+
if (bps == 0) pre = post;
|
|
1083
|
+
else if (post == 0) pre = 0;
|
|
1084
|
+
else if (bps == 10000) {
|
|
1085
|
+
if (__builtin_add_overflow(maximum, post, &pre)) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: transfer fee overflow");
|
|
1086
|
+
} else {
|
|
1087
|
+
unsigned __int128 raw = ((unsigned __int128)post * 10000 + (10000 - bps) - 1) / (10000 - bps);
|
|
1088
|
+
if (raw - post >= maximum) {
|
|
1089
|
+
if (__builtin_add_overflow(post, maximum, &pre)) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: transfer fee overflow");
|
|
1090
|
+
} else {
|
|
1091
|
+
if (raw > UINT64_MAX) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: transfer fee overflow");
|
|
1092
|
+
pre = (uint64_t)raw;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
if (bps == 0 || pre == 0) return SUCCESS;
|
|
1096
|
+
unsigned __int128 fee = ((unsigned __int128)pre * bps + 9999) / 10000;
|
|
1097
|
+
*out = fee > maximum ? maximum : (uint64_t)fee;
|
|
1098
|
+
return SUCCESS;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/* Whether every extension of a Token-2022 mint or account is one of `allowed` (true for legacy SPL Token ones). */
|
|
1102
|
+
static inline bool ts_t22_extensions_within(const TsAccount *a, const uint16_t *allowed, uint64_t n) {
|
|
1103
|
+
if (!ts_key_eq(&a->owner, &TS_TOKEN_2022_PROGRAM_ID) || a->data_len <= TS_TOKEN_ACCOUNT_LEN + 1) return true;
|
|
1104
|
+
uint64_t at = TS_TOKEN_ACCOUNT_LEN + 1;
|
|
1105
|
+
while (at + 4 <= a->data_len) {
|
|
1106
|
+
uint16_t t = (uint16_t)ts_read_le(a->data + at, 2);
|
|
1107
|
+
uint16_t len = (uint16_t)ts_read_le(a->data + at + 2, 2);
|
|
1108
|
+
if (t == 0) return true; /* uninitialized: end of the entries */
|
|
1109
|
+
bool ok = false;
|
|
1110
|
+
for (uint64_t i = 0; i < n; i++) ok = ok || allowed[i] == t;
|
|
1111
|
+
if (!ok) return false;
|
|
1112
|
+
at += 4 + (uint64_t)len;
|
|
1113
|
+
}
|
|
1114
|
+
return true;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1061
1117
|
/* ---- Metaplex Core and Bubblegum ----------------------------------------- */
|
|
1062
1118
|
static const SolPubkey TS_MPL_CORE_ID = {{175, 84, 171, 16, 189, 151, 165, 66, 160, 158, 247, 179, 152, 137, 221, 12, 211, 148, 164, 204, 233, 223, 166, 205, 201, 126, 190, 45, 35, 91, 167, 72}};
|
|
1063
1119
|
static const SolPubkey TS_BUBBLEGUM_ID = {{152, 139, 128, 235, 121, 53, 40, 105, 178, 36, 116, 95, 89, 221, 191, 138, 38, 88, 202, 19, 220, 104, 129, 33, 38, 53, 28, 174, 7, 193, 165, 165}};
|
package/ts-plugin/index.js
CHANGED
|
@@ -2,17 +2,22 @@
|
|
|
2
2
|
//
|
|
3
3
|
// programs/tsconfig.json: { "compilerOptions": { …, "plugins": [{ "name": "typesol/ts-plugin" }] } }
|
|
4
4
|
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// (an unsupported construct, a
|
|
8
|
-
//
|
|
5
|
+
// Once TypeScript itself reports no errors in a file, the program entries of the project (typesol.json) are checked
|
|
6
|
+
// with the TypeSOL compiler on the editor's text (unsaved changes in every open file included), and what the compiler
|
|
7
|
+
// refuses (an unsupported construct, a constraint that cannot hold…) is shown where it is: in the entry or in any file
|
|
8
|
+
// it imports. The compiler runs in the editor's process once it has loaded (an ESM import, started when the plugin
|
|
9
|
+
// is created) and as `typesol check --json --files` until then. Editors load tsconfig plugins from the workspace's
|
|
10
|
+
// TypeScript (VS Code: "TypeScript: Select TypeScript Version" → "Use Workspace Version"; `typesol init` sets that up).
|
|
9
11
|
// CommonJS on purpose: tsserver loads plugins with require().
|
|
10
12
|
"use strict";
|
|
11
13
|
const { execFileSync } = require("node:child_process");
|
|
14
|
+
const { createHash } = require("node:crypto");
|
|
12
15
|
const fs = require("node:fs");
|
|
13
16
|
const path = require("node:path");
|
|
17
|
+
const { pathToFileURL } = require("node:url");
|
|
14
18
|
|
|
15
|
-
const
|
|
19
|
+
const DIST = path.join(__dirname, "..", "dist");
|
|
20
|
+
const CLI = path.join(DIST, "cli.js");
|
|
16
21
|
const CODE = 9900;
|
|
17
22
|
|
|
18
23
|
/** The program entry files of the typesol.json at or above `dir` (absolute), or an empty set. */
|
|
@@ -35,46 +40,62 @@ function init({ typescript: ts }) {
|
|
|
35
40
|
function create(info) {
|
|
36
41
|
const ls = info.languageService;
|
|
37
42
|
const log = (m) => info.project.projectService.logger.info(`[typesol] ${m}`);
|
|
38
|
-
|
|
43
|
+
/** The compiler, loaded in the background; until then each check runs as a child process. */
|
|
44
|
+
let compiler;
|
|
45
|
+
const ready = import(pathToFileURL(path.join(DIST, "compiler", "index.js")).href).then(
|
|
46
|
+
(m) => (compiler = m),
|
|
47
|
+
(e) => log(`in-process compiler unavailable (${e.message}); checking with the CLI`),
|
|
48
|
+
);
|
|
49
|
+
const cache = new Map(); // entry -> { key, found }
|
|
39
50
|
|
|
40
|
-
/** The
|
|
41
|
-
function
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
51
|
+
/** The diagnostics of one program entry for these texts: in-process when possible, else through the CLI. */
|
|
52
|
+
function check(entry, files) {
|
|
53
|
+
if (compiler) {
|
|
54
|
+
try {
|
|
55
|
+
compiler.generate(entry, { files: new Map(Object.entries(files)) });
|
|
56
|
+
return [];
|
|
57
|
+
} catch (e) {
|
|
58
|
+
if (e instanceof compiler.CompileError) return e.diagnostics;
|
|
59
|
+
log(`check failed for ${entry}: ${e.message}`);
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
49
62
|
}
|
|
50
|
-
return `${stamps}\n${sf.text}`;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function typesolDiagnostics(fileName, sf) {
|
|
54
|
-
const k = key(fileName, sf);
|
|
55
|
-
const hit = cache.get(fileName);
|
|
56
|
-
if (hit && hit.key === k) return hit.found;
|
|
57
|
-
let found = [];
|
|
58
63
|
try {
|
|
59
|
-
const out = execFileSync(process.execPath, [CLI, "check",
|
|
60
|
-
input:
|
|
64
|
+
const out = execFileSync(process.execPath, [CLI, "check", entry, "--json", "--files"], {
|
|
65
|
+
input: JSON.stringify({ files }),
|
|
61
66
|
encoding: "utf8",
|
|
62
67
|
timeout: 15000,
|
|
63
68
|
// tsserver may run inside an editor's Electron: make it behave as plain Node for the child.
|
|
64
69
|
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
|
|
65
70
|
stdio: ["pipe", "pipe", "pipe"],
|
|
66
71
|
});
|
|
67
|
-
|
|
72
|
+
return JSON.parse(out).diagnostics;
|
|
68
73
|
} catch (e) {
|
|
69
74
|
// Exit 1 with JSON on stdout means diagnostics; anything else is a crash worth logging, not showing.
|
|
70
75
|
try {
|
|
71
|
-
|
|
76
|
+
return JSON.parse(String(e.stdout)).diagnostics;
|
|
72
77
|
} catch {
|
|
73
|
-
log(`check failed for ${
|
|
74
|
-
|
|
78
|
+
log(`check failed for ${entry}: ${e.message}`);
|
|
79
|
+
return [];
|
|
75
80
|
}
|
|
76
81
|
}
|
|
77
|
-
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** `check`, cached on the texts it reads and the modification times of the .ts files beside the entry. */
|
|
85
|
+
function cachedCheck(entry, files) {
|
|
86
|
+
const hash = createHash("sha1");
|
|
87
|
+
for (const f of Object.keys(files).sort()) hash.update(`${f}\0${files[f]}\0`);
|
|
88
|
+
const dir = path.dirname(entry);
|
|
89
|
+
try {
|
|
90
|
+
for (const f of fs.readdirSync(dir).sort()) if (f.endsWith(".ts")) hash.update(`${f}:${fs.statSync(path.join(dir, f)).mtimeMs};`);
|
|
91
|
+
} catch {
|
|
92
|
+
/* the texts alone */
|
|
93
|
+
}
|
|
94
|
+
const key = hash.digest("hex");
|
|
95
|
+
const hit = cache.get(entry);
|
|
96
|
+
if (hit && hit.key === key) return hit.found;
|
|
97
|
+
const found = check(entry, files);
|
|
98
|
+
cache.set(entry, { key, found });
|
|
78
99
|
return found;
|
|
79
100
|
}
|
|
80
101
|
|
|
@@ -83,27 +104,42 @@ function init({ typescript: ts }) {
|
|
|
83
104
|
proxy.getSemanticDiagnostics = (fileName) => {
|
|
84
105
|
const prior = ls.getSemanticDiagnostics(fileName);
|
|
85
106
|
if (prior.some((d) => d.category === ts.DiagnosticCategory.Error)) return prior; // TypeScript's errors first
|
|
86
|
-
|
|
87
|
-
const
|
|
107
|
+
const target = path.resolve(fileName);
|
|
108
|
+
const entries = entriesNear(path.dirname(target));
|
|
109
|
+
if (!entries.size) return prior;
|
|
110
|
+
const program = ls.getProgram();
|
|
111
|
+
const sf = program && program.getSourceFile(fileName);
|
|
88
112
|
if (!sf) return prior;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
113
|
+
// The editor's text of the project's own files (open buffers included).
|
|
114
|
+
const files = {};
|
|
115
|
+
for (const f of program.getSourceFiles()) if (!f.isDeclarationFile && !f.fileName.includes("/node_modules/")) files[path.resolve(f.fileName)] = f.text;
|
|
116
|
+
// An entry is checked on its own; another file through every entry (whichever imports it reports it).
|
|
117
|
+
const run = entries.has(target) ? [target] : [...entries].filter((e) => fs.existsSync(e) || files[e] !== undefined);
|
|
118
|
+
const seen = new Set();
|
|
119
|
+
const own = [];
|
|
120
|
+
for (const entry of run)
|
|
121
|
+
for (const d of cachedCheck(entry, files)) {
|
|
122
|
+
if (path.resolve(d.file) !== target) continue;
|
|
123
|
+
const id = `${d.line}:${d.column}:${d.message}`;
|
|
124
|
+
if (seen.has(id)) continue;
|
|
125
|
+
seen.add(id);
|
|
92
126
|
const line = Math.max(0, Math.min(d.line - 1, sf.getLineStarts().length - 1));
|
|
93
127
|
const start = Math.min(sf.getPositionOfLineAndCharacter(line, 0) + Math.max(0, d.column - 1), sf.end);
|
|
94
128
|
const word = /^[\w$]+/.exec(sf.text.slice(start));
|
|
95
|
-
|
|
129
|
+
own.push({
|
|
96
130
|
file: sf,
|
|
97
131
|
start,
|
|
98
|
-
length: word ? word[0].length : 1,
|
|
132
|
+
length: Math.max(1, Math.min(d.length || (word ? word[0].length : 1), sf.end - start)),
|
|
99
133
|
messageText: d.message,
|
|
100
134
|
category: ts.DiagnosticCategory.Error,
|
|
101
135
|
code: CODE,
|
|
102
136
|
source: "typesol",
|
|
103
|
-
};
|
|
104
|
-
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
105
139
|
return [...prior, ...own];
|
|
106
140
|
};
|
|
141
|
+
// Tests (and curious hosts) can wait for the in-process compiler.
|
|
142
|
+
proxy.typesolReady = () => ready;
|
|
107
143
|
return proxy;
|
|
108
144
|
}
|
|
109
145
|
return { create };
|