@typesol/cli 0.39.0 → 0.41.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 +74 -0
- package/README.md +29 -23
- package/dist/ai.d.ts +10 -0
- package/dist/ai.js +43 -0
- package/dist/cli.js +52 -4
- package/dist/compiler/analyze.js +13 -7
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/emit/base.d.ts +2 -1
- package/dist/compiler/emit/calls.d.ts +5 -0
- package/dist/compiler/emit/calls.js +173 -5
- package/dist/compiler/emit/expressions.d.ts +6 -0
- package/dist/compiler/emit/expressions.js +95 -2
- package/dist/compiler/emit/program.js +12 -0
- package/dist/compiler/emit/shared.d.ts +10 -0
- package/dist/compiler/emit/statements.d.ts +20 -1
- package/dist/compiler/emit/statements.js +177 -7
- package/dist/compiler/hints.d.ts +5 -0
- package/dist/compiler/hints.js +88 -0
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +6 -1
- package/dist/tools/mcp.d.ts +11 -0
- package/dist/tools/mcp.js +208 -0
- package/dist/workspace.js +8 -0
- package/docs/ai.md +52 -0
- package/docs/audit.md +16 -14
- package/docs/case-study-marginfi.md +2 -2
- package/docs/case-study-raydium-amm.md +80 -0
- package/docs/case-study-raydium-cp-swap.md +77 -41
- package/docs/language.md +27 -7
- package/docs/stability.md +56 -0
- package/docs/testing.md +6 -5
- package/docs/troubleshooting.md +6 -0
- package/lib/typesol.d.ts +73 -2
- package/llms-full.txt +1195 -0
- package/llms.txt +30 -0
- package/package.json +4 -2
- package/runtime/typesol_rt.h +47 -0
- package/ts-plugin/index.js +24 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,80 @@ codes, and says so here.
|
|
|
6
6
|
|
|
7
7
|
## Unreleased
|
|
8
8
|
|
|
9
|
+
## 0.41.0 — 2026-11-07
|
|
10
|
+
|
|
11
|
+
TypeSOL for AI coding agents, and Raydium CP-Swap ported in full. `typesol init` writes the rules an agent needs
|
|
12
|
+
(AGENTS.md, CLAUDE.md, Cursor's rules) and an MCP server configuration; `typesol mcp` gives agents check, IDL and docs
|
|
13
|
+
search as tools; `llms.txt` / `llms-full.txt` put the docs in one file for models. Raydium CP-Swap now has all 21 of its
|
|
14
|
+
instructions, checked against today's mainnet binary with a fuzz test. Programs that do not log a narrowed Option
|
|
15
|
+
compile to the same C as in 0.40.0.
|
|
16
|
+
|
|
17
|
+
- AI agents (docs/ai.md): `typesol init` writes AGENTS.md, CLAUDE.md and Cursor's rules (what TypeSOL refuses that
|
|
18
|
+
TypeScript habits produce, how to check and test) and the MCP server's configuration (.mcp.json, .cursor/mcp.json).
|
|
19
|
+
- New: `typesol mcp`, a Model Context Protocol server on stdio with the tools `check` (diagnostics with hints, from a
|
|
20
|
+
file or source text), `idl`, `docs` (search) and `rules`. No new dependencies.
|
|
21
|
+
- New: `llms.txt` and `llms-full.txt` (the rules, the quick start and the reference in one file), built from the docs by
|
|
22
|
+
`scripts/llms.ts`, shipped in the npm package; the tests fail when they are out of date.
|
|
23
|
+
- CLI: `typesol check --json` gives each error's hint as a `hint` field (it stays the message's last line too).
|
|
24
|
+
- Fixed: `log(x)` of an Option that TypeScript narrowed to its value (after `x === null` was ruled out) generated C that
|
|
25
|
+
did not compile; it logs the value now, and a possibly-null Option is refused with what to do instead.
|
|
26
|
+
- Examples: showcase/mainnet/raydium-cp-swap ports all 21 of Raydium CP-Swap's instructions (was 10): `initialize_v2`,
|
|
27
|
+
`initialize_with_permission`, `collect_creator_fee`, `collect_creator_fee_permissionless`, the permission, creator
|
|
28
|
+
fee share and supported-mint accounts (create and close), and `collect_excess_lamports`. Checked against the binary
|
|
29
|
+
on mainnet today (deployed 2026-10-31; test/programs/raydium_cp_swap.so updated): 136 transactions (was 70) with
|
|
30
|
+
the same outcomes, account bytes and events, Raydium's five signing keys replaced by test keys in both so the admin
|
|
31
|
+
instructions run too, and a fuzz test (random swaps, deposits, withdrawals and fee collections in an SPL Token
|
|
32
|
+
and a Token-2022 pool); an exact-output swap for the whole vault now panics as the original does instead of failing
|
|
33
|
+
with 5100. 42–85% fewer compute units; 214,944 bytes against 749,848. docs/case-study-raydium-cp-swap.md.
|
|
34
|
+
- Docs: docs/stability.md, what 1.0 will promise, what is stable already and what is still experimental, and what to
|
|
35
|
+
settle first; the audit package's line counts and its list of unreviewed changes brought up to 0.40.0.
|
|
36
|
+
|
|
37
|
+
## 0.40.0 — 2026-11-06
|
|
38
|
+
|
|
39
|
+
Raydium AMM v4 ported in full, a native (non-Anchor) program, and checked against its mainnet binary down to its log
|
|
40
|
+
lines and panics. The compiler gained what a native program needs: accounts without a discriminator, the instruction
|
|
41
|
+
data read by offset, errors from code 0, built-in program errors, panics with a location, and the entrypoint's log
|
|
42
|
+
lines. Also: functions chosen at run time, `find(…)!.field` / `?.field` on struct lists, struct maps inside chains, and
|
|
43
|
+
hints under the errors newcomers meet first, in the CLI and the editor. Programs that use none of the new features
|
|
44
|
+
compile to the same C as in 0.39.0.
|
|
45
|
+
|
|
46
|
+
- Examples: showcase/mainnet/raydium-amm, a port of Raydium AMM v4 (the native program at 675kPX9M…, all of its
|
|
47
|
+
instructions: Initialize2, deposits, withdrawals, the v1 and v2 swaps base in and base out, P&L, parameters, the
|
|
48
|
+
config, excess lamports), checked against the mainnet binary (test/programs/raydium_amm_v4.so) on 484 transactions,
|
|
49
|
+
fuzzed: the same outcomes, account bytes and log lines, ray_log records and the original's panics included; swaps
|
|
50
|
+
take 41–44% of the original's compute units, deposits and withdrawals 35–37%. See docs/case-study-raydium-amm.md.
|
|
51
|
+
- New (native programs; docs/language.md "Porting a native program"): `loadRaw<T>` / `loadRawMut<T>` for accounts
|
|
52
|
+
without a discriminator; `readU8/U16/U32/U64/U128/readPubkey(offset)` on `instructionData()`; error enums from code 0
|
|
53
|
+
(returned as CUSTOM_ZERO); `require(c, ProgramError.X)` for Solana's built-in errors; `panic(message, location?)`;
|
|
54
|
+
`PANIC_ON_OVERFLOW`, `ERROR_LOG_PREFIX` and `PROGRAM_ERROR_LOG_PREFIX` program constants; `createProgramAddress`;
|
|
55
|
+
`logBase64(prefix, struct)`.
|
|
56
|
+
- Fixed: `isqrt` of a u256 (it generated C that did not compile).
|
|
57
|
+
- New: a function chosen at run time, `const g = k === 1n ? dbl : inc; g(x)` (the condition read once; only the chosen
|
|
58
|
+
function runs), and a list of functions run in turn, `for (const f of [dbl, inc]) …` (unrolled; `continue` and `break`
|
|
59
|
+
work).
|
|
60
|
+
- New: `xs.find(f)!.field` and `xs.find(f)?.field` on lists of structs (located with findIndex, read in place; `!` aborts
|
|
61
|
+
with 5108 when nothing matched, `?.` gives an Option).
|
|
62
|
+
- New: `map` to structs inside a chain when the callback names the struct, `xs.map((o): Scored => ({ … })).filter(…)
|
|
63
|
+
.reduce(…)`: one struct per element, nothing stored.
|
|
64
|
+
- Hints: comparing an integer with a number (`k === 1`) points at `1n`. `.length` on something that is not a list says
|
|
65
|
+
what it is instead of asking for byteLength; the FixedVec argument/account refusal says why (two byte layouts, one IDL
|
|
66
|
+
type).
|
|
67
|
+
- Docs: the README's quick start ends with a first change to make and a short "where next" list (it was one long
|
|
68
|
+
paragraph); the showcase lists Marginfi v2 as complete and links every case study.
|
|
69
|
+
- Editor: the plugin (`typesol/ts-plugin`) adds the same hints under TypeScript's errors in a program's files, once the
|
|
70
|
+
in-process compiler has loaded, so VS Code shows what to write instead too.
|
|
71
|
+
- CLI: `typesol init` names the other starters (`--template vault`, `--template escrow`) after the next steps.
|
|
72
|
+
- CLI: build errors show the path relative to the working directory and the source line with the problem marked.
|
|
73
|
+
`--json` and the compiler API keep their fields (a hint is a line of the message).
|
|
74
|
+
- New: hints for the errors newcomers meet first, under TypeScript's message: a number where a u64 is (`1n`), `Math.max`
|
|
75
|
+
(`min` / `max`), `console.log` (`log`), a missing `typesol` import, `async`, writing an account that is not `Mut<T>`,
|
|
76
|
+
`xs[i]` (`.get` / `.set`). Refused syntax is named in TypeScript's words ("classes are not supported: …") instead of
|
|
77
|
+
the compiler's internal node names, and `require` with a template string says what its error can be.
|
|
78
|
+
- Docs: Marginfi's case study lists part 5 as done (all 124 instructions); troubleshooting points to the hints.
|
|
79
|
+
- Releases: `scripts/release-manifest.ts` builds the program-examples ports of sources up to 0.38.0 (`test/ports/`; a
|
|
80
|
+
0.38.0 tree listed only 18 programs). docs/testing.md and CONTRIBUTING describe the manifest and binary diff as attached
|
|
81
|
+
by hand.
|
|
82
|
+
|
|
9
83
|
## 0.39.0 — 2026-11-06
|
|
10
84
|
|
|
11
85
|
Marginfi v2 ported in full: all 124 instructions, checked against the mainnet binary on 2,081 transactions with the
|
package/README.md
CHANGED
|
@@ -173,22 +173,22 @@ existing project: `npm install -D typesol@npm:@typesol/cli`.
|
|
|
173
173
|
Deploying again upgrades the program in place. Keep `target/deploy/<name>-keypair.json`: that keypair is your
|
|
174
174
|
program's address.
|
|
175
175
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
[docs/
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
176
|
+
**Your first change.** Open `programs/counter.ts`, add an instruction (say `decrement`, with
|
|
177
|
+
`require(counter.count >= 1n, …)` before `counter.count -= 1n`), call it from `tests/counter.test.ts` and run `npm test`.
|
|
178
|
+
If the build refuses something, the error points at the line and, for the usual first mistakes (`1` instead of `1n`,
|
|
179
|
+
`console.log`, a missing import, `async`), adds a `hint:` with what to write instead; your editor shows the same.
|
|
180
|
+
|
|
181
|
+
**Where next**
|
|
182
|
+
- The language, every type and built-in: [docs/language.md](docs/language.md).
|
|
183
|
+
- Tests with `typesol/testing` (accounts by name, plain values): [docs/test-your-program.md](docs/test-your-program.md).
|
|
184
|
+
- Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, and
|
|
185
|
+
`typesol port` starts from your program's IDL; [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one
|
|
186
|
+
program through the port.
|
|
187
|
+
- Real programs checked against their mainnet binaries: [Showcase](#showcase-ports-checked-against-mainnet), with a
|
|
188
|
+
case study each (Marginfi v2 in full: all 124 instructions, the same on 2,081 transactions; Raydium AMM v4, a native
|
|
189
|
+
program, down to its log lines).
|
|
190
|
+
- To mainnet (wallet, cost, deploy, IDL, verification): [docs/mainnet.md](docs/mainnet.md).
|
|
191
|
+
- With an AI coding agent: [docs/ai.md](docs/ai.md) (agent rules, [llms.txt](https://typesol.com/llms.txt), the MCP server).
|
|
192
192
|
|
|
193
193
|
## How it works
|
|
194
194
|
|
|
@@ -200,7 +200,7 @@ counter.ts ─▶ tsc typecheck ─▶ subset check ─▶ C + typesol_rt.h ─
|
|
|
200
200
|
1. **Typecheck.** The TypeScript compiler checks your code against [`lib/typesol.d.ts`](lib/typesol.d.ts), which
|
|
201
201
|
declares every TypeSOL type and built-in.
|
|
202
202
|
2. **Subset check.** TypeSOL rejects anything outside the language (floats, classes, `any`, foreign imports)
|
|
203
|
-
with a `file:line:col` diagnostic. Nothing is half-supported.
|
|
203
|
+
with a `file:line:col` diagnostic, and a hint for the usual first mistakes. Nothing is half-supported.
|
|
204
204
|
3. **Lower.** Instruction bodies become C. Account validation, checked arithmetic, Borsh encoding and CPI plumbing
|
|
205
205
|
come from [`runtime/typesol_rt.h`](runtime/typesol_rt.h).
|
|
206
206
|
4. **Build.** The Agave platform-tools `clang` and `ld.lld` produce the `.so` (SBPF v0 by default; v1 and v2 with
|
|
@@ -216,7 +216,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
|
|
|
216
216
|
| **Accounts** | `Signer`, `Account<T>`, `Mut<T>`, `Init<T>`, `InitIfNeeded<T>` (PDAs or keypair accounts, with Anchor's `space`; mints, token accounts and associated token accounts), `Zeroed<T>` (up to 10 MiB), optional accounts (`A \| null`), token accounts and mints, `SystemAccount`, programs, sysvars, and account groups (Anchor's composite accounts) |
|
|
217
217
|
| **Constraints** | `HasOne`, `Seeds` (also from account fields and under another program; `pdaBump` like `ctx.bumps`), `CloseTo`, `Ata`, `Address`, `Owner`, `Executable`. They are checked before the body runs and recorded in the IDL, and take your own error as Anchor's `@ ErrorCode.X` does |
|
|
218
218
|
| **Data** | `u8`…`u128`, `i8`…`i128`, `u256` (for computation), `f64` (as its bits, in events and accounts), `boolean`, `Pubkey`, `Hash`, nested structs, `FixedArray`, `FixedString`, `Option`, unit enums, data enums (discriminated unions), `Vec` that resizes its account, `FixedVec` lists anywhere, and Anchor's own byte layout (`@layout borsh`) to take over existing Anchor accounts and to pass, return and emit structs with String / Vec / Option fields as Anchor does |
|
|
219
|
-
| **Control flow** | `if`, `for`, `for … of`, `while`, `switch` (with narrowing on data enums), ternaries, `??`, destructuring, helper functions (returning structs too, arrow functions, closures, function arguments, generics), list callbacks (`some`, `find`, `reduce`,
|
|
219
|
+
| **Control flow** | `if`, `for`, `for … of`, `while`, `switch` (with narrowing on data enums), ternaries, `??`, destructuring, helper functions (returning structs too, arrow functions, closures, function arguments, generics, functions chosen at run time), list callbacks (`some`, `find`, `reduce`, …, with `map` / `filter` chains that store nothing) across multiple files |
|
|
220
220
|
| **CPIs** | System, SPL Token, Token-2022 (including extension reads, metadata and token groups), ATA, Memo, Stake, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing (one or several PDAs per call), return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
|
|
221
221
|
| **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
|
|
222
222
|
| **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard feeds and verifiable randomness |
|
|
@@ -228,11 +228,12 @@ The full reference, with every type, check and built-in, is in [docs/language.md
|
|
|
228
228
|
|
|
229
229
|
| Command | What it does |
|
|
230
230
|
| --- | --- |
|
|
231
|
-
| `typesol init` | scaffold a project with a program, a LiteSVM test
|
|
231
|
+
| `typesol init` | scaffold a project with a program, a LiteSVM test, TypeScript configs and the files AI coding agents read (AGENTS.md, CLAUDE.md, Cursor rules, MCP config) |
|
|
232
232
|
| `typesol new <program>` | add another program and its test to a project |
|
|
233
233
|
| `typesol clone <address…>` | copy mainnet accounts and programs for the tests, loaded by `testProgram` |
|
|
234
234
|
| `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
|
|
235
|
-
| `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file) |
|
|
235
|
+
| `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file); `--json` gives each error's hint as a field |
|
|
236
|
+
| `typesol mcp` | an MCP server for AI coding agents: check, IDL, docs search and the rules as tools ([docs/ai.md](docs/ai.md)) |
|
|
236
237
|
| `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
|
|
237
238
|
| `typesol idl publish` | upload the IDL to the Program Metadata program (canonical when the upgrade authority signs) |
|
|
238
239
|
| `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
|
|
@@ -343,13 +344,17 @@ Details are in [docs/testing.md](docs/testing.md).
|
|
|
343
344
|
[`showcase/`](showcase) holds programs ported from Anchor and checked against the binaries deployed on mainnet (same
|
|
344
345
|
outcomes, account bytes and events; [`showcase/test`](showcase/test)), and the ports of all 46
|
|
345
346
|
[solana-developers/program-examples](showcase/program-examples/README.md).
|
|
347
|
+
Case studies: [Marginfi v2](docs/case-study-marginfi.md), [Raydium AMM v4](docs/case-study-raydium-amm.md), [Raydium CLMM](docs/case-study-raydium-clmm.md),
|
|
348
|
+
[Raydium CP-Swap](docs/case-study-raydium-cp-swap.md), [Jito MEV](docs/case-study-jito-mev.md),
|
|
349
|
+
[coral-xyz/multisig](docs/case-study-multisig.md), [an Anchor escrow](docs/case-study-escrow.md).
|
|
346
350
|
|
|
347
351
|
| | |
|
|
348
352
|
| --- | --- |
|
|
349
|
-
| [`raydium-cp-swap/`](showcase/mainnet/raydium-cp-swap) | Raydium CP-Swap
|
|
353
|
+
| [`raydium-cp-swap/`](showcase/mainnet/raydium-cp-swap) | Raydium CP-Swap in full, all 21 instructions: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle, creator fees and their shares, permissioned pools, supported mints |
|
|
350
354
|
| [`raydium-clmm/`](showcase/mainnet/raydium-clmm) | Raydium CLMM in full: concentrated-liquidity positions as NFTs, swaps and multi-hop routes across tick arrays, limit orders, rewards, dynamic fees, u256 math |
|
|
351
355
|
| [`jito-mev/`](showcase/mainnet/jito-mev) | Jito's tip payment, tip distribution and priority fee distribution: tips paid out per leader, Merkle-proof claims, epochs and expiry |
|
|
352
|
-
| [`marginfi/`](showcase/mainnet/marginfi) | Marginfi v2
|
|
356
|
+
| [`marginfi/`](showcase/mainnet/marginfi) | Marginfi v2 in full, all 124 instructions: I80F48 fixed-point arithmetic, zero-copy accounts, oracles (Pyth, Switchboard, staked SOL, Scope, venue exchange rates), the risk engine, liquidation and bankruptcy, flash loans, orders, rebalances, and the Solend, Kamino, Drift and JupLend banks |
|
|
357
|
+
| [`raydium-amm/`](showcase/mainnet/raydium-amm) | Raydium AMM v4, the original constant-product AMM and a native (non-Anchor) program, in full: pool creation, deposits and withdrawals, the v1 and v2 swaps, P&L and administration, down to its log records and panics |
|
|
353
358
|
| [`multisig.ts`](showcase/mainnet/multisig/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
|
|
354
359
|
|
|
355
360
|
## Status
|
|
@@ -365,7 +370,8 @@ change.
|
|
|
365
370
|
external audit.
|
|
366
371
|
- Report vulnerabilities as described in [SECURITY.md](SECURITY.md).
|
|
367
372
|
|
|
368
|
-
Not supported yet: see the end of [docs/language.md](docs/language.md#not-supported-yet).
|
|
373
|
+
Not supported yet: see the end of [docs/language.md](docs/language.md#not-supported-yet). What 1.0 will promise, what is
|
|
374
|
+
stable already and what is still experimental: [docs/stability.md](docs/stability.md).
|
|
369
375
|
|
|
370
376
|
## Requirements
|
|
371
377
|
|
package/dist/ai.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The rules every TypeSOL program follows that a model trained on ordinary TypeScript gets wrong first. */
|
|
2
|
+
export declare const AGENT_RULES = "## Writing TypeSOL\n\nTypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live\nin `programs/`, tests in `tests/`; `typesol.json` lists the programs.\n\n- Exported functions are instructions; their parameters are the accounts (`Signer`, `Account<T>`, `Mut<T>`,\n `Init<T>`, token accounts, programs) and then the arguments. Account data types are exported interfaces.\n- Integers are bigint: `u8` \u2026 `u128`, `i8` \u2026 `i128` (write `1n`, never `1`; take `u64`, never `number`).\n Arithmetic is checked: an overflow fails the instruction. There is no floating point.\n- Import everything from `\"typesol\"`: types, and functions such as `require`, `log`, `min`, `max`,\n `fixedArray`, `emit`, `invoke`.\n- Fail with `require(condition, MyError.Name)` (an exported string enum of messages) or `require(condition, \"message\")`.\n There is no `throw`, `try`, `async`, `class`, `console` or `Math`.\n- An account the instruction changes is `Mut<T>`; one it creates is `Init<T>` (`acct.create(payer, seeds)`).\n- Lists: `FixedArray<T, N>`, `FixedVec<T, N>`, `Vec<T>`; read with `.get(i)` and write with `.set(i, v)`\n (`i` a bigint), not `xs[i]`. `map`, `filter`, `find`, `some`, `reduce` work on them.\n- Strings are `FixedString<N>` in account data; `Option<T>` (`T | null`) for optional values.\n\n## Checking your work\n\n- `npx typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a\n `hint` that says what to write instead. Fix those first; they are faster than a build.\n- `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx typesol build`\n writes `target/<name>/`: the `.so`, the IDL and a typed client.\n- The MCP server (`npx typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,\n the IDL and the docs as tools.\n- The language reference: `node_modules/typesol/docs/language.md`, or https://typesol.com/llms-full.txt.\n";
|
|
3
|
+
/** AGENTS.md for a new project (Codex, Cursor, Zed, and other agents that read it). */
|
|
4
|
+
export declare function agentsMd(name: string): string;
|
|
5
|
+
/** Claude Code reads CLAUDE.md, which imports AGENTS.md so the rules are kept in one place. */
|
|
6
|
+
export declare const CLAUDE_MD = "@AGENTS.md\n";
|
|
7
|
+
/** Cursor's project rules, always applied to the program and test files. */
|
|
8
|
+
export declare function cursorRule(): string;
|
|
9
|
+
/** The MCP server configuration Claude Code (.mcp.json) and Cursor (.cursor/mcp.json) read. */
|
|
10
|
+
export declare const MCP_JSON: string;
|
package/dist/ai.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// What an AI coding agent needs to write TypeSOL: the rules `typesol init` puts in AGENTS.md (and CLAUDE.md, Cursor's
|
|
2
|
+
// rules), the MCP server configurations it writes, and the llms.txt files built from the docs (scripts/llms.ts).
|
|
3
|
+
/** The rules every TypeSOL program follows that a model trained on ordinary TypeScript gets wrong first. */
|
|
4
|
+
export const AGENT_RULES = `## Writing TypeSOL
|
|
5
|
+
|
|
6
|
+
TypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live
|
|
7
|
+
in \`programs/\`, tests in \`tests/\`; \`typesol.json\` lists the programs.
|
|
8
|
+
|
|
9
|
+
- Exported functions are instructions; their parameters are the accounts (\`Signer\`, \`Account<T>\`, \`Mut<T>\`,
|
|
10
|
+
\`Init<T>\`, token accounts, programs) and then the arguments. Account data types are exported interfaces.
|
|
11
|
+
- Integers are bigint: \`u8\` … \`u128\`, \`i8\` … \`i128\` (write \`1n\`, never \`1\`; take \`u64\`, never \`number\`).
|
|
12
|
+
Arithmetic is checked: an overflow fails the instruction. There is no floating point.
|
|
13
|
+
- Import everything from \`"typesol"\`: types, and functions such as \`require\`, \`log\`, \`min\`, \`max\`,
|
|
14
|
+
\`fixedArray\`, \`emit\`, \`invoke\`.
|
|
15
|
+
- Fail with \`require(condition, MyError.Name)\` (an exported string enum of messages) or \`require(condition, "message")\`.
|
|
16
|
+
There is no \`throw\`, \`try\`, \`async\`, \`class\`, \`console\` or \`Math\`.
|
|
17
|
+
- An account the instruction changes is \`Mut<T>\`; one it creates is \`Init<T>\` (\`acct.create(payer, seeds)\`).
|
|
18
|
+
- Lists: \`FixedArray<T, N>\`, \`FixedVec<T, N>\`, \`Vec<T>\`; read with \`.get(i)\` and write with \`.set(i, v)\`
|
|
19
|
+
(\`i\` a bigint), not \`xs[i]\`. \`map\`, \`filter\`, \`find\`, \`some\`, \`reduce\` work on them.
|
|
20
|
+
- Strings are \`FixedString<N>\` in account data; \`Option<T>\` (\`T | null\`) for optional values.
|
|
21
|
+
|
|
22
|
+
## Checking your work
|
|
23
|
+
|
|
24
|
+
- \`npx typesol check\` (or \`--json\`) type-checks every program and lists what TypeSOL refuses, each error with a
|
|
25
|
+
\`hint\` that says what to write instead. Fix those first; they are faster than a build.
|
|
26
|
+
- \`npm test\` builds the programs and runs \`tests/\` in LiteSVM (an in-process Solana runtime). \`npx typesol build\`
|
|
27
|
+
writes \`target/<name>/\`: the \`.so\`, the IDL and a typed client.
|
|
28
|
+
- The MCP server (\`npx typesol mcp\`, configured in \`.mcp.json\` and \`.cursor/mcp.json\`) gives the same check,
|
|
29
|
+
the IDL and the docs as tools.
|
|
30
|
+
- The language reference: \`node_modules/typesol/docs/language.md\`, or https://typesol.com/llms-full.txt.
|
|
31
|
+
`;
|
|
32
|
+
/** AGENTS.md for a new project (Codex, Cursor, Zed, and other agents that read it). */
|
|
33
|
+
export function agentsMd(name) {
|
|
34
|
+
return `# ${name}\n\nA Solana program written in TypeSOL (https://typesol.com).\n\n${AGENT_RULES}`;
|
|
35
|
+
}
|
|
36
|
+
/** Claude Code reads CLAUDE.md, which imports AGENTS.md so the rules are kept in one place. */
|
|
37
|
+
export const CLAUDE_MD = "@AGENTS.md\n";
|
|
38
|
+
/** Cursor's project rules, always applied to the program and test files. */
|
|
39
|
+
export function cursorRule() {
|
|
40
|
+
return `---\ndescription: TypeSOL, a TypeScript subset compiled to Solana programs\nglobs: programs/**/*.ts, tests/**/*.ts\nalwaysApply: true\n---\n\n${AGENT_RULES}`;
|
|
41
|
+
}
|
|
42
|
+
/** The MCP server configuration Claude Code (.mcp.json) and Cursor (.cursor/mcp.json) read. */
|
|
43
|
+
export const MCP_JSON = JSON.stringify({ mcpServers: { typesol: { command: "npx", args: ["typesol", "mcp"] } } }, null, 2) + "\n";
|
package/dist/cli.js
CHANGED
|
@@ -66,7 +66,7 @@ const COMMANDS = {
|
|
|
66
66
|
init: {
|
|
67
67
|
usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
|
|
68
68
|
help: [
|
|
69
|
-
"Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors).",
|
|
69
|
+
"Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors), AGENTS.md / CLAUDE.md / .cursor/rules (the rules for AI coding agents) and .mcp.json / .cursor/mcp.json (the TypeSOL MCP server).",
|
|
70
70
|
"Refuses to overwrite files. <name> must be snake_case (default: derived from <dir>).",
|
|
71
71
|
"--template counter a PDA counter per user (default)",
|
|
72
72
|
"--template vault a SOL vault at a PDA: deposit, withdraw above rent, close",
|
|
@@ -99,7 +99,8 @@ const COMMANDS = {
|
|
|
99
99
|
(rel === "." ? "" : ` cd ${rel}\n`) +
|
|
100
100
|
` npm install\n` +
|
|
101
101
|
` 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`
|
|
102
|
+
` npx typesol doctor # checks the toolchain, keypair and RPC before a deploy` +
|
|
103
|
+
(template === "counter" ? `\n\n other starters: typesol init <dir> --template vault (SOL at a PDA) or --template escrow (SPL token escrow)` : ""));
|
|
103
104
|
return 0;
|
|
104
105
|
},
|
|
105
106
|
},
|
|
@@ -178,7 +179,7 @@ const COMMANDS = {
|
|
|
178
179
|
throw e;
|
|
179
180
|
diagnostics.push(...e.diagnostics);
|
|
180
181
|
if (!v.json)
|
|
181
|
-
console.error(`${name}:\n${e.
|
|
182
|
+
console.error(`${name}:\n${showDiagnostics(e.diagnostics)}`);
|
|
182
183
|
}
|
|
183
184
|
}
|
|
184
185
|
if (v.json)
|
|
@@ -224,6 +225,20 @@ const COMMANDS = {
|
|
|
224
225
|
return 0;
|
|
225
226
|
},
|
|
226
227
|
},
|
|
228
|
+
mcp: {
|
|
229
|
+
usage: "typesol mcp",
|
|
230
|
+
help: [
|
|
231
|
+
"Serve the Model Context Protocol on stdio for AI coding agents: tools to check a program (errors with hints), read",
|
|
232
|
+
"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`.",
|
|
234
|
+
].join("\n "),
|
|
235
|
+
options: {},
|
|
236
|
+
async run() {
|
|
237
|
+
const { serve } = await import("./tools/mcp.js");
|
|
238
|
+
await serve();
|
|
239
|
+
return 0;
|
|
240
|
+
},
|
|
241
|
+
},
|
|
227
242
|
doctor: {
|
|
228
243
|
usage: "typesol doctor [--url <rpc>] [--config <solana cli config>]",
|
|
229
244
|
help: [
|
|
@@ -552,6 +567,39 @@ const USAGE = `Usage:\n${Object.values(COMMANDS)
|
|
|
552
567
|
function log(s) {
|
|
553
568
|
console.log(s);
|
|
554
569
|
}
|
|
570
|
+
/**
|
|
571
|
+
* Diagnostics for a terminal: the path relative to the working directory, the source line with the problem marked, and
|
|
572
|
+
* the rest of the message (a hint, TypeScript's details) under it. `--json` and CompileError.message keep the plain form.
|
|
573
|
+
*/
|
|
574
|
+
function showDiagnostics(diagnostics, sources) {
|
|
575
|
+
const cache = new Map();
|
|
576
|
+
const linesOf = (file) => {
|
|
577
|
+
if (!cache.has(file)) {
|
|
578
|
+
let text = sources?.get(file);
|
|
579
|
+
if (text === undefined && existsSync(file))
|
|
580
|
+
text = readFileSync(file, "utf8");
|
|
581
|
+
cache.set(file, text?.split(/\r?\n/));
|
|
582
|
+
}
|
|
583
|
+
return cache.get(file);
|
|
584
|
+
};
|
|
585
|
+
return diagnostics
|
|
586
|
+
.map((d) => {
|
|
587
|
+
const rel = path.relative(process.cwd(), d.file);
|
|
588
|
+
const shown = rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel : d.file;
|
|
589
|
+
const [first, ...rest] = d.message.split("\n");
|
|
590
|
+
const out = [`${shown}:${d.line}:${d.column} - error: ${first}`];
|
|
591
|
+
const src = linesOf(d.file)?.[d.line - 1];
|
|
592
|
+
if (src !== undefined) {
|
|
593
|
+
const gutter = String(d.line);
|
|
594
|
+
const width = Math.max(1, Math.min(d.length ?? 1, src.length - (d.column - 1)));
|
|
595
|
+
out.push(` ${gutter} | ${src}`, ` ${" ".repeat(gutter.length)} | ${" ".repeat(Math.max(0, d.column - 1))}${"^".repeat(width)}`);
|
|
596
|
+
}
|
|
597
|
+
for (const r of rest)
|
|
598
|
+
out.push(` ${r}`);
|
|
599
|
+
return out.join("\n");
|
|
600
|
+
})
|
|
601
|
+
.join("\n\n");
|
|
602
|
+
}
|
|
555
603
|
function mustExist(file) {
|
|
556
604
|
if (!existsSync(file))
|
|
557
605
|
throw new UsageError(`${file} does not exist`);
|
|
@@ -645,7 +693,7 @@ try {
|
|
|
645
693
|
}
|
|
646
694
|
catch (e) {
|
|
647
695
|
if (e instanceof CompileError) {
|
|
648
|
-
console.error(e.
|
|
696
|
+
console.error(showDiagnostics(e.diagnostics));
|
|
649
697
|
console.error(`\n${e.diagnostics.length} error(s)`);
|
|
650
698
|
}
|
|
651
699
|
else
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { CompileError, Reporter } from "./diagnostics.js";
|
|
6
6
|
import { decodeAddress } from "../keys.js";
|
|
7
7
|
import { borshIdentical } from "./emit/borsh.js";
|
|
8
|
+
import { hintForTypeScript, unsupportedSyntax } from "./hints.js";
|
|
8
9
|
import { optionKey, INT_INFO, INT_NAMES, scalarKey, fixedVecName, isScalar, scalarSize, typeName, } from "./model.js";
|
|
9
10
|
export const LIB_PATH = fileURLToPath(new URL("../../lib/typesol.d.ts", import.meta.url));
|
|
10
11
|
/** Names a struct field may not use because account parameters already expose them. */
|
|
@@ -259,11 +260,14 @@ function typecheck(entry, files) {
|
|
|
259
260
|
const tsDiagnostics = userFiles.flatMap((f) => ts.getPreEmitDiagnostics(program, f));
|
|
260
261
|
if (tsDiagnostics.length > 0) {
|
|
261
262
|
const diagnostics = tsDiagnostics.map((d) => {
|
|
262
|
-
const
|
|
263
|
+
const flat = ts.flattenDiagnosticMessageText(d.messageText, "\n");
|
|
264
|
+
const hint = hintForTypeScript(d, flat, LIB_PATH);
|
|
265
|
+
const message = hint ? `${flat}\nhint: ${hint}` : flat;
|
|
266
|
+
const extra = hint ? { hint } : {};
|
|
263
267
|
if (!d.file || d.start === undefined)
|
|
264
|
-
return { file: entry, line: 1, column: 1, message };
|
|
268
|
+
return { file: entry, line: 1, column: 1, message, ...extra };
|
|
265
269
|
const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
|
|
266
|
-
return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length };
|
|
270
|
+
return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length, ...extra };
|
|
267
271
|
});
|
|
268
272
|
throw new CompileError(diagnostics);
|
|
269
273
|
}
|
|
@@ -420,8 +424,10 @@ export function analyze(entry, files) {
|
|
|
420
424
|
const tag = ts.getJSDocTags(m).find((t) => t.tagName.text === "code");
|
|
421
425
|
if (tag) {
|
|
422
426
|
const text = typeof tag.comment === "string" ? tag.comment.trim() : "";
|
|
423
|
-
|
|
424
|
-
|
|
427
|
+
// The first code may be below 6000: a native program's `ProgramError::Custom(n)` errors start at 0.
|
|
428
|
+
const least = errors.length ? code : 0;
|
|
429
|
+
if (!/^\d+$/.test(text) || Number(text) < least || Number(text) > 4_294_967_295)
|
|
430
|
+
reporter.fail(m, `@code must be a number from ${least} up (codes only go up; untagged ones start at 6000)`);
|
|
425
431
|
code = Number(text);
|
|
426
432
|
}
|
|
427
433
|
const def = { code, name: m.name.getText(file), msg: m.initializer.text };
|
|
@@ -508,7 +514,7 @@ export function analyze(entry, files) {
|
|
|
508
514
|
}
|
|
509
515
|
}
|
|
510
516
|
else {
|
|
511
|
-
reporter.fail(stmt,
|
|
517
|
+
reporter.fail(stmt, unsupportedSyntax(stmt.kind, "top level"));
|
|
512
518
|
}
|
|
513
519
|
});
|
|
514
520
|
}
|
|
@@ -822,7 +828,7 @@ export function analyze(entry, files) {
|
|
|
822
828
|
reporter.guard(() => checkBorshLayout(sd, structs, dataEnums, reporter));
|
|
823
829
|
continue;
|
|
824
830
|
}
|
|
825
|
-
reporter.error(ix.node.name ?? ix.node, `argument ${a.name}: ${n} holds a FixedVec and is also account data, nested or returned
|
|
831
|
+
reporter.error(ix.node.name ?? ix.node, `argument ${a.name}: ${n} holds a FixedVec and is also account data, nested or returned: its bytes there are a fixed layout, in instruction data Borsh, and the IDL describes a type one way; declare a separate struct for the argument, or pass the list as its own FixedVec<T, N> argument`);
|
|
826
832
|
}
|
|
827
833
|
}
|
|
828
834
|
// Structs with Options (at any depth) that travel only in instruction data and events (Anchor's BankConfigOpt):
|
|
@@ -6,6 +6,8 @@ export interface Diagnostic {
|
|
|
6
6
|
message: string;
|
|
7
7
|
/** Characters the problem spans from line:column (the construct refused), when known. */
|
|
8
8
|
length?: number;
|
|
9
|
+
/** What to write instead, when known (also the message's last line, "hint: …"): for tools and AI agents. */
|
|
10
|
+
hint?: string;
|
|
9
11
|
}
|
|
10
12
|
export declare class CompileError extends Error {
|
|
11
13
|
readonly diagnostics: Diagnostic[];
|
|
@@ -2,7 +2,7 @@ import ts from "typescript";
|
|
|
2
2
|
import { type Analysis, type TypeArg, type TypeScope } from "../analyze.js";
|
|
3
3
|
import type { Reporter } from "../diagnostics.js";
|
|
4
4
|
import { type AccountParam, type GenericHelper, type Helper, type IdlSeed, type Instruction, type ProgramModel, type ValueType } from "../model.js";
|
|
5
|
-
import { type Value, type Ref, type Local, type Closure, type EmitOptions } from "./shared.js";
|
|
5
|
+
import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions } from "./shared.js";
|
|
6
6
|
/**
|
|
7
7
|
* State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
|
|
8
8
|
* scopes, evaluation-order snapshots and account lookups.
|
|
@@ -153,6 +153,7 @@ export declare abstract class EmitterBase {
|
|
|
153
153
|
}): undefined;
|
|
154
154
|
protected abstract epilogue(): string[];
|
|
155
155
|
protected abstract expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
|
|
156
|
+
protected abstract callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
|
|
156
157
|
protected abstract listMethod(node: ts.CallExpression, method: string): Value | undefined;
|
|
157
158
|
protected abstract isPipeline(e: ts.Expression): e is ts.CallExpression;
|
|
158
159
|
protected abstract closureOf(arg: ts.Expression): Closure;
|
|
@@ -42,6 +42,11 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
|
|
|
42
42
|
protected writeData(node: ts.CallExpression): undefined;
|
|
43
43
|
/** `loadForeign<T>(account, owner)`: read-only view of another program's Anchor account. */
|
|
44
44
|
protected loadForeign(node: ts.CallExpression): Value;
|
|
45
|
+
/**
|
|
46
|
+
* `loadRaw<T>(acct)` / `loadRawMut<T>(acct)`: a native program's account (no discriminator) as a fixed-layout struct
|
|
47
|
+
* from byte 0, checked as a `#[repr(C)]` type's load_checked does: this program's (3007), large enough (3003).
|
|
48
|
+
*/
|
|
49
|
+
protected loadRaw(node: ts.CallExpression, mut: boolean): Value;
|
|
45
50
|
/** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
|
|
46
51
|
protected loadAccount(node: ts.CallExpression, mut: boolean): Value;
|
|
47
52
|
/**
|