@typesol/cli 0.40.0 → 0.42.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 +120 -0
- package/README.md +9 -5
- package/dist/ai.d.ts +10 -0
- package/dist/ai.js +43 -0
- package/dist/cli.js +15 -1
- package/dist/compiler/analyze.js +44 -3
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/emit/base.d.ts +40 -7
- package/dist/compiler/emit/base.js +33 -0
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +102 -2
- package/dist/compiler/emit/calls.js +671 -50
- package/dist/compiler/emit/cpi-core.d.ts +9 -3
- package/dist/compiler/emit/cpi-core.js +12 -7
- package/dist/compiler/emit/cpi.js +8 -14
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +51 -2
- package/dist/compiler/emit/function.js +2 -2
- package/dist/compiler/emit/outline.d.ts +24 -0
- package/dist/compiler/emit/outline.js +100 -0
- package/dist/compiler/emit/program.js +7 -2
- package/dist/compiler/emit/shared.d.ts +35 -1
- package/dist/compiler/emit/shared.js +9 -1
- package/dist/compiler/emit/statements.d.ts +31 -0
- package/dist/compiler/emit/statements.js +272 -14
- package/dist/compiler/emit/storage.d.ts +27 -1
- package/dist/compiler/emit/storage.js +124 -11
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/model.d.ts +20 -1
- package/dist/compiler/model.js +5 -0
- package/dist/testing-stake.d.ts +216 -0
- package/dist/testing-stake.js +526 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -0
- 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/architecture.md +1 -1
- package/docs/audit.md +16 -14
- package/docs/case-study-raydium-cp-swap.md +77 -41
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +107 -14
- package/docs/security-model.md +4 -0
- package/docs/stability.md +69 -0
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/lib/typesol.d.ts +241 -40
- package/llms-full.txt +1352 -0
- package/llms.txt +30 -0
- package/package.json +4 -2
- package/runtime/typesol_rt.h +69 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// `typesol mcp`: a Model Context Protocol server over stdio (newline-delimited JSON-RPC 2.0), so an AI coding agent
|
|
2
|
+
// (Claude Code, Cursor, …) can check a program, read its IDL and search the TypeSOL docs as tools. No dependencies.
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { AGENT_RULES } from "../ai.js";
|
|
8
|
+
import { CompileError, COMPILER_VERSION, generate } from "../compiler/index.js";
|
|
9
|
+
import { buildIdl } from "../compiler/idl.js";
|
|
10
|
+
const DOCS = fileURLToPath(new URL("../../docs", import.meta.url));
|
|
11
|
+
const README = fileURLToPath(new URL("../../README.md", import.meta.url));
|
|
12
|
+
/** Any address: the IDL's `address` field, when the caller gives none. */
|
|
13
|
+
const PLACEHOLDER_ADDRESS = "11111111111111111111111111111111";
|
|
14
|
+
/** The program to work on: a file path, or source text (written to a temporary file, so imports of "typesol" work). */
|
|
15
|
+
function withProgram(args, fn) {
|
|
16
|
+
if (typeof args.file === "string") {
|
|
17
|
+
const file = path.resolve(args.file);
|
|
18
|
+
if (!existsSync(file))
|
|
19
|
+
throw new Error(`no such file: ${file}`);
|
|
20
|
+
return fn(file);
|
|
21
|
+
}
|
|
22
|
+
if (typeof args.source !== "string")
|
|
23
|
+
throw new Error("give `file` (a path) or `source` (the program's text)");
|
|
24
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), "typesol-mcp-"));
|
|
25
|
+
const entry = path.join(dir, "program.ts");
|
|
26
|
+
writeFileSync(entry, args.source);
|
|
27
|
+
try {
|
|
28
|
+
return fn(entry, new Map([[entry, args.source]]));
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
rmSync(dir, { recursive: true, force: true });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** The docs as sections (a heading and what follows it), for the search tool. */
|
|
35
|
+
function sections() {
|
|
36
|
+
const out = [];
|
|
37
|
+
const files = [
|
|
38
|
+
README,
|
|
39
|
+
...(existsSync(DOCS)
|
|
40
|
+
? readdirSync(DOCS)
|
|
41
|
+
.filter((f) => f.endsWith(".md"))
|
|
42
|
+
.map((f) => path.join(DOCS, f))
|
|
43
|
+
: []),
|
|
44
|
+
];
|
|
45
|
+
for (const f of files) {
|
|
46
|
+
const name = path.basename(f);
|
|
47
|
+
let heading = name;
|
|
48
|
+
let text = [];
|
|
49
|
+
const flush = () => {
|
|
50
|
+
if (text.join("").trim())
|
|
51
|
+
out.push({ source: name, heading, text: text.join("\n").trim() });
|
|
52
|
+
text = [];
|
|
53
|
+
};
|
|
54
|
+
for (const line of readFileSync(f, "utf8").split("\n")) {
|
|
55
|
+
if (/^#{1,3} /.test(line)) {
|
|
56
|
+
flush();
|
|
57
|
+
heading = line.replace(/^#+ /, "");
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
text.push(line);
|
|
61
|
+
}
|
|
62
|
+
flush();
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
const TOOLS = [
|
|
67
|
+
{
|
|
68
|
+
name: "check",
|
|
69
|
+
description: "Type-check a TypeSOL program and list what the compiler refuses, each with its file, line, column, message and, for the usual mistakes, a hint saying what to write instead. Give `file` (a path) or `source` (the program's text).",
|
|
70
|
+
inputSchema: {
|
|
71
|
+
type: "object",
|
|
72
|
+
properties: {
|
|
73
|
+
file: { type: "string", description: "path to the program's entry .ts file" },
|
|
74
|
+
source: { type: "string", description: "the program's source text" },
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
run(args) {
|
|
78
|
+
return withProgram(args, (entry, files) => {
|
|
79
|
+
try {
|
|
80
|
+
const { model } = generate(entry, { files });
|
|
81
|
+
return { text: JSON.stringify({ ok: true, program: model.name, instructions: model.instructions.map((i) => i.name), diagnostics: [] }) };
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
if (!(e instanceof CompileError))
|
|
85
|
+
throw e;
|
|
86
|
+
// Source given as text is reported as program.ts, not the temporary file it was checked in.
|
|
87
|
+
const diagnostics = files ? e.diagnostics.map((d) => ({ ...d, file: path.basename(d.file) })) : e.diagnostics;
|
|
88
|
+
return { text: JSON.stringify({ ok: false, diagnostics }) };
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
name: "idl",
|
|
95
|
+
description: "The Anchor-compatible IDL a TypeSOL program compiles to (instructions, accounts, types, errors, events). Give `file` or `source`.",
|
|
96
|
+
inputSchema: {
|
|
97
|
+
type: "object",
|
|
98
|
+
properties: { file: { type: "string" }, source: { type: "string" }, address: { type: "string", description: "the program address to record" } },
|
|
99
|
+
},
|
|
100
|
+
run(args) {
|
|
101
|
+
return withProgram(args, (entry, files) => {
|
|
102
|
+
try {
|
|
103
|
+
const address = typeof args.address === "string" ? args.address : PLACEHOLDER_ADDRESS;
|
|
104
|
+
return { text: JSON.stringify(buildIdl(generate(entry, { files }).model, address), null, 2) };
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
if (!(e instanceof CompileError))
|
|
108
|
+
throw e;
|
|
109
|
+
return { text: JSON.stringify({ ok: false, diagnostics: e.diagnostics }), isError: true };
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
name: "docs",
|
|
116
|
+
description: "Search the TypeSOL documentation (the language reference, errors, testing, CLI, porting from Anchor, case studies). Returns the best-matching sections.",
|
|
117
|
+
inputSchema: { type: "object", properties: { query: { type: "string" }, limit: { type: "number" } }, required: ["query"] },
|
|
118
|
+
run(args) {
|
|
119
|
+
const words = String(args.query ?? "")
|
|
120
|
+
.toLowerCase()
|
|
121
|
+
.split(/\W+/)
|
|
122
|
+
.filter((w) => w.length > 1);
|
|
123
|
+
if (!words.length)
|
|
124
|
+
throw new Error("give a `query`");
|
|
125
|
+
const scored = sections()
|
|
126
|
+
.map((s) => {
|
|
127
|
+
const hay = `${s.heading}\n${s.text}`.toLowerCase();
|
|
128
|
+
const score = words.reduce((n, w) => n + (hay.split(w).length - 1) + (s.heading.toLowerCase().includes(w) ? 5 : 0), 0);
|
|
129
|
+
return { s, score };
|
|
130
|
+
})
|
|
131
|
+
.filter((x) => x.score > 0)
|
|
132
|
+
.sort((a, b) => b.score - a.score)
|
|
133
|
+
.slice(0, Math.max(1, Math.min(10, Number(args.limit ?? 4))));
|
|
134
|
+
if (!scored.length)
|
|
135
|
+
return { text: "No section matches; try other words, or the `rules` tool." };
|
|
136
|
+
return { text: scored.map(({ s }) => `# ${s.heading} (${s.source})\n\n${s.text.slice(0, 4000)}`).join("\n\n---\n\n") };
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: "rules",
|
|
141
|
+
description: "The rules a TypeSOL program follows that ordinary TypeScript habits break (bigint integers, imports, no throw/async/class, Mut<T> for changed accounts, …), and how to check and test.",
|
|
142
|
+
inputSchema: { type: "object", properties: {} },
|
|
143
|
+
run() {
|
|
144
|
+
return { text: AGENT_RULES };
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
];
|
|
148
|
+
/** One request's response (undefined for a notification). */
|
|
149
|
+
export function handle(msg) {
|
|
150
|
+
const reply = (result) => ({ jsonrpc: "2.0", id: msg.id ?? null, result });
|
|
151
|
+
const fail = (code, message) => ({ jsonrpc: "2.0", id: msg.id ?? null, error: { code, message } });
|
|
152
|
+
if (msg.id === undefined || msg.id === null)
|
|
153
|
+
return undefined; // notifications (notifications/initialized, …)
|
|
154
|
+
switch (msg.method) {
|
|
155
|
+
case "initialize":
|
|
156
|
+
return reply({
|
|
157
|
+
protocolVersion: typeof msg.params?.protocolVersion === "string" ? msg.params.protocolVersion : "2025-06-18",
|
|
158
|
+
capabilities: { tools: {} },
|
|
159
|
+
serverInfo: { name: "typesol", version: COMPILER_VERSION },
|
|
160
|
+
instructions: "TypeSOL compiles a TypeScript subset to Solana programs. Call `rules` first, `check` after every edit, `docs` for the reference.",
|
|
161
|
+
});
|
|
162
|
+
case "ping":
|
|
163
|
+
return reply({});
|
|
164
|
+
case "tools/list":
|
|
165
|
+
return reply({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
|
|
166
|
+
case "tools/call": {
|
|
167
|
+
const tool = TOOLS.find((t) => t.name === msg.params?.name);
|
|
168
|
+
if (!tool)
|
|
169
|
+
return fail(-32602, `unknown tool: ${String(msg.params?.name)}`);
|
|
170
|
+
try {
|
|
171
|
+
const out = tool.run(msg.params?.arguments ?? {});
|
|
172
|
+
return reply({ content: [{ type: "text", text: out.text }], isError: !!out.isError });
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
return reply({ content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }], isError: true });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
default:
|
|
179
|
+
return fail(-32601, `method not found: ${String(msg.method)}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** Serve on stdin / stdout until stdin closes. Logs go to stderr: stdout carries only protocol messages. */
|
|
183
|
+
export function serve() {
|
|
184
|
+
return new Promise((resolve) => {
|
|
185
|
+
let buffer = "";
|
|
186
|
+
process.stdin.setEncoding("utf8");
|
|
187
|
+
process.stdin.on("data", (chunk) => {
|
|
188
|
+
buffer += chunk;
|
|
189
|
+
let nl;
|
|
190
|
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
|
191
|
+
const line = buffer.slice(0, nl).trim();
|
|
192
|
+
buffer = buffer.slice(nl + 1);
|
|
193
|
+
if (!line)
|
|
194
|
+
continue;
|
|
195
|
+
let out;
|
|
196
|
+
try {
|
|
197
|
+
out = handle(JSON.parse(line));
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
out = { jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } };
|
|
201
|
+
}
|
|
202
|
+
if (out)
|
|
203
|
+
process.stdout.write(JSON.stringify(out) + "\n");
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
process.stdin.on("end", () => resolve());
|
|
207
|
+
});
|
|
208
|
+
}
|
package/dist/workspace.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* Program keypairs live in `<out>/deploy/<name>-keypair.json` (created on first build; keep them, never commit them).
|
|
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
|
+
import { agentsMd, CLAUDE_MD, cursorRule, MCP_JSON } from "./ai.js";
|
|
14
15
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
16
|
import path from "node:path";
|
|
16
17
|
import { writeClient } from "./tools/clientgen.js";
|
|
@@ -170,6 +171,13 @@ export function scaffold(dir, name, template = "counter") {
|
|
|
170
171
|
...t.devDependencies,
|
|
171
172
|
},
|
|
172
173
|
}, null, 2) + "\n",
|
|
174
|
+
// AI coding agents: the rules (AGENTS.md, and CLAUDE.md / Cursor's rules pointing at the same text) and the
|
|
175
|
+
// TypeSOL MCP server (check, IDL, docs as tools).
|
|
176
|
+
"AGENTS.md": agentsMd(name),
|
|
177
|
+
"CLAUDE.md": CLAUDE_MD,
|
|
178
|
+
".cursor/rules/typesol.mdc": cursorRule(),
|
|
179
|
+
".mcp.json": MCP_JSON,
|
|
180
|
+
".cursor/mcp.json": MCP_JSON,
|
|
173
181
|
// VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
|
|
174
182
|
".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
|
|
175
183
|
// target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
|
package/docs/ai.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Writing TypeSOL with an AI agent
|
|
2
|
+
|
|
3
|
+
TypeSOL is TypeScript, which AI coding agents write well, but a subset of it: a model's ordinary habits (`1` for an
|
|
4
|
+
integer, `console.log`, `throw`, `xs[i]`) are refused. Four things close that gap.
|
|
5
|
+
|
|
6
|
+
## The rules in the project
|
|
7
|
+
|
|
8
|
+
`typesol init` writes the rules an agent needs into the project:
|
|
9
|
+
|
|
10
|
+
| File | Read by |
|
|
11
|
+
| --- | --- |
|
|
12
|
+
| `AGENTS.md` | Codex, Cursor, Zed, Aider and other agents that read AGENTS.md |
|
|
13
|
+
| `CLAUDE.md` (`@AGENTS.md`) | Claude Code |
|
|
14
|
+
| `.cursor/rules/typesol.mdc` | Cursor (always applied to `programs/` and `tests/`) |
|
|
15
|
+
|
|
16
|
+
They say what ordinary TypeScript habits break (bigint integers, imports from `"typesol"`, no `throw` / `async` /
|
|
17
|
+
`class`, `Mut<T>` for an account that changes, `.get(i)` / `.set(i, v)` on lists) and how to check and test. Keep your
|
|
18
|
+
own project notes below them in AGENTS.md.
|
|
19
|
+
|
|
20
|
+
## llms.txt
|
|
21
|
+
|
|
22
|
+
[typesol.com/llms.txt](https://typesol.com/llms.txt) is the index of the docs for models
|
|
23
|
+
([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
|
|
24
|
+
and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
|
|
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`).
|
|
27
|
+
|
|
28
|
+
## Errors an agent can fix by itself
|
|
29
|
+
|
|
30
|
+
`typesol check --json` prints `{ "ok": false, "diagnostics": [...] }`; each diagnostic has `file`, `line`, `column`,
|
|
31
|
+
`length`, `message` and, for the usual mistakes, `hint`: what to write instead ("integers (u64, u32, i64 …) are bigint
|
|
32
|
+
in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on check → edit → check without building.
|
|
33
|
+
|
|
34
|
+
## The MCP server
|
|
35
|
+
|
|
36
|
+
`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`. Other clients take the
|
|
38
|
+
same command:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{ "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
| Tool | What it does |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
|
|
47
|
+
| `idl` | the Anchor-compatible IDL the program compiles to |
|
|
48
|
+
| `docs` | searches the docs and returns the best-matching sections |
|
|
49
|
+
| `rules` | the rules above |
|
|
50
|
+
|
|
51
|
+
Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
|
|
52
|
+
files, which an agent should do in the open.
|
package/docs/architecture.md
CHANGED
|
@@ -32,7 +32,7 @@ program.so + program.build.json (manifest: versions, sha256 of sources and binar
|
|
|
32
32
|
| `ts-plugin/` | The editor plugin (`typesol/ts-plugin`) |
|
|
33
33
|
| `examples/` | Example programs; the `typesol init` templates are copies of three of them |
|
|
34
34
|
| `test/` | The compiler's test suite (`pnpm test:core`), by subject: `language/`, `security/`, `examples/`, `integrations/` (token, Metaplex, oracle and other CPIs), `client/`, `cli/`, `verification/` (differential and fuzz tests). Shared: `harness.ts` and the `*-helpers.ts`, `fixtures/` (programs the tests compile), `golden/` (pinned generated C and clients), `programs/` (third-party program binaries, see its SOURCES.md), `anchor-twins/` (below) |
|
|
35
|
-
| `showcase/` | Ports, apart from the compiler's own tests (`pnpm test:showcase`, its own CI job): `mainnet/` (Raydium CP-Swap and CLMM, Jito's MEV programs, Marginfi, coral-xyz/multisig, each checked against the binary on mainnet), `program-examples/` (TypeSOL rewrites of solana-developers/program-examples), `test/` (their differential tests, fuzzers, helpers and fixtures; `porting/` for the program-examples) |
|
|
35
|
+
| `showcase/` | Ports, apart from the compiler's own tests (`pnpm test:showcase`, its own CI job): `mainnet/` (SPL Stake Pool, Raydium AMM v4, CP-Swap and CLMM, Jito's MEV programs, Marginfi, coral-xyz/multisig, each checked against the binary on mainnet), `program-examples/` (TypeSOL rewrites of solana-developers/program-examples), `test/` (their differential tests, fuzzers, helpers and fixtures; `porting/` for the program-examples) |
|
|
36
36
|
| `test/anchor-twins/` | Anchor twins of the counter, vault and escrow examples, for the differential tests (`pnpm build:twins`) and the zero-copy client test; the benchmarks themselves are in [typesol-lang/benchmarks](https://github.com/typesol-lang/benchmarks) |
|
|
37
37
|
| `scripts/` | `smoke.ts`, `localnet.sh` and `localnet-fixtures.ts` (a local validator run), `fetch-programs.sh` (third-party binaries), `readme-bench.ts` (the README numbers), `codegen-snapshot.ts` (the generated C and IDL of every program, to diff a refactor), `release-manifest.ts` (a release's binary, IDL and toolchain hashes) |
|
|
38
38
|
| `docs/` | User and contributor documentation (also published on typesol.com) |
|
package/docs/audit.md
CHANGED
|
@@ -7,21 +7,21 @@ with TypeSOL are out of scope; their authors audit them.
|
|
|
7
7
|
|
|
8
8
|
## Scope
|
|
9
9
|
|
|
10
|
-
In order of priority. Line counts at 0.
|
|
10
|
+
In order of priority. Line counts at 0.40.0 (November 2026).
|
|
11
11
|
|
|
12
12
|
| Priority | Component | Files | Lines | Why |
|
|
13
13
|
| --- | --- | --- | ---: | --- |
|
|
14
|
-
| 1 | C runtime | `runtime/typesol_rt.h` | 2,
|
|
15
|
-
| 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` |
|
|
16
|
-
| 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 2,
|
|
17
|
-
| 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` |
|
|
14
|
+
| 1 | C runtime | `runtime/typesol_rt.h` | 2,510 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
|
|
15
|
+
| 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 870 | Which checks each account parameter gets, and their order |
|
|
16
|
+
| 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 2,802 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
|
|
17
|
+
| 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 4,084 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
|
|
18
18
|
| 1 | Metaplex CPIs | `src/compiler/emit/metaplex.ts` | 1,454 | Token Metadata, Core and Bubblegum instruction layouts and their account lists |
|
|
19
|
-
| 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 1,
|
|
20
|
-
| 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 2,
|
|
21
|
-
| 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,
|
|
19
|
+
| 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 1,820 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
|
|
20
|
+
| 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 2,930 | What the language accepts; constraints and account types as parsed from the source |
|
|
21
|
+
| 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,316 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
|
|
22
22
|
| 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, deploy and verification commands |
|
|
23
23
|
|
|
24
|
-
The language surface is `lib/typesol.d.ts` (2,
|
|
24
|
+
The language surface is `lib/typesol.d.ts` (2,163 lines): every type and built-in a program can use, with its
|
|
25
25
|
documented behavior. [docs/language.md](language.md) is the reference; [docs/architecture.md](architecture.md) maps
|
|
26
26
|
the code, [docs/runtime.md](runtime.md) the runtime's conventions.
|
|
27
27
|
|
|
@@ -49,11 +49,13 @@ accepts. Areas where a bug would be most damaging, and where earlier internal re
|
|
|
49
49
|
## Earlier reviews
|
|
50
50
|
|
|
51
51
|
Internal reviews, by the maintainers, in October 2026. Their findings and fixes are in the CHANGELOG. The releases
|
|
52
|
-
after 0.25.0 (0.26.0 to 0.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
52
|
+
after 0.25.0 (0.26.0 to 0.40.0) have had no review of this kind yet; they add, among others, `u256`, big-endian seeds
|
|
53
|
+
and accounts loaded in the body (0.37.0), stored bumps in nested fields and error members without messages (0.38.0),
|
|
54
|
+
`@code`, `@repr` / `@serialization`, `@bytes` / `@idlName`, `f64`, Options inside Options in arguments and events,
|
|
55
|
+
loop-scoped `loadAccountMut` with `Dup<T>`, account resizing and raw writes, `systemProgram.createPda` (0.39.0), and
|
|
56
|
+
the native-program surface: `loadRaw` / `loadRawMut` (accounts without a discriminator), instruction data readers,
|
|
57
|
+
error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0). An external review should include them;
|
|
58
|
+
the native-program surface first, since it skips the account checks Anchor-style parameters get.
|
|
57
59
|
|
|
58
60
|
- **0.25.0** (runtime and emitted checks): two Medium issues fixed, a remaining account loaded mutably twice through
|
|
59
61
|
the same slot, and a Vec element written after its right side resized the Vec; plus a token program ambiguity,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Case study: Raydium CP-Swap
|
|
2
2
|
|
|
3
|
-
This page ports
|
|
3
|
+
This page ports a production AMM, every instruction of it: [Raydium CP-Swap](https://github.com/raydium-io/raydium-cp-swap)
|
|
4
4
|
(`programs/cp-swap`, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
|
|
5
5
|
`CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`showcase/mainnet/raydium-cp-swap/`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-cp-swap)
|
|
6
6
|
(`state.ts`, `curve.ts`, `raydium_cp_swap.ts`). As with [coral-xyz/multisig](case-study-multisig.md), it is checked
|
|
@@ -8,32 +8,24 @@ against the binary that runs on mainnet, not a rebuild.
|
|
|
8
8
|
|
|
9
9
|
## What is ported
|
|
10
10
|
|
|
11
|
-
The port covers
|
|
11
|
+
The port covers all 21 of the original's instructions:
|
|
12
12
|
|
|
13
|
-
- `initialize`,
|
|
13
|
+
- pool creation: `initialize`, `initialize_v2` (the same without the rent sysvar, choosing the creator fee) and
|
|
14
|
+
`initialize_with_permission` (for a payer Raydium authorized, on behalf of another creator, with the creator fee on);
|
|
14
15
|
- the four trading instructions: `swap_base_input`, `swap_base_output`, `deposit` and `withdraw`;
|
|
15
|
-
- `collect_protocol_fee` and
|
|
16
|
-
|
|
16
|
+
- the fees: `collect_protocol_fee`, `collect_fund_fee`, `collect_creator_fee` and
|
|
17
|
+
`collect_creator_fee_permissionless`;
|
|
18
|
+
- the admin instructions: `create_amm_config`, `update_amm_config`, `update_pool_status`, `create_permission_pda`,
|
|
19
|
+
`close_permission_pda`, `create_creator_fee_share`, `close_creator_fee_share`, `create_support_mint_associated`,
|
|
20
|
+
`close_support_mint_associated` and `collect_excess_lamports`.
|
|
17
21
|
|
|
18
22
|
The port keeps the original's account layouts:
|
|
19
23
|
|
|
20
|
-
- `AmmConfig`
|
|
24
|
+
- `AmmConfig`, `Permission`, `CreatorFeeShare` and `SupportMintAssociated` are Borsh accounts of fixed size.
|
|
21
25
|
- `PoolState` and `ObservationState` are zero-copy `#[repr(C, packed)]` structs, which is TypeSOL's fixed layout.
|
|
22
26
|
|
|
23
|
-
It also keeps the original's names, argument order and error codes, and emits the same events
|
|
24
|
-
`LpChangeEvent`). Existing pools, clients and indexers work with it unchanged.
|
|
25
|
-
|
|
26
|
-
These are not ported yet:
|
|
27
|
-
|
|
28
|
-
- **`initialize_with_permission`.** It is `initialize` for a creator the admin authorized, with the creator fee on.
|
|
29
|
-
- **The creator-fee instructions**: `collect_creator_fee`, `collect_creator_fee_permissionless`,
|
|
30
|
-
`create_creator_fee_share` and `close_creator_fee_share`.
|
|
31
|
-
- **The permission instructions**: `create_permission_pda` and `close_permission_pda`.
|
|
32
|
-
- **The support-mint instructions**: `create_support_mint_associated` and `close_support_mint_associated`.
|
|
33
|
-
- **`collect_excess_lamports`.**
|
|
34
|
-
|
|
35
|
-
The pool logic these depend on is in the port (fee booking, the creator-fee split in the swap math, tested below with
|
|
36
|
-
the creator fee on), so a pool the original created and configured is traded the same way.
|
|
27
|
+
It also keeps the original's names, account order, argument order and error codes, and emits the same events
|
|
28
|
+
(`SwapEvent`, `LpChangeEvent`). Existing pools, clients and indexers work with it unchanged.
|
|
37
29
|
|
|
38
30
|
## What it needed
|
|
39
31
|
|
|
@@ -56,6 +48,10 @@ Four Token-2022 reads were added to the compiler for this port (`test/integratio
|
|
|
56
48
|
- `transferFeeBasisPoints(mint)` and `transferFeeMaximum(mint)`: the fee in force this epoch.
|
|
57
49
|
- `extensionsWithin(account, [types])`: the original's list of mint extensions a pool accepts.
|
|
58
50
|
|
|
51
|
+
The instructions added later needed none: `Ata<InitIfNeeded<…>>` for the creator's token accounts, `CloseTo` for the
|
|
52
|
+
closing instructions, `readData` to read a token account as `StateWithExtensions::unpack` does, and `invoke` for the
|
|
53
|
+
token instructions Anchor has no wrapper for (`WithdrawExcessLamports`, `SyncNative`, `UnwrapLamports`).
|
|
54
|
+
|
|
59
55
|
The rest uses features TypeSOL already had:
|
|
60
56
|
|
|
61
57
|
- `constraint(…)`, for Anchor's `address = pool_state.load()?.amm_config` and `constraint = …` in Anchor's order;
|
|
@@ -66,21 +62,24 @@ The rest uses features TypeSOL already had:
|
|
|
66
62
|
## How it was checked
|
|
67
63
|
|
|
68
64
|
[`showcase/test/raydium-cp-swap.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/raydium-cp-swap.test.ts) loads the binary dumped from
|
|
69
|
-
mainnet on 2026-
|
|
65
|
+
mainnet on 2026-11-07 (deployed at slot 463522946 on 2026-10-31; sha256 in [`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)) into one
|
|
70
66
|
LiteSVM and the port into another. Both use the same program id and the same clock.
|
|
71
67
|
|
|
72
68
|
**Setup.**
|
|
73
69
|
|
|
74
70
|
- Mints and token accounts are made by the same SPL Token / Token-2022 instructions in both.
|
|
75
|
-
-
|
|
76
|
-
|
|
71
|
+
- Raydium's five signing keys (the admin, and the owners of permissions, fee shares, supported mints and excess
|
|
72
|
+
lamports) are replaced by test keys in both: in the original, at each place its code loads one (four 64-bit
|
|
73
|
+
immediates); in the port, in its source. The admin instructions then run in both.
|
|
74
|
+
- Pools for trading (an `AmmConfig`, a pool's `PoolState` and its `ObservationState`) are written in both as the
|
|
75
|
+
original lays them out, so each test starts from the state it needs.
|
|
77
76
|
|
|
78
77
|
**Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
|
|
79
78
|
code), the same lamports, owner and data for every account involved, and the same events byte for byte.
|
|
80
79
|
|
|
81
|
-
There are
|
|
80
|
+
There are 136 transactions:
|
|
82
81
|
|
|
83
|
-
- **Pool creation.**
|
|
82
|
+
- **Pool creation.** With `initialize`, these cases are covered:
|
|
84
83
|
- a pool at its PDA, at a signing keypair, and at a pre-funded address;
|
|
85
84
|
- a pool with the creation fee, paid in wrapped SOL;
|
|
86
85
|
- a pool of Token-2022 fee mints;
|
|
@@ -90,12 +89,26 @@ There are 70 transactions:
|
|
|
90
89
|
- an unsupported extension (6007);
|
|
91
90
|
- a disabled config (6000);
|
|
92
91
|
- too little liquidity (6009).
|
|
92
|
+
|
|
93
|
+
`initialize_v2` with the creator fee off and on in each of its three modes, and its refusals.
|
|
94
|
+
`initialize_with_permission` without a permission (3007), with another payer's (2006), and with one.
|
|
93
95
|
- **Swaps.** Both directions, by input and by output; the observation ring advancing as the clock moves; slippage
|
|
94
96
|
(6005); zero amounts.
|
|
95
97
|
- **Liquidity.** Deposit, a partial withdrawal, slippage both ways, withdrawing more LP than held, zero.
|
|
96
98
|
- **Fees.** Protocol and fund fees collected by their owners after trading, and refused for anyone else (6001).
|
|
97
99
|
- **Creator fees.** Pools with the creator fee on at 0.05%, taken from the input token, only token_0, or only
|
|
98
|
-
token_1: swaps both ways, by input and by output, booking the fee on the right side.
|
|
100
|
+
token_1: swaps both ways, by input and by output, booking the fee on the right side. Collected by the creator (its
|
|
101
|
+
token accounts created on the way) at the config's share, again with nothing owed (6014), with the creator's own
|
|
102
|
+
share, by anyone with the permissionless form, at the config's share again after the share is closed, for SPL Token
|
|
103
|
+
and Token-2022 fee mints; a share above 100% (6003); anyone but the creator (2012).
|
|
104
|
+
- **Permissions, fee shares, supported mints.** Each created and closed by Raydium's keys and refused for anyone else
|
|
105
|
+
(6001, 6000); a fee share above 100% (6003); a permission created twice; a supported-mint entry for an SPL Token
|
|
106
|
+
mint (6000). A Token-2022 mint with a permanent delegate is refused for a pool (6007) until it is listed and the
|
|
107
|
+
entry passed, and again without the entry.
|
|
108
|
+
- **Excess lamports.** Swept from the pool and its observation account (rent kept), from an SPL Token and a Token-2022
|
|
109
|
+
vault and the LP mint (`WithdrawExcessLamports`), from wrapped SOL held by the pool authority (`SyncNative`, then
|
|
110
|
+
`UnwrapLamports` of exactly the difference); a trader's account (the token program's OwnerMismatch, 4); anyone but
|
|
111
|
+
the two keys (6001).
|
|
99
112
|
- **The price oracle.** A new point, a second swap within 15 seconds (added to the current point), and a ring at its
|
|
100
113
|
last slot whose cumulative price is 10 below `u128::MAX`: the next point wraps to slot 0 and the sum wraps around.
|
|
101
114
|
- **Token-2022.** A pool of two transfer-fee mints (1.5% and 0.37%): swaps both ways and by output, deposit and
|
|
@@ -107,28 +120,45 @@ There are 70 transactions:
|
|
|
107
120
|
- Swaps or deposits on a pool whose status disables them (6000).
|
|
108
121
|
- The admin instructions sent by anyone but the admin (2012, 6001).
|
|
109
122
|
|
|
123
|
+
**Fuzzing.** A random sequence (`FUZZ_SEED` reproduces one, `CP_FUZZ_STEPS` lengthens it; 120 steps by default) runs
|
|
124
|
+
in two pools, one of SPL Token mints and one of Token-2022 mints with random transfer fees, each with the creator fee
|
|
125
|
+
on in a random mode at a random rate and protocol share: swaps both ways by input and by output with random amounts
|
|
126
|
+
and slippage limits, deposits, withdrawals, creator fee collections (by the creator and permissionless), protocol and
|
|
127
|
+
fund fee collections, and the clock moving on. Every step must give the same outcome, account bytes and events as the
|
|
128
|
+
original. Runs of 600 steps on several seeds found one difference, now fixed: an exact-output swap for the whole
|
|
129
|
+
vault or more panics in the original (`checked_sub(..).unwrap()`, `checked_ceil_div(..).unwrap()`), where the port
|
|
130
|
+
failed with 5100; it panics now at the original's location. These fuzz transactions are not in the 136 above.
|
|
131
|
+
|
|
110
132
|
## Cost
|
|
111
133
|
|
|
112
134
|
Compute units per transaction, mainnet original against the port, from that test:
|
|
113
135
|
|
|
114
136
|
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
115
137
|
| --- | ---: | ---: | ---: |
|
|
116
|
-
| `initialize` | 83,
|
|
117
|
-
| `initialize`, Token-2022 transfer fees |
|
|
118
|
-
| `
|
|
119
|
-
| `
|
|
120
|
-
| `
|
|
121
|
-
| `
|
|
138
|
+
| `initialize` | 83,559 | 39,878 | −52% |
|
|
139
|
+
| `initialize`, Token-2022 transfer fees | 93,047 | 53,834 | −42% |
|
|
140
|
+
| `initialize_v2`, creator fee on | 86,286 | 41,760 | −52% |
|
|
141
|
+
| `initialize_with_permission` | 98,221 | 43,358 | −56% |
|
|
142
|
+
| `swap_base_input` | 24,162 | 5,734 | −76% |
|
|
143
|
+
| `swap_base_output` | 24,591 | 5,989 | −76% |
|
|
144
|
+
| `deposit` | 25,007 | 6,194 | −75% |
|
|
145
|
+
| `withdraw` | 25,214 | 6,203 | −75% |
|
|
122
146
|
| `collect_protocol_fee` | 20,205 | 4,189 | −79% |
|
|
123
|
-
| `
|
|
124
|
-
| `
|
|
125
|
-
| `
|
|
147
|
+
| `collect_creator_fee`, creating the creator's two token accounts | 61,644 | 34,014 | −45% |
|
|
148
|
+
| `collect_creator_fee_permissionless` | 28,165 | 5,887 | −79% |
|
|
149
|
+
| `create_permission_pda` | 10,525 | 2,291 | −78% |
|
|
150
|
+
| `create_creator_fee_share` | 8,421 | 2,067 | −75% |
|
|
151
|
+
| `create_support_mint_associated` | 7,837 | 2,012 | −74% |
|
|
152
|
+
| `close_creator_fee_share` | 5,169 | 767 | −85% |
|
|
153
|
+
| `collect_excess_lamports`, wrapped SOL | 10,798 | 3,764 | −65% |
|
|
154
|
+
| `swap_base_input`, Token-2022 transfer fees | 31,339 | 12,082 | −61% |
|
|
155
|
+
| `swap_base_output`, Token-2022 transfer fees | 32,508 | 14,097 | −57% |
|
|
156
|
+
| `deposit`, Token-2022 transfer fees | 33,203 | 14,478 | −56% |
|
|
126
157
|
|
|
127
158
|
The Token-2022 rows include the token program's own work, which is the same in both. Refusals cost far less. For
|
|
128
|
-
example, a swap through the wrong config costs 17,
|
|
159
|
+
example, a swap through the wrong config costs 17,193 against 1,656.
|
|
129
160
|
|
|
130
|
-
On size, the port's binary is
|
|
131
|
-
14 instructions not ported here, so the size ratio overstates the gain for the same feature set.
|
|
161
|
+
On size, the port's binary is 214,944 bytes and the deployed original is 749,848 bytes, for the same 21 instructions.
|
|
132
162
|
|
|
133
163
|
Pool creation is mostly the token programs' and the System Program's own work (account creation, initialization,
|
|
134
164
|
transfers), which costs the same in both. The difference is the program's part. Its cost also varies from run to run
|
|
@@ -141,12 +171,18 @@ when the values fit, and an instruction reads the Clock once. Together they took
|
|
|
141
171
|
|
|
142
172
|
- **Panics.** Where the original calls `unwrap()` or `assert!`, it aborts with `ProgramFailedToComplete`. The port
|
|
143
173
|
fails with a numbered error instead:
|
|
144
|
-
-
|
|
145
|
-
- a division by zero, 5101: the price of an empty side, or an exact-output swap for exactly what the vault holds;
|
|
174
|
+
- a division by zero, 5101: the price of an empty side;
|
|
146
175
|
- invalid input, 6003: a fee rate out of range in the admin instructions, which only the admin can reach.
|
|
176
|
+
- an overflow adding to the destination's lamports in `collect_excess_lamports`, 5100 where the original returns
|
|
177
|
+
`ArithmeticOverflow`: no account holds that many lamports.
|
|
147
178
|
|
|
148
|
-
The swaps and liquidity instructions reach none of these with the amounts a pool can hold.
|
|
179
|
+
The swaps and liquidity instructions reach none of these with the amounts a pool can hold. An exact-output swap for
|
|
180
|
+
the whole vault or more, which a trader can send, panics as the original does (fuzzing found it).
|
|
149
181
|
- **Check order on double faults.** Account checks run in Anchor's order, so a transaction breaking one check gets the
|
|
150
182
|
same code. The port keeps the pool's `address = …` and `token::…` constraints as `constraint(…)` calls in Anchor's
|
|
151
183
|
order. A transaction that breaks a token check and an account-type check at once can still be reported differently.
|
|
184
|
+
- **Token accounts in `collect_excess_lamports`.** The original reads a remaining account as a token account with
|
|
185
|
+
`StateWithExtensions::unpack`, which also walks the Token-2022 extension list. The port checks the size, the
|
|
186
|
+
account type byte, the state and the option tags, not the extension list: a Token-2022 account the token program
|
|
187
|
+
wrote always has a valid one.
|
|
152
188
|
- **Logs.** Error messages are TypeSOL's. Codes and events are the original's.
|