@typesol/cli 0.39.0 → 0.40.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 +46 -0
- package/README.md +22 -19
- package/dist/cli.js +37 -3
- package/dist/compiler/analyze.js +10 -5
- package/dist/compiler/emit/base.d.ts +2 -1
- package/dist/compiler/emit/calls.d.ts +5 -0
- package/dist/compiler/emit/calls.js +165 -4
- 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/docs/case-study-marginfi.md +2 -2
- package/docs/case-study-raydium-amm.md +80 -0
- package/docs/language.md +27 -7
- package/docs/testing.md +6 -5
- package/docs/troubleshooting.md +6 -0
- package/lib/typesol.d.ts +73 -2
- package/package.json +1 -1
- package/runtime/typesol_rt.h +47 -0
- package/ts-plugin/index.js +24 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,52 @@ codes, and says so here.
|
|
|
6
6
|
|
|
7
7
|
## Unreleased
|
|
8
8
|
|
|
9
|
+
## 0.40.0 — 2026-11-06
|
|
10
|
+
|
|
11
|
+
Raydium AMM v4 ported in full, a native (non-Anchor) program, and checked against its mainnet binary down to its log
|
|
12
|
+
lines and panics. The compiler gained what a native program needs: accounts without a discriminator, the instruction
|
|
13
|
+
data read by offset, errors from code 0, built-in program errors, panics with a location, and the entrypoint's log
|
|
14
|
+
lines. Also: functions chosen at run time, `find(…)!.field` / `?.field` on struct lists, struct maps inside chains, and
|
|
15
|
+
hints under the errors newcomers meet first, in the CLI and the editor. Programs that use none of the new features
|
|
16
|
+
compile to the same C as in 0.39.0.
|
|
17
|
+
|
|
18
|
+
- Examples: showcase/mainnet/raydium-amm, a port of Raydium AMM v4 (the native program at 675kPX9M…, all of its
|
|
19
|
+
instructions: Initialize2, deposits, withdrawals, the v1 and v2 swaps base in and base out, P&L, parameters, the
|
|
20
|
+
config, excess lamports), checked against the mainnet binary (test/programs/raydium_amm_v4.so) on 484 transactions,
|
|
21
|
+
fuzzed: the same outcomes, account bytes and log lines, ray_log records and the original's panics included; swaps
|
|
22
|
+
take 41–44% of the original's compute units, deposits and withdrawals 35–37%. See docs/case-study-raydium-amm.md.
|
|
23
|
+
- New (native programs; docs/language.md "Porting a native program"): `loadRaw<T>` / `loadRawMut<T>` for accounts
|
|
24
|
+
without a discriminator; `readU8/U16/U32/U64/U128/readPubkey(offset)` on `instructionData()`; error enums from code 0
|
|
25
|
+
(returned as CUSTOM_ZERO); `require(c, ProgramError.X)` for Solana's built-in errors; `panic(message, location?)`;
|
|
26
|
+
`PANIC_ON_OVERFLOW`, `ERROR_LOG_PREFIX` and `PROGRAM_ERROR_LOG_PREFIX` program constants; `createProgramAddress`;
|
|
27
|
+
`logBase64(prefix, struct)`.
|
|
28
|
+
- Fixed: `isqrt` of a u256 (it generated C that did not compile).
|
|
29
|
+
- New: a function chosen at run time, `const g = k === 1n ? dbl : inc; g(x)` (the condition read once; only the chosen
|
|
30
|
+
function runs), and a list of functions run in turn, `for (const f of [dbl, inc]) …` (unrolled; `continue` and `break`
|
|
31
|
+
work).
|
|
32
|
+
- New: `xs.find(f)!.field` and `xs.find(f)?.field` on lists of structs (located with findIndex, read in place; `!` aborts
|
|
33
|
+
with 5108 when nothing matched, `?.` gives an Option).
|
|
34
|
+
- New: `map` to structs inside a chain when the callback names the struct, `xs.map((o): Scored => ({ … })).filter(…)
|
|
35
|
+
.reduce(…)`: one struct per element, nothing stored.
|
|
36
|
+
- Hints: comparing an integer with a number (`k === 1`) points at `1n`. `.length` on something that is not a list says
|
|
37
|
+
what it is instead of asking for byteLength; the FixedVec argument/account refusal says why (two byte layouts, one IDL
|
|
38
|
+
type).
|
|
39
|
+
- Docs: the README's quick start ends with a first change to make and a short "where next" list (it was one long
|
|
40
|
+
paragraph); the showcase lists Marginfi v2 as complete and links every case study.
|
|
41
|
+
- Editor: the plugin (`typesol/ts-plugin`) adds the same hints under TypeScript's errors in a program's files, once the
|
|
42
|
+
in-process compiler has loaded, so VS Code shows what to write instead too.
|
|
43
|
+
- CLI: `typesol init` names the other starters (`--template vault`, `--template escrow`) after the next steps.
|
|
44
|
+
- CLI: build errors show the path relative to the working directory and the source line with the problem marked.
|
|
45
|
+
`--json` and the compiler API keep their fields (a hint is a line of the message).
|
|
46
|
+
- New: hints for the errors newcomers meet first, under TypeScript's message: a number where a u64 is (`1n`), `Math.max`
|
|
47
|
+
(`min` / `max`), `console.log` (`log`), a missing `typesol` import, `async`, writing an account that is not `Mut<T>`,
|
|
48
|
+
`xs[i]` (`.get` / `.set`). Refused syntax is named in TypeScript's words ("classes are not supported: …") instead of
|
|
49
|
+
the compiler's internal node names, and `require` with a template string says what its error can be.
|
|
50
|
+
- Docs: Marginfi's case study lists part 5 as done (all 124 instructions); troubleshooting points to the hints.
|
|
51
|
+
- Releases: `scripts/release-manifest.ts` builds the program-examples ports of sources up to 0.38.0 (`test/ports/`; a
|
|
52
|
+
0.38.0 tree listed only 18 programs). docs/testing.md and CONTRIBUTING describe the manifest and binary diff as attached
|
|
53
|
+
by hand.
|
|
54
|
+
|
|
9
55
|
## 0.39.0 — 2026-11-06
|
|
10
56
|
|
|
11
57
|
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,21 @@ 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
|
-
mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
|
|
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).
|
|
192
191
|
|
|
193
192
|
## How it works
|
|
194
193
|
|
|
@@ -200,7 +199,7 @@ counter.ts ─▶ tsc typecheck ─▶ subset check ─▶ C + typesol_rt.h ─
|
|
|
200
199
|
1. **Typecheck.** The TypeScript compiler checks your code against [`lib/typesol.d.ts`](lib/typesol.d.ts), which
|
|
201
200
|
declares every TypeSOL type and built-in.
|
|
202
201
|
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.
|
|
202
|
+
with a `file:line:col` diagnostic, and a hint for the usual first mistakes. Nothing is half-supported.
|
|
204
203
|
3. **Lower.** Instruction bodies become C. Account validation, checked arithmetic, Borsh encoding and CPI plumbing
|
|
205
204
|
come from [`runtime/typesol_rt.h`](runtime/typesol_rt.h).
|
|
206
205
|
4. **Build.** The Agave platform-tools `clang` and `ld.lld` produce the `.so` (SBPF v0 by default; v1 and v2 with
|
|
@@ -216,7 +215,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
|
|
|
216
215
|
| **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
216
|
| **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
217
|
| **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`,
|
|
218
|
+
| **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
219
|
| **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
220
|
| **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
|
|
222
221
|
| **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard feeds and verifiable randomness |
|
|
@@ -343,13 +342,17 @@ Details are in [docs/testing.md](docs/testing.md).
|
|
|
343
342
|
[`showcase/`](showcase) holds programs ported from Anchor and checked against the binaries deployed on mainnet (same
|
|
344
343
|
outcomes, account bytes and events; [`showcase/test`](showcase/test)), and the ports of all 46
|
|
345
344
|
[solana-developers/program-examples](showcase/program-examples/README.md).
|
|
345
|
+
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),
|
|
346
|
+
[Raydium CP-Swap](docs/case-study-raydium-cp-swap.md), [Jito MEV](docs/case-study-jito-mev.md),
|
|
347
|
+
[coral-xyz/multisig](docs/case-study-multisig.md), [an Anchor escrow](docs/case-study-escrow.md).
|
|
346
348
|
|
|
347
349
|
| | |
|
|
348
350
|
| --- | --- |
|
|
349
351
|
| [`raydium-cp-swap/`](showcase/mainnet/raydium-cp-swap) | Raydium CP-Swap's trading core: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle |
|
|
350
352
|
| [`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
353
|
| [`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
|
|
354
|
+
| [`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 |
|
|
355
|
+
| [`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
356
|
| [`multisig.ts`](showcase/mainnet/multisig/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
|
|
354
357
|
|
|
355
358
|
## Status
|
package/dist/cli.js
CHANGED
|
@@ -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)
|
|
@@ -552,6 +553,39 @@ const USAGE = `Usage:\n${Object.values(COMMANDS)
|
|
|
552
553
|
function log(s) {
|
|
553
554
|
console.log(s);
|
|
554
555
|
}
|
|
556
|
+
/**
|
|
557
|
+
* Diagnostics for a terminal: the path relative to the working directory, the source line with the problem marked, and
|
|
558
|
+
* the rest of the message (a hint, TypeScript's details) under it. `--json` and CompileError.message keep the plain form.
|
|
559
|
+
*/
|
|
560
|
+
function showDiagnostics(diagnostics, sources) {
|
|
561
|
+
const cache = new Map();
|
|
562
|
+
const linesOf = (file) => {
|
|
563
|
+
if (!cache.has(file)) {
|
|
564
|
+
let text = sources?.get(file);
|
|
565
|
+
if (text === undefined && existsSync(file))
|
|
566
|
+
text = readFileSync(file, "utf8");
|
|
567
|
+
cache.set(file, text?.split(/\r?\n/));
|
|
568
|
+
}
|
|
569
|
+
return cache.get(file);
|
|
570
|
+
};
|
|
571
|
+
return diagnostics
|
|
572
|
+
.map((d) => {
|
|
573
|
+
const rel = path.relative(process.cwd(), d.file);
|
|
574
|
+
const shown = rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel : d.file;
|
|
575
|
+
const [first, ...rest] = d.message.split("\n");
|
|
576
|
+
const out = [`${shown}:${d.line}:${d.column} - error: ${first}`];
|
|
577
|
+
const src = linesOf(d.file)?.[d.line - 1];
|
|
578
|
+
if (src !== undefined) {
|
|
579
|
+
const gutter = String(d.line);
|
|
580
|
+
const width = Math.max(1, Math.min(d.length ?? 1, src.length - (d.column - 1)));
|
|
581
|
+
out.push(` ${gutter} | ${src}`, ` ${" ".repeat(gutter.length)} | ${" ".repeat(Math.max(0, d.column - 1))}${"^".repeat(width)}`);
|
|
582
|
+
}
|
|
583
|
+
for (const r of rest)
|
|
584
|
+
out.push(` ${r}`);
|
|
585
|
+
return out.join("\n");
|
|
586
|
+
})
|
|
587
|
+
.join("\n\n");
|
|
588
|
+
}
|
|
555
589
|
function mustExist(file) {
|
|
556
590
|
if (!existsSync(file))
|
|
557
591
|
throw new UsageError(`${file} does not exist`);
|
|
@@ -645,7 +679,7 @@ try {
|
|
|
645
679
|
}
|
|
646
680
|
catch (e) {
|
|
647
681
|
if (e instanceof CompileError) {
|
|
648
|
-
console.error(e.
|
|
682
|
+
console.error(showDiagnostics(e.diagnostics));
|
|
649
683
|
console.error(`\n${e.diagnostics.length} error(s)`);
|
|
650
684
|
}
|
|
651
685
|
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,7 +260,9 @@ 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;
|
|
263
266
|
if (!d.file || d.start === undefined)
|
|
264
267
|
return { file: entry, line: 1, column: 1, message };
|
|
265
268
|
const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
|
|
@@ -420,8 +423,10 @@ export function analyze(entry, files) {
|
|
|
420
423
|
const tag = ts.getJSDocTags(m).find((t) => t.tagName.text === "code");
|
|
421
424
|
if (tag) {
|
|
422
425
|
const text = typeof tag.comment === "string" ? tag.comment.trim() : "";
|
|
423
|
-
|
|
424
|
-
|
|
426
|
+
// The first code may be below 6000: a native program's `ProgramError::Custom(n)` errors start at 0.
|
|
427
|
+
const least = errors.length ? code : 0;
|
|
428
|
+
if (!/^\d+$/.test(text) || Number(text) < least || Number(text) > 4_294_967_295)
|
|
429
|
+
reporter.fail(m, `@code must be a number from ${least} up (codes only go up; untagged ones start at 6000)`);
|
|
425
430
|
code = Number(text);
|
|
426
431
|
}
|
|
427
432
|
const def = { code, name: m.name.getText(file), msg: m.initializer.text };
|
|
@@ -508,7 +513,7 @@ export function analyze(entry, files) {
|
|
|
508
513
|
}
|
|
509
514
|
}
|
|
510
515
|
else {
|
|
511
|
-
reporter.fail(stmt,
|
|
516
|
+
reporter.fail(stmt, unsupportedSyntax(stmt.kind, "top level"));
|
|
512
517
|
}
|
|
513
518
|
});
|
|
514
519
|
}
|
|
@@ -822,7 +827,7 @@ export function analyze(entry, files) {
|
|
|
822
827
|
reporter.guard(() => checkBorshLayout(sd, structs, dataEnums, reporter));
|
|
823
828
|
continue;
|
|
824
829
|
}
|
|
825
|
-
reporter.error(ix.node.name ?? ix.node, `argument ${a.name}: ${n} holds a FixedVec and is also account data, nested or returned
|
|
830
|
+
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
831
|
}
|
|
827
832
|
}
|
|
828
833
|
// Structs with Options (at any depth) that travel only in instruction data and events (Anchor's BankConfigOpt):
|
|
@@ -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
|
/**
|
|
@@ -10,6 +10,34 @@ import { ExpressionEmitter } from "./expressions.js";
|
|
|
10
10
|
* Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
|
|
11
11
|
*/
|
|
12
12
|
/** List methods taking a callback (or a value) that expand into a loop. */
|
|
13
|
+
/** solana_program's ProgramError variants with no data, in order from InvalidArgument (2) on. */
|
|
14
|
+
const PROGRAM_ERRORS = [
|
|
15
|
+
"InvalidArgument",
|
|
16
|
+
"InvalidInstructionData",
|
|
17
|
+
"InvalidAccountData",
|
|
18
|
+
"AccountDataTooSmall",
|
|
19
|
+
"InsufficientFunds",
|
|
20
|
+
"IncorrectProgramId",
|
|
21
|
+
"MissingRequiredSignature",
|
|
22
|
+
"AccountAlreadyInitialized",
|
|
23
|
+
"UninitializedAccount",
|
|
24
|
+
"NotEnoughAccountKeys",
|
|
25
|
+
"AccountBorrowFailed",
|
|
26
|
+
"MaxSeedLengthExceeded",
|
|
27
|
+
"InvalidSeeds",
|
|
28
|
+
"BorshIoError",
|
|
29
|
+
"AccountNotRentExempt",
|
|
30
|
+
"UnsupportedSysvar",
|
|
31
|
+
"IllegalOwner",
|
|
32
|
+
"MaxAccountsDataAllocationsExceeded",
|
|
33
|
+
"InvalidRealloc",
|
|
34
|
+
"MaxInstructionTraceLengthExceeded",
|
|
35
|
+
"BuiltinProgramsMustConsumeComputeUnits",
|
|
36
|
+
"InvalidAccountOwner",
|
|
37
|
+
"ArithmeticOverflow",
|
|
38
|
+
"Immutable",
|
|
39
|
+
"IncorrectAuthority",
|
|
40
|
+
];
|
|
13
41
|
const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "reduce", "includes", "indexOf"]);
|
|
14
42
|
export class CallEmitter extends ExpressionEmitter {
|
|
15
43
|
call(node, topLevel) {
|
|
@@ -36,12 +64,49 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
36
64
|
if (!this.namesError(args[1])) {
|
|
37
65
|
// A code computed at run time (a helper that returns its error as a value): u32, the program error it names.
|
|
38
66
|
const v = this.expr(args[1], U32);
|
|
67
|
+
if (v.type.kind === "string")
|
|
68
|
+
this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
|
|
39
69
|
const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
|
|
40
70
|
this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
|
|
41
71
|
return undefined;
|
|
42
72
|
}
|
|
73
|
+
// A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
|
|
74
|
+
if (ts.isPropertyAccessExpression(args[1]) && this.exportName(args[1].expression) === "ProgramError") {
|
|
75
|
+
const idx = PROGRAM_ERRORS.indexOf(args[1].name.text);
|
|
76
|
+
if (idx < 0)
|
|
77
|
+
this.fail(args[1].name, `ProgramError has no ${args[1].name.text}`);
|
|
78
|
+
// `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
|
|
79
|
+
const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
|
|
80
|
+
const text = typeof pre === "string" ? `${pre}${args[1].name.text}` : `Error: ${args[1].name.text} (${this.location(node)})`;
|
|
81
|
+
this.line(`if (!${cond.c}) TS_FAIL(((uint64_t)${idx + 2}) << 32, ${cString(text)});`);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
43
84
|
const err = this.errorRef(args[1]);
|
|
44
|
-
|
|
85
|
+
// `const ERROR_LOG_PREFIX = "AMM error: "`: the program's errors log as its native entrypoint logs them.
|
|
86
|
+
const prefix = this.model.constants.get("ERROR_LOG_PREFIX")?.value;
|
|
87
|
+
const text = typeof prefix === "string" ? `${prefix}${err.msg}` : `Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`;
|
|
88
|
+
this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
case "panic": {
|
|
92
|
+
// String literals, or top-level string constants.
|
|
93
|
+
const text = (a) => {
|
|
94
|
+
if (ts.isStringLiteralLike(a))
|
|
95
|
+
return a.text;
|
|
96
|
+
const v = ts.isIdentifier(a) ? this.model.constants.get(a.text)?.value : undefined;
|
|
97
|
+
return typeof v === "string" ? v : undefined;
|
|
98
|
+
};
|
|
99
|
+
if (args.length > 2 || args.some((a) => text(a) === undefined))
|
|
100
|
+
this.fail(node, 'panic() takes an optional message and an optional "file:line:column" location: string literals or string constants');
|
|
101
|
+
const msg = args.length ? text(args[0]) : "explicit panic";
|
|
102
|
+
// The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"): the given one, as a
|
|
103
|
+
// ported program's panic reports it, else this source line.
|
|
104
|
+
const at = args.length > 1 ? text(args[1]) : this.location(node);
|
|
105
|
+
const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(at);
|
|
106
|
+
const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [at, "0", "0"];
|
|
107
|
+
this.line(`sol_log(${cString(msg)});`);
|
|
108
|
+
this.line(`sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`);
|
|
109
|
+
this.line(`__builtin_unreachable();`);
|
|
45
110
|
return undefined;
|
|
46
111
|
}
|
|
47
112
|
case "log": {
|
|
@@ -220,7 +285,9 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
220
285
|
const v = this.expr(args[0]);
|
|
221
286
|
const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : v;
|
|
222
287
|
if (x.type.kind !== "int" || INT_INFO[x.type.name].signed)
|
|
223
|
-
this.fail(args[0], "isqrt needs an unsigned integer (u8 …
|
|
288
|
+
this.fail(args[0], "isqrt needs an unsigned integer (u8 … u256)");
|
|
289
|
+
if (x.type.name === "u256")
|
|
290
|
+
return { c: `ts_isqrt_u256(${x.c})`, type: x.type };
|
|
224
291
|
const wide = INT_INFO[x.type.name].bytes === 16;
|
|
225
292
|
return { c: wide ? `ts_isqrt_u128(${x.c})` : `((${INT_INFO[x.type.name].c})ts_isqrt_u64((uint64_t)(${x.c})))`, type: x.type };
|
|
226
293
|
}
|
|
@@ -513,6 +580,34 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
513
580
|
this.line(`TS_TRY(ts_init_account(${h}, params->program_id, TS_DISC_${s.name}, sizeof(TSS_${s.name})));`);
|
|
514
581
|
return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: true } };
|
|
515
582
|
}
|
|
583
|
+
case "createProgramAddress": {
|
|
584
|
+
// Pubkey::create_program_address(seeds, program): the bump is the last seed; null when the seeds give a point
|
|
585
|
+
// on the curve (Rust's Err(PubkeyError::InvalidSeeds)) or are too many / too long.
|
|
586
|
+
if (args.length !== 2)
|
|
587
|
+
this.fail(node, "createProgramAddress(seeds, program) takes the seeds (bump last) and the program's address");
|
|
588
|
+
const seeds = this.seeds(args[0], 0);
|
|
589
|
+
const program = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
|
|
590
|
+
const t = this.tmp("cpa");
|
|
591
|
+
this.model.options.set("pubkey", PUBKEY);
|
|
592
|
+
this.line(`${optC(PUBKEY)} ${t};`);
|
|
593
|
+
this.line(`${t}.some = ts_create_pda_address(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
|
|
594
|
+
return { c: t, type: { kind: "option", inner: PUBKEY } };
|
|
595
|
+
}
|
|
596
|
+
case "logBase64": {
|
|
597
|
+
// msg!("{prefix}{base64 of the struct's bytes}"): a fixed-layout struct's bytes are its bincode / Borsh form
|
|
598
|
+
// when it holds integers and Pubkeys only (Raydium's ray_log).
|
|
599
|
+
if (args.length !== 2 || !ts.isStringLiteralLike(args[0]))
|
|
600
|
+
this.fail(node, 'logBase64("prefix", value) takes a string literal and a struct value');
|
|
601
|
+
const place = this.structPlace(args[1]);
|
|
602
|
+
if (!place)
|
|
603
|
+
this.fail(args[1], "logBase64 logs a struct value (a local, a literal bound to a const, or account data)");
|
|
604
|
+
const sd = this.model.structs.get(place.struct);
|
|
605
|
+
if (sd.size === undefined || sd.vec || sd.fields.some((f) => !["int", "pubkey", "array"].includes(f.type.kind)))
|
|
606
|
+
this.fail(args[1], `${sd.name} must hold only integers, Pubkeys and fixed arrays of them for its bytes to be its serialized form`);
|
|
607
|
+
const prefix = args[0].text;
|
|
608
|
+
this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
516
611
|
case "findProgramAddress": {
|
|
517
612
|
// Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
|
|
518
613
|
if (args.length !== 2)
|
|
@@ -578,6 +673,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
578
673
|
this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
|
|
579
674
|
case "loadAccount":
|
|
580
675
|
case "loadAccountMut":
|
|
676
|
+
case "loadRaw":
|
|
677
|
+
case "loadRawMut":
|
|
581
678
|
case "loadForeign":
|
|
582
679
|
this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
|
|
583
680
|
case "emit":
|
|
@@ -625,6 +722,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
625
722
|
this.fail(node, `${callee.text} returns a function: bind it (const f = ${callee.text}(…)) or call it right away (${callee.text}(…)(…))`);
|
|
626
723
|
if (local?.closure)
|
|
627
724
|
return this.expandClosure(local.closure, node.arguments, node);
|
|
725
|
+
if (local?.choice)
|
|
726
|
+
return this.callChoice(local.choice, node.arguments, node);
|
|
628
727
|
const name = calleeName(callee, this.model.helperDecls, this.checker) ?? callee.text;
|
|
629
728
|
if (!local && this.model.factories.has(name))
|
|
630
729
|
this.fail(node, `${callee.text} returns a function: bind it (const f = ${callee.text}(…)) or call it right away (${callee.text}(…)(…))`);
|
|
@@ -653,8 +752,29 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
653
752
|
if (ts.isIdentifier(callee.expression)) {
|
|
654
753
|
const l = this.lookup(callee.expression.text);
|
|
655
754
|
if (l?.type.kind === "vecArg") {
|
|
755
|
+
// Bytes (instruction data, a Vec<u8> argument): little-endian reads at a byte offset, bounds-checked (5104).
|
|
756
|
+
const le = {
|
|
757
|
+
readU8: ["uint8_t", 1, U8],
|
|
758
|
+
readU16: ["uint16_t", 2, { kind: "int", name: "u16" }],
|
|
759
|
+
readU32: ["uint32_t", 4, { kind: "int", name: "u32" }],
|
|
760
|
+
readU64: ["uint64_t", 8, U64],
|
|
761
|
+
readU128: ["__uint128_t", 16, { kind: "int", name: "u128" }],
|
|
762
|
+
readPubkey: ["SolPubkey", 32, PUBKEY],
|
|
763
|
+
};
|
|
764
|
+
if (le[method] && l.type.elem.kind === "int" && l.type.elem.name === "u8") {
|
|
765
|
+
if (args.length !== 1)
|
|
766
|
+
this.fail(node, `${method}(offset) takes the byte offset`);
|
|
767
|
+
const [c, size, type] = le[method];
|
|
768
|
+
const off = this.tmp("off");
|
|
769
|
+
this.line(`uint64_t ${off} = ${this.expect(this.expr(args[0], U64), U64, args[0]).c};`);
|
|
770
|
+
this.line(`if (${off} > (uint64_t)${l.c}.len || (uint64_t)${l.c}.len - ${off} < ${size}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: read past the end of the bytes");`);
|
|
771
|
+
const t = this.tmp("rd");
|
|
772
|
+
this.line(`${c} ${t};`);
|
|
773
|
+
this.line(`ts_memcpy(&${t}, ${l.c}.ptr + ${off}, ${size});`);
|
|
774
|
+
return type.kind === "pubkey" ? { c: `(&${t})`, type } : { c: t, type };
|
|
775
|
+
}
|
|
656
776
|
if (method !== "get" || args.length !== 1)
|
|
657
|
-
this.fail(node, "Vec arguments are read-only: use .get(i) and
|
|
777
|
+
this.fail(node, "Vec arguments are read-only: use .get(i), .length, and on bytes readU8/U16/U32/U64/U128/readPubkey(offset)");
|
|
658
778
|
const elem = l.type.elem;
|
|
659
779
|
if (elem.kind === "string") {
|
|
660
780
|
const idx = this.index(args[0], `(uint64_t)${l.c}.len`);
|
|
@@ -1317,6 +1437,47 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1317
1437
|
this.line(l.trim());
|
|
1318
1438
|
return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: false } };
|
|
1319
1439
|
}
|
|
1440
|
+
/**
|
|
1441
|
+
* `loadRaw<T>(acct)` / `loadRawMut<T>(acct)`: a native program's account (no discriminator) as a fixed-layout struct
|
|
1442
|
+
* from byte 0, checked as a `#[repr(C)]` type's load_checked does: this program's (3007), large enough (3003).
|
|
1443
|
+
*/
|
|
1444
|
+
loadRaw(node, mut) {
|
|
1445
|
+
const fn = mut ? "loadRawMut" : "loadRaw";
|
|
1446
|
+
const targ = node.typeArguments?.[0];
|
|
1447
|
+
const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
|
|
1448
|
+
if (!s || s.size === undefined || s.vec)
|
|
1449
|
+
this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account)`);
|
|
1450
|
+
if (s.layout === "borsh")
|
|
1451
|
+
this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
|
|
1452
|
+
if (node.arguments.length !== 1)
|
|
1453
|
+
this.fail(node, `${fn}<T>(account) takes one remaining account or AccountInfo parameter`);
|
|
1454
|
+
let h = this.handle(node.arguments[0]);
|
|
1455
|
+
let param;
|
|
1456
|
+
if (!h) {
|
|
1457
|
+
const acct = this.accountParam(node.arguments[0], "the account");
|
|
1458
|
+
if (acct.kind.kind !== "info")
|
|
1459
|
+
this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
|
|
1460
|
+
if (mut && !isWritable(acct.kind))
|
|
1461
|
+
this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadRawMut`);
|
|
1462
|
+
if (!this.ix)
|
|
1463
|
+
this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
|
|
1464
|
+
h = `a_${acct.name}`;
|
|
1465
|
+
param = this.ix.accounts.indexOf(acct);
|
|
1466
|
+
}
|
|
1467
|
+
this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
|
|
1468
|
+
this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
|
|
1469
|
+
if (mut) {
|
|
1470
|
+
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
1471
|
+
const slot = this.claimSlots.get(node);
|
|
1472
|
+
if (slot)
|
|
1473
|
+
this.line(param === undefined
|
|
1474
|
+
? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));`
|
|
1475
|
+
: `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
|
|
1476
|
+
else
|
|
1477
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
|
|
1478
|
+
}
|
|
1479
|
+
return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut } };
|
|
1480
|
+
}
|
|
1320
1481
|
/** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
|
|
1321
1482
|
loadAccount(node, mut) {
|
|
1322
1483
|
let targ = node.typeArguments?.[0];
|
|
@@ -1705,7 +1866,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1705
1866
|
return true;
|
|
1706
1867
|
if (!ts.isPropertyAccessExpression(node))
|
|
1707
1868
|
return false;
|
|
1708
|
-
if (this.exportName(node.expression) === "AnchorError")
|
|
1869
|
+
if (this.exportName(node.expression) === "AnchorError" || this.exportName(node.expression) === "ProgramError")
|
|
1709
1870
|
return true;
|
|
1710
1871
|
return ts.isIdentifier(node.expression) && this.model.errorEnums.has(node.expression.text);
|
|
1711
1872
|
}
|
|
@@ -17,6 +17,12 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
|
|
|
17
17
|
* when the account was left out / the option is empty. (A method call through `?.` is not supported.)
|
|
18
18
|
*/
|
|
19
19
|
protected optionalChain(node: ts.PropertyAccessExpression): Value;
|
|
20
|
+
/**
|
|
21
|
+
* `xs.find(cb)!.a.b` and `xs.find(cb)?.a` on a list of structs: the element is located with findIndex, then read as
|
|
22
|
+
* `xs.get(i).a.b`. With `!` an element that is not found fails the instruction (5108, as `x!` on an empty Option);
|
|
23
|
+
* with `?.` the field comes back as an Option, empty when nothing matched. Undefined for any other expression.
|
|
24
|
+
*/
|
|
25
|
+
protected foundAccess(node: ts.Expression, hint?: ValueType): Value | undefined;
|
|
20
26
|
protected literal(value: bigint, type: ValueType, node: ts.Node): Value;
|
|
21
27
|
protected expr(node: ts.Expression, hint?: ValueType): Value;
|
|
22
28
|
protected property(node: ts.PropertyAccessExpression): Value;
|