@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
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,126 @@ codes, and says so here.
|
|
|
6
6
|
|
|
7
7
|
## Unreleased
|
|
8
8
|
|
|
9
|
+
## 0.42.0 — 2026-11-09
|
|
10
|
+
|
|
11
|
+
SPL Stake Pool ported in full, the native program behind most liquid staking tokens, from the tag a reproducible build
|
|
12
|
+
proves is the mainnet binary, and checked against that binary on 2,107 transactions and a fuzz over epochs. The
|
|
13
|
+
compiler gained what it needed: Borsh accounts without a discriminator, `BigVec<T>`, typed CPIs on remaining accounts
|
|
14
|
+
(`programAt`, `sysvarAt`, `named`), the Stake program's split, merge and minimum delegation, native account writes,
|
|
15
|
+
the EpochRewards sysvar, local lists and the instruction data as a list; `typesol/testing` gained epochs and staking.
|
|
16
|
+
Every program that uses none of the new features compiles to the same binary as in 0.41.0.
|
|
17
|
+
|
|
18
|
+
- Examples: showcase/mainnet/spl-stake-pool, a port of SPL Stake Pool (the native program at SPoo1Ku8…, all 27
|
|
19
|
+
instructions), from the tag a reproducible build proves is the mainnet binary (program@v2.1.0), checked against that
|
|
20
|
+
binary on 2,107 transactions (the original's own 221 integration tests mapped and run as differential cases, pools of
|
|
21
|
+
up to 20,000 validators) and a random walk over epochs with the same outcomes, log lines and account bytes; 19–80% of
|
|
22
|
+
the original's compute units (the stake CPIs are the same in both), 202,240 bytes against 338,912.
|
|
23
|
+
docs/case-study-spl-stake-pool.md.
|
|
24
|
+
- BigVec loops cost less an entry. A loop over a BigVec (`for … of`, the list methods, a slice) becomes a C function
|
|
25
|
+
of its own, given the variables it uses: inside a large function it shared SBF's registers with everything held
|
|
26
|
+
across it, and clang spilled its pointer and totals every step. `retain` over structs walks the elements with one
|
|
27
|
+
pointer. SPL Stake Pool's UpdateStakePoolBalance sum costs 16 CU an entry (was 31; the original 27) and its cleanup's
|
|
28
|
+
retain 5 (was 11; the original 9), so both fit the default 200,000 units wherever the original does. The heap
|
|
29
|
+
buffers such a loop takes on first use (an event's, an element copied for a helper) stay declared in the function
|
|
30
|
+
it came from, so they are taken once however many times the loop runs; a loop that formats a Pubkey moves too.
|
|
31
|
+
Programs without a BigVec compile to the same C.
|
|
32
|
+
- `panic(null, "src/lib.rs:105:19")` panics at a location without logging a message, for a native port whose panic
|
|
33
|
+
handler writes none; `abort()` is Rust's abort on SBF (the allocator's out-of-memory error), the runtime's `abort`
|
|
34
|
+
syscall: "SBF program panicked", no location.
|
|
35
|
+
- A ternary between accounts, `const source = ephemeral ? rest.get(5n) : reserve`: remaining accounts, locals and
|
|
36
|
+
`RemainingAccount` helper parameters bound to one, and `AccountInfo` parameters; only the chosen side runs, and the
|
|
37
|
+
result goes wherever a remaining account does (typed CPIs, `readData`, `loadRaw`, `loadBorsh`, helpers).
|
|
38
|
+
- Local lists on the stack: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey, isSigner, isWritable }])`,
|
|
39
|
+
`fixedVec([])`, `FixedArray<T, N>` locals, structs and `FixedString<N>` elements (also in `fixedArray<T, N>(fill)`),
|
|
40
|
+
at most 2 KiB each (a compile error naming the size); `fixedArray(…)` written inline feeds a chain, a list method or
|
|
41
|
+
`for … of`.
|
|
42
|
+
- New: `FixedVec.pushAll(items)`, a bulk append (a memcpy: about 0.01 CU a byte for 1000 bytes, against 11 for a loop
|
|
43
|
+
of `push`), 5104 when it does not fit. Declared on `Vec` as well so a Vec still passes for a FixedVec; calling it on
|
|
44
|
+
a Vec is a compile error.
|
|
45
|
+
- The instruction data is a list: `for … of`, the list methods, `data.slice(start, end?)` (a view; 5104 out of range,
|
|
46
|
+
where JS would clamp) and `InstructionBytes` helper parameters.
|
|
47
|
+
- `invokeInstruction` in helpers (with their `RemainingAccounts` parameter), with metas and data from local lists, a
|
|
48
|
+
`FixedArray`, the instruction data or a slice of it: a native port's instruction builder, metas naming accounts by
|
|
49
|
+
key.
|
|
50
|
+
- `NATIVE_ACCOUNT_WRITES` (no change in behaviour, now tested and documented): a second `loadRawMut` of one account at
|
|
51
|
+
the same position is allowed with the flag (2040 without), and `loadRaw` reads what `loadRawMut`, `storeBorsh` or a
|
|
52
|
+
BigVec push wrote, with or without it.
|
|
53
|
+
- New: `named(account, address)`, a Stake CPI's sysvar or stake config argument as solana_program's stake builders
|
|
54
|
+
and `invoke_signed` give it: the instruction names the address, the slot's account is the account info. The runtime
|
|
55
|
+
looks the address up among the CPI's accounts only, so a slot holding another account fails with MissingAccount, as
|
|
56
|
+
the original does, even when the sysvar is elsewhere in the transaction.
|
|
57
|
+
- New: `loadBorsh<T>(acct)` / `storeBorsh(acct, value)`, a native program's Borsh account (no discriminator; SPL Stake
|
|
58
|
+
Pool's `StakePool`) read into a local struct and written back from byte 0, as Rust's `try_from_slice_unchecked` and
|
|
59
|
+
`serialize` do: trailing bytes ignored, the bytes after a shrunk value left as they were, invalid bytes or a value
|
|
60
|
+
that does not fit failing with `ProgramError.BorshIoError`. Without `NATIVE_ACCOUNT_WRITES` the account written must
|
|
61
|
+
be writable (3006) and passed once (2040: not also another declared or remaining account), as the other writes
|
|
62
|
+
check. A straight-line decoder and encoder per struct, no heap
|
|
63
|
+
(a 611-byte `StakePool`: about 280 CU to read, 610 CU to read and write back). Programs that do not use them
|
|
64
|
+
compile to the same C as before.
|
|
65
|
+
- New: `BigVec<T>`, SPL's `big_vec` for native ports (the stake pool's validator list): the last field of a `loadRaw`
|
|
66
|
+
struct, sized by the account; `push`, `retain`, `slice` (`deserialize_mut_slice`), `get` / `set`, `for … of`, the list
|
|
67
|
+
methods and `.capacity`, with big_vec's bytes and errors (AccountDataTooSmall). Every access is bounded by the
|
|
68
|
+
account's room as well as the length (the capacity computed once at the load), so a length written again after the
|
|
69
|
+
load (writeData, another view, storeBorsh) never reaches past the account. Other programs compile to the same C.
|
|
70
|
+
- `typesol/testing`: epochs and staking. `warpToEpoch` / `nextEpoch` move the Clock consistently (epoch, slot, leader
|
|
71
|
+
schedule epoch, timestamps); `StakeCluster` keeps a cluster-like StakeHistory over one or more LiteSVMs, so warmup
|
|
72
|
+
and cooldown are rate-limited as on a cluster (it refuses a history with a gap or an entry for an epoch that has not
|
|
73
|
+
ended, when made and at each warp); `stakeActivation` ports the Stake program's activation math;
|
|
74
|
+
`createVoteAccount`, `createStakeAccount`, `delegateStake`, `readStakeAccount`. Checked to the lamport against the
|
|
75
|
+
Stake program in LiteSVM (docs/test-your-program.md#epochs-and-staking).
|
|
76
|
+
- New: `programAt<P>(account)`: a remaining account (or an `AccountInfo` parameter) checked to be that program (one key
|
|
77
|
+
compare; ProgramError.IncorrectProgramId otherwise) with P's typed methods, for `StakeProgram`, `SystemProgram`,
|
|
78
|
+
`TokenProgram`, `Token2022Program`, `TokenInterface`, `AssociatedTokenProgram` and `MemoProgram`; bind it, call it
|
|
79
|
+
inline or pass it to a helper taking that program. `sysvarAt<StakeHistorySysvar>(account)` likewise.
|
|
80
|
+
- Typed CPIs (System, Token / Token-2022, ATA, Memo, Stake) take remaining accounts and `AccountInfo` parameters for
|
|
81
|
+
any account, as native ports need; declared parameters keep their compile-time checks, remaining accounts are left to
|
|
82
|
+
the runtime and the called program. `returnData` takes a remaining account as the program.
|
|
83
|
+
- Stake program: `split`, `merge`, `getMinimumDelegation()` (fails as solana_program's `get_minimum_delegation`),
|
|
84
|
+
`initialize(…, lockup?)`, and the lockup custodian for `authorize` / `withdraw`. Existing calls compile to the same C.
|
|
85
|
+
- New (language surface: `epochRewards()` and the `EpochRewards` type in lib/typesol.d.ts): the EpochRewards sysvar
|
|
86
|
+
through `sol_get_epoch_rewards_sysvar`, Rust's `EpochRewards::get()`, with no account: every field
|
|
87
|
+
(`active`, `totalRewards`, `distributedRewards`, `totalPoints`, `numPartitions`, `parentBlockhash`,
|
|
88
|
+
`distributionStartingBlockHeight`). Other programs compile to the same C.
|
|
89
|
+
- New: a struct, data-enum or `fixedArray<T, N>(fill)` literal as a helper argument (`applyFee({ denominator: 100n,
|
|
90
|
+
numerator: 3n }, amount)`, nested literals, a ternary with a literal branch, helpers in other files), built as
|
|
91
|
+
`const fee: Fee = { … }` would be; it failed with "expected a Fee". Other programs compile to the same C.
|
|
92
|
+
- Fixed: an `Option<Pubkey>` (or `Option<Hash>`) in a template string or `+` was refused ("only strings, integers,
|
|
93
|
+
booleans and Pubkeys can be joined into text") even after `x !== null`; it joins as the base58, or `null` when
|
|
94
|
+
empty, as JS prints it (as Options of integers and booleans already did). Other programs compile to the same C.
|
|
95
|
+
- New: `export const NATIVE_ACCOUNT_WRITES = true` (opt-in, for native ports): `loadRawMut`, `storeBorsh` and BigVec
|
|
96
|
+
writes skip the up-front writability check (3006) and the one-claim-per-account refusal (2040) and take a plain
|
|
97
|
+
`AccountInfo`; the runtime reports a changed read-only account (`ReadonlyDataModified`), and an account passed twice
|
|
98
|
+
is two views of one buffer, as in a native program. Lamports, `loadAccountMut`, CPIs and `Mut<…>` checks unchanged;
|
|
99
|
+
see docs/language.md#porting-a-native-program for the trade-off. Programs without it compile to the same C.
|
|
100
|
+
|
|
101
|
+
## 0.41.0 — 2026-11-07
|
|
102
|
+
|
|
103
|
+
TypeSOL for AI coding agents, and Raydium CP-Swap ported in full. `typesol init` writes the rules an agent needs
|
|
104
|
+
(AGENTS.md, CLAUDE.md, Cursor's rules) and an MCP server configuration; `typesol mcp` gives agents check, IDL and docs
|
|
105
|
+
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
|
|
106
|
+
instructions, checked against today's mainnet binary with a fuzz test. Programs that do not log a narrowed Option
|
|
107
|
+
compile to the same C as in 0.40.0.
|
|
108
|
+
|
|
109
|
+
- AI agents (docs/ai.md): `typesol init` writes AGENTS.md, CLAUDE.md and Cursor's rules (what TypeSOL refuses that
|
|
110
|
+
TypeScript habits produce, how to check and test) and the MCP server's configuration (.mcp.json, .cursor/mcp.json).
|
|
111
|
+
- New: `typesol mcp`, a Model Context Protocol server on stdio with the tools `check` (diagnostics with hints, from a
|
|
112
|
+
file or source text), `idl`, `docs` (search) and `rules`. No new dependencies.
|
|
113
|
+
- New: `llms.txt` and `llms-full.txt` (the rules, the quick start and the reference in one file), built from the docs by
|
|
114
|
+
`scripts/llms.ts`, shipped in the npm package; the tests fail when they are out of date.
|
|
115
|
+
- CLI: `typesol check --json` gives each error's hint as a `hint` field (it stays the message's last line too).
|
|
116
|
+
- Fixed: `log(x)` of an Option that TypeScript narrowed to its value (after `x === null` was ruled out) generated C that
|
|
117
|
+
did not compile; it logs the value now, and a possibly-null Option is refused with what to do instead.
|
|
118
|
+
- Examples: showcase/mainnet/raydium-cp-swap ports all 21 of Raydium CP-Swap's instructions (was 10): `initialize_v2`,
|
|
119
|
+
`initialize_with_permission`, `collect_creator_fee`, `collect_creator_fee_permissionless`, the permission, creator
|
|
120
|
+
fee share and supported-mint accounts (create and close), and `collect_excess_lamports`. Checked against the binary
|
|
121
|
+
on mainnet today (deployed 2026-10-31; test/programs/raydium_cp_swap.so updated): 136 transactions (was 70) with
|
|
122
|
+
the same outcomes, account bytes and events, Raydium's five signing keys replaced by test keys in both so the admin
|
|
123
|
+
instructions run too, and a fuzz test (random swaps, deposits, withdrawals and fee collections in an SPL Token
|
|
124
|
+
and a Token-2022 pool); an exact-output swap for the whole vault now panics as the original does instead of failing
|
|
125
|
+
with 5100. 42–85% fewer compute units; 214,944 bytes against 749,848. docs/case-study-raydium-cp-swap.md.
|
|
126
|
+
- Docs: docs/stability.md, what 1.0 will promise, what is stable already and what is still experimental, and what to
|
|
127
|
+
settle first; the audit package's line counts and its list of unreviewed changes brought up to 0.40.0.
|
|
128
|
+
|
|
9
129
|
## 0.40.0 — 2026-11-06
|
|
10
130
|
|
|
11
131
|
Raydium AMM v4 ported in full, a native (non-Anchor) program, and checked against its mainnet binary down to its log
|
package/README.md
CHANGED
|
@@ -188,6 +188,7 @@ If the build refuses something, the error points at the line and, for the usual
|
|
|
188
188
|
case study each (Marginfi v2 in full: all 124 instructions, the same on 2,081 transactions; Raydium AMM v4, a native
|
|
189
189
|
program, down to its log lines).
|
|
190
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).
|
|
191
192
|
|
|
192
193
|
## How it works
|
|
193
194
|
|
|
@@ -227,11 +228,12 @@ The full reference, with every type, check and built-in, is in [docs/language.md
|
|
|
227
228
|
|
|
228
229
|
| Command | What it does |
|
|
229
230
|
| --- | --- |
|
|
230
|
-
| `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) |
|
|
231
232
|
| `typesol new <program>` | add another program and its test to a project |
|
|
232
233
|
| `typesol clone <address…>` | copy mainnet accounts and programs for the tests, loaded by `testProgram` |
|
|
233
234
|
| `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
|
|
234
|
-
| `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)) |
|
|
235
237
|
| `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
|
|
236
238
|
| `typesol idl publish` | upload the IDL to the Program Metadata program (canonical when the upgrade authority signs) |
|
|
237
239
|
| `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
|
|
@@ -342,16 +344,17 @@ Details are in [docs/testing.md](docs/testing.md).
|
|
|
342
344
|
[`showcase/`](showcase) holds programs ported from Anchor and checked against the binaries deployed on mainnet (same
|
|
343
345
|
outcomes, account bytes and events; [`showcase/test`](showcase/test)), and the ports of all 46
|
|
344
346
|
[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),
|
|
347
|
+
Case studies: [Marginfi v2](docs/case-study-marginfi.md), [SPL Stake Pool](docs/case-study-spl-stake-pool.md), [Raydium AMM v4](docs/case-study-raydium-amm.md), [Raydium CLMM](docs/case-study-raydium-clmm.md),
|
|
346
348
|
[Raydium CP-Swap](docs/case-study-raydium-cp-swap.md), [Jito MEV](docs/case-study-jito-mev.md),
|
|
347
349
|
[coral-xyz/multisig](docs/case-study-multisig.md), [an Anchor escrow](docs/case-study-escrow.md).
|
|
348
350
|
|
|
349
351
|
| | |
|
|
350
352
|
| --- | --- |
|
|
351
|
-
| [`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 |
|
|
352
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 |
|
|
353
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 |
|
|
354
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
|
+
| [`spl-stake-pool/`](showcase/mainnet/spl-stake-pool) | SPL Stake Pool in full, all 27 instructions, a native program and the one behind most liquid staking tokens: pools of stake across up to 20,000 validators, SOL and stake deposits and withdrawals, rebalancing over epochs, fees and authorities, token metadata |
|
|
355
358
|
| [`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 |
|
|
356
359
|
| [`multisig.ts`](showcase/mainnet/multisig/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
|
|
357
360
|
|
|
@@ -368,7 +371,8 @@ change.
|
|
|
368
371
|
external audit.
|
|
369
372
|
- Report vulnerabilities as described in [SECURITY.md](SECURITY.md).
|
|
370
373
|
|
|
371
|
-
Not supported yet: see the end of [docs/language.md](docs/language.md#not-supported-yet).
|
|
374
|
+
Not supported yet: see the end of [docs/language.md](docs/language.md#not-supported-yet). What 1.0 will promise, what is
|
|
375
|
+
stable already and what is still experimental: [docs/stability.md](docs/stability.md).
|
|
372
376
|
|
|
373
377
|
## Requirements
|
|
374
378
|
|
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",
|
|
@@ -225,6 +225,20 @@ const COMMANDS = {
|
|
|
225
225
|
return 0;
|
|
226
226
|
},
|
|
227
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
|
+
},
|
|
228
242
|
doctor: {
|
|
229
243
|
usage: "typesol doctor [--url <rpc>] [--config <solana cli config>]",
|
|
230
244
|
help: [
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -80,6 +80,9 @@ const TYPE_EXPORTS = new Set([
|
|
|
80
80
|
"FixedArray",
|
|
81
81
|
"FixedString",
|
|
82
82
|
"FixedVec",
|
|
83
|
+
"BigVec",
|
|
84
|
+
"BigVecSlice",
|
|
85
|
+
"InstructionBytes",
|
|
83
86
|
"Program",
|
|
84
87
|
"UncheckedProgram",
|
|
85
88
|
"CpiAccount",
|
|
@@ -122,6 +125,7 @@ const TYPE_EXPORTS = new Set([
|
|
|
122
125
|
"ProgramData",
|
|
123
126
|
"SignerSeeds",
|
|
124
127
|
"SystemAccount",
|
|
128
|
+
"EpochRewards",
|
|
125
129
|
]);
|
|
126
130
|
/** Largest fixed array a struct may declare, and largest FixedString. */
|
|
127
131
|
const MAX_ARRAY_LEN = 1_000_000;
|
|
@@ -263,10 +267,11 @@ function typecheck(entry, files) {
|
|
|
263
267
|
const flat = ts.flattenDiagnosticMessageText(d.messageText, "\n");
|
|
264
268
|
const hint = hintForTypeScript(d, flat, LIB_PATH);
|
|
265
269
|
const message = hint ? `${flat}\nhint: ${hint}` : flat;
|
|
270
|
+
const extra = hint ? { hint } : {};
|
|
266
271
|
if (!d.file || d.start === undefined)
|
|
267
|
-
return { file: entry, line: 1, column: 1, message };
|
|
272
|
+
return { file: entry, line: 1, column: 1, message, ...extra };
|
|
268
273
|
const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
|
|
269
|
-
return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length };
|
|
274
|
+
return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length, ...extra };
|
|
270
275
|
});
|
|
271
276
|
throw new CompileError(diagnostics);
|
|
272
277
|
}
|
|
@@ -920,6 +925,7 @@ export function analyze(entry, files) {
|
|
|
920
925
|
fstrings,
|
|
921
926
|
fixedVecs,
|
|
922
927
|
localVecs: new Map(),
|
|
928
|
+
borshNative: new Set(),
|
|
923
929
|
},
|
|
924
930
|
sourceFile,
|
|
925
931
|
files: programFiles(program, entryPath).map((f) => f.fileName),
|
|
@@ -1181,6 +1187,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1181
1187
|
}
|
|
1182
1188
|
const ext = typesolName(node, imports);
|
|
1183
1189
|
const targs = node.typeArguments ?? [];
|
|
1190
|
+
if (ext === "BigVec")
|
|
1191
|
+
reporter.fail(node, "BigVec<T> is only the last field of a struct (its elements run to the end of the account), not inside another type");
|
|
1184
1192
|
if (ext === "FixedArray") {
|
|
1185
1193
|
if (!targs[0])
|
|
1186
1194
|
reporter.fail(node, "FixedArray<T, N> needs an element type");
|
|
@@ -1218,6 +1226,20 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1218
1226
|
return { kind: "struct", name: node.typeName.text };
|
|
1219
1227
|
reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct");
|
|
1220
1228
|
};
|
|
1229
|
+
// `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
|
|
1230
|
+
// elements are the account's remaining bytes; T is a scalar or a fixed-size struct.
|
|
1231
|
+
const bigVecField = (m, decl) => {
|
|
1232
|
+
const node = m.type;
|
|
1233
|
+
const elemNode = node.typeArguments?.[0];
|
|
1234
|
+
if (!elemNode || node.typeArguments.length !== 1)
|
|
1235
|
+
reporter.fail(node, "BigVec<T> takes one element type: BigVec<ValidatorStakeInfo>");
|
|
1236
|
+
if (decl.members.at(-1) !== m)
|
|
1237
|
+
reporter.fail(m, `BigVec<T> must be the last field of ${decl.name.text}: its elements run to the end of the account (move it after the others)`);
|
|
1238
|
+
const elem = fieldType(elemNode);
|
|
1239
|
+
if (!isScalarField(elem) && elem.kind !== "struct")
|
|
1240
|
+
reporter.fail(elemNode, "BigVec elements are integers, booleans, Pubkeys, unit enums or fixed-size structs");
|
|
1241
|
+
return { kind: "vec", elem, big: true };
|
|
1242
|
+
};
|
|
1221
1243
|
for (const { decl, imports: fileImports } of items) {
|
|
1222
1244
|
scope = scopeFor(fileImports);
|
|
1223
1245
|
imports = fileImports;
|
|
@@ -1236,7 +1258,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1236
1258
|
const problem = cNameProblem(name);
|
|
1237
1259
|
if (problem)
|
|
1238
1260
|
reporter.fail(m.name, problem);
|
|
1239
|
-
const type = fieldType(m.type);
|
|
1261
|
+
const type = typesolName(m.type, imports) === "BigVec" ? bigVecField(m, decl) : fieldType(m.type);
|
|
1240
1262
|
// `/** @bytes */`: an integer the IDL describes as its bytes (Marginfi's WrappedI80F48 { value: [u8; 16] }), or a
|
|
1241
1263
|
// FixedArray of them, each its bytes (Marginfi's HealthCache.prices: [[u8; 8]; 16], f64 bits).
|
|
1242
1264
|
const bytesTag = ts.getJSDocTags(m).find((t) => t.tagName.text === "bytes");
|
|
@@ -1258,6 +1280,11 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1258
1280
|
if (layoutTag && layoutText !== "borsh" && layoutText !== "fixed")
|
|
1259
1281
|
reporter.fail(layoutTag, "@layout is borsh (Anchor's account bytes) or fixed (the default)");
|
|
1260
1282
|
const growable = (f) => f.type.kind === "vec" && f.type.cap === undefined;
|
|
1283
|
+
const big = fields.find((f) => f.type.kind === "vec" && f.type.big);
|
|
1284
|
+
if (big && layoutText === "borsh")
|
|
1285
|
+
reporter.fail(big.node, "a @layout borsh struct cannot hold a BigVec: BigVec is read in place (loadRaw / loadRawMut) from a fixed layout");
|
|
1286
|
+
if (big && fields.some((f) => f !== big && growable(f)))
|
|
1287
|
+
reporter.fail(big.node, `${decl.name.text} has a Vec and a BigVec: only one list may run to the end of the account`);
|
|
1261
1288
|
// In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
|
|
1262
1289
|
// only by the account when it is written back.
|
|
1263
1290
|
if (layoutText === "borsh")
|
|
@@ -1406,6 +1433,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1406
1433
|
visit(s);
|
|
1407
1434
|
if (s.size === undefined)
|
|
1408
1435
|
reporter.fail(at, `${t.name} has a string field and cannot be nested; use FixedString<N>`);
|
|
1436
|
+
if (s.bigVec)
|
|
1437
|
+
reporter.fail(at, `${t.name} ends in a BigVec and cannot be nested: read it with loadRaw / loadRawMut`);
|
|
1409
1438
|
if (s.vec)
|
|
1410
1439
|
reporter.fail(at, `${t.name} has a growable Vec and can only be account data, not nested`);
|
|
1411
1440
|
return s.size;
|
|
@@ -1477,6 +1506,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1477
1506
|
(s.vecs ??= []).push({ name: f.name, elem: f.type.elem, elemSize });
|
|
1478
1507
|
}
|
|
1479
1508
|
s.vec = s.vecs?.[0];
|
|
1509
|
+
if (s.vec && s.fields.some((f) => f.name === s.vec.name && f.type.kind === "vec" && f.type.big))
|
|
1510
|
+
s.bigVec = s.vec;
|
|
1480
1511
|
// The C struct holds the first Vec's length; each further one adds its own when the account is created.
|
|
1481
1512
|
if (s.vecs && s.size !== undefined)
|
|
1482
1513
|
s.size -= 4 * (s.vecs.length - 1);
|
|
@@ -1709,6 +1740,9 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
|
|
|
1709
1740
|
reporter.fail(p.type, "helpers take the list itself: check the Option argument is not null and pass it");
|
|
1710
1741
|
if (type)
|
|
1711
1742
|
return { name: p.name.text, type, node: p };
|
|
1743
|
+
// The instruction data (or a slice of it), read-only: a view like a Vec<u8> argument.
|
|
1744
|
+
if (typesolName(p.type, scope.imports) === "InstructionBytes")
|
|
1745
|
+
return { name: p.name.text, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, node: p };
|
|
1712
1746
|
if (typesolName(p.type, scope.imports) === "SignerSeeds")
|
|
1713
1747
|
return { name: p.name.text, type: { kind: "signerSeeds" }, node: p };
|
|
1714
1748
|
// One of the remaining accounts (remainingAccounts().get(i)), as the instruction holds it: read with readData or
|
|
@@ -2304,6 +2338,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
|
|
|
2304
2338
|
const s = ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) ? structs.get(t.typeName.text) : undefined;
|
|
2305
2339
|
if (s && s.size === undefined)
|
|
2306
2340
|
reporter.fail(t, `${s.name} has a variable-length string field and cannot be account data; use FixedString<N>`);
|
|
2341
|
+
if (s?.bigVec)
|
|
2342
|
+
reporter.fail(t, `${s.name} ends in a BigVec, which is a native program's zero-copy list: take the account as AccountInfo (or a remaining account) and read it with loadRaw<${s.name}> / loadRawMut<${s.name}>`);
|
|
2307
2343
|
if (s)
|
|
2308
2344
|
checkAccountMembers(s, t, reporter);
|
|
2309
2345
|
return s;
|
|
@@ -2456,6 +2492,11 @@ function resolveAccountKind(node, reporter, imports, structs) {
|
|
|
2456
2492
|
reporter.fail(t, "Mut<T> takes a struct, Signer, AccountInfo, TokenAccount or Mint");
|
|
2457
2493
|
}
|
|
2458
2494
|
}
|
|
2495
|
+
const bare = ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) ? structs.get(node.typeName.text) : undefined;
|
|
2496
|
+
if (bare?.bigVec)
|
|
2497
|
+
reporter.fail(node, `${bare.name} ends in a BigVec, so it is account data, not an argument: read it with loadRaw<${bare.name}> / loadRawMut<${bare.name}> from an AccountInfo or a remaining account`);
|
|
2498
|
+
if (typesolName(node, imports) === "BigVec")
|
|
2499
|
+
reporter.fail(node, "BigVec<T> is the last field of a native account's struct (read with loadRaw), not an argument; a list argument is a Vec<T>");
|
|
2459
2500
|
reporter.fail(node, "parameter type must be an integer, boolean, Pubkey, string, or an account type (Signer, Account<T>, Mut<T>, Init<T>, AccountInfo, TokenAccount, Mint, SystemProgram, TokenProgram, Token2022Program, TokenInterface, Program<...>)");
|
|
2460
2501
|
}
|
|
2461
2502
|
export { isScalar };
|
|
@@ -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 FunctionChoice, type EmitOptions } from "./shared.js";
|
|
5
|
+
import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions, type CpiProgram } 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.
|
|
@@ -17,6 +17,17 @@ export declare abstract class EmitterBase {
|
|
|
17
17
|
protected lines: string[];
|
|
18
18
|
/** Declarations placed at the top of the function (buffers reused by every pass through a loop). */
|
|
19
19
|
protected hoisted: string[];
|
|
20
|
+
/**
|
|
21
|
+
* The hoisted declarations of heap buffers taken on first use (`T *name = NULL;`), by line: a loop moved into a
|
|
22
|
+
* function of its own leaves them in its caller and is given a pointer to each (see outlinedLoop), so the buffer is
|
|
23
|
+
* still taken once per function, not once per call of the loop's.
|
|
24
|
+
*/
|
|
25
|
+
protected readonly lazyHoists: Map<string, {
|
|
26
|
+
name: string;
|
|
27
|
+
decl: (name: string) => string;
|
|
28
|
+
}>;
|
|
29
|
+
/** Loops moved into C functions of their own (see outlinedLoop), placed before this function. */
|
|
30
|
+
protected outlinedLoops: string[];
|
|
20
31
|
protected indent: number;
|
|
21
32
|
protected temp: number;
|
|
22
33
|
/** Init accounts whose create() has run (top-level, in order). */
|
|
@@ -81,6 +92,8 @@ export declare abstract class EmitterBase {
|
|
|
81
92
|
/** `file.ts:line` of a node, for messages. */
|
|
82
93
|
protected location(node: ts.Node): string;
|
|
83
94
|
protected tmp(prefix?: string): string;
|
|
95
|
+
/** Declare a heap buffer pointer at the top of the function, NULL until first use (`decl(name)` declares it). */
|
|
96
|
+
protected hoistLazy(name: string, decl: (name: string) => string): void;
|
|
84
97
|
/**
|
|
85
98
|
* JS evaluates operands left to right, but a lowered Value is a C expression read where it is used.
|
|
86
99
|
* When lowering a later operand emitted statements (from line `mark` on, e.g. a pop() or a helper call),
|
|
@@ -100,6 +113,15 @@ export declare abstract class EmitterBase {
|
|
|
100
113
|
protected probe<T>(fn: () => T): T | undefined;
|
|
101
114
|
protected fail(node: ts.Node, message: string): never;
|
|
102
115
|
protected exportName(node: ts.Expression): string | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut, storeBorsh and BigVec writes follow a native program, which
|
|
118
|
+
* writes data in place and leaves writability to the runtime (ReadonlyDataModified when a read-only account's data
|
|
119
|
+
* changed) and lets one account be viewed twice. Without it they check writability (3006) and claim the account
|
|
120
|
+
* once (2040) up front.
|
|
121
|
+
*/
|
|
122
|
+
protected nativeAccountWrites(): boolean;
|
|
123
|
+
/** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
|
|
124
|
+
protected isEpochRewards(node: ts.Expression): boolean;
|
|
103
125
|
/**
|
|
104
126
|
* `acct!.field` on an optional account: the same access without `!` (using the account checks that it was passed,
|
|
105
127
|
* failing with 5115 otherwise). Returns undefined for anything else.
|
|
@@ -123,6 +145,15 @@ export declare abstract class EmitterBase {
|
|
|
123
145
|
protected abstract isRemaining(node: ts.Expression): boolean;
|
|
124
146
|
protected abstract remainingBase(node: ts.Expression): string;
|
|
125
147
|
protected abstract handle(node: ts.Expression): string | undefined;
|
|
148
|
+
protected abstract looksLikeAccountHandle(node: ts.Expression): boolean;
|
|
149
|
+
protected abstract isVecArgView(node: ts.Expression): boolean;
|
|
150
|
+
protected abstract vecArgView(node: ts.Expression): {
|
|
151
|
+
c: string;
|
|
152
|
+
type: ValueType & {
|
|
153
|
+
kind: "vecArg";
|
|
154
|
+
};
|
|
155
|
+
} | undefined;
|
|
156
|
+
protected abstract accountChoice(node: ts.ConditionalExpression): Value;
|
|
126
157
|
protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
|
|
127
158
|
protected abstract isTxIx(node: ts.Expression): boolean;
|
|
128
159
|
protected abstract seeds(node: ts.Expression, extra: number): {
|
|
@@ -135,13 +166,13 @@ export declare abstract class EmitterBase {
|
|
|
135
166
|
protected abstract createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
|
|
136
167
|
protected abstract createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
|
|
137
168
|
protected abstract systemTransfer(node: ts.CallExpression): undefined;
|
|
138
|
-
protected abstract createAccount(node: ts.CallExpression, system:
|
|
169
|
+
protected abstract createAccount(node: ts.CallExpression, system: CpiProgram): undefined;
|
|
139
170
|
protected abstract createPda(node: ts.CallExpression): Value;
|
|
140
|
-
protected abstract allocateOrAssign(node: ts.CallExpression, system:
|
|
141
|
-
protected abstract tokenOp(node: ts.CallExpression, program:
|
|
142
|
-
protected abstract ataOp(node: ts.CallExpression, program:
|
|
143
|
-
protected abstract memoOp(node: ts.CallExpression, program:
|
|
144
|
-
protected abstract stakeOp(node: ts.CallExpression, program:
|
|
171
|
+
protected abstract allocateOrAssign(node: ts.CallExpression, system: CpiProgram, method: "allocate" | "assign"): undefined;
|
|
172
|
+
protected abstract tokenOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
|
|
173
|
+
protected abstract ataOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
|
|
174
|
+
protected abstract memoOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
|
|
175
|
+
protected abstract stakeOp(node: ts.CallExpression, program: CpiProgram, method: string): Value | undefined;
|
|
145
176
|
protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
|
|
146
177
|
protected abstract coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
|
|
147
178
|
protected abstract bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
|
|
@@ -155,6 +186,7 @@ export declare abstract class EmitterBase {
|
|
|
155
186
|
protected abstract expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
|
|
156
187
|
protected abstract callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
|
|
157
188
|
protected abstract listMethod(node: ts.CallExpression, method: string): Value | undefined;
|
|
189
|
+
protected abstract programErrorFail(name: string, node: ts.Node): string;
|
|
158
190
|
protected abstract isPipeline(e: ts.Expression): e is ts.CallExpression;
|
|
159
191
|
protected abstract closureOf(arg: ts.Expression): Closure;
|
|
160
192
|
/** The arguments and accounts code written here can name (what a closure written here keeps). */
|
|
@@ -168,5 +200,6 @@ export declare abstract class EmitterBase {
|
|
|
168
200
|
next?: string;
|
|
169
201
|
alwaysNext?: boolean;
|
|
170
202
|
atNext?: () => void;
|
|
203
|
+
body?: ts.Node;
|
|
171
204
|
}, body: (element: ts.Expression, index: ts.Expression) => void): void;
|
|
172
205
|
}
|
|
@@ -16,6 +16,14 @@ export class EmitterBase {
|
|
|
16
16
|
lines = [];
|
|
17
17
|
/** Declarations placed at the top of the function (buffers reused by every pass through a loop). */
|
|
18
18
|
hoisted = [];
|
|
19
|
+
/**
|
|
20
|
+
* The hoisted declarations of heap buffers taken on first use (`T *name = NULL;`), by line: a loop moved into a
|
|
21
|
+
* function of its own leaves them in its caller and is given a pointer to each (see outlinedLoop), so the buffer is
|
|
22
|
+
* still taken once per function, not once per call of the loop's.
|
|
23
|
+
*/
|
|
24
|
+
lazyHoists = new Map();
|
|
25
|
+
/** Loops moved into C functions of their own (see outlinedLoop), placed before this function. */
|
|
26
|
+
outlinedLoops = [];
|
|
19
27
|
indent = 1;
|
|
20
28
|
temp = 0;
|
|
21
29
|
/** Init accounts whose create() has run (top-level, in order). */
|
|
@@ -218,6 +226,12 @@ export class EmitterBase {
|
|
|
218
226
|
tmp(prefix = "t") {
|
|
219
227
|
return `${prefix}${this.temp++}`;
|
|
220
228
|
}
|
|
229
|
+
/** Declare a heap buffer pointer at the top of the function, NULL until first use (`decl(name)` declares it). */
|
|
230
|
+
hoistLazy(name, decl) {
|
|
231
|
+
const line = ` ${decl(name)} = NULL;`;
|
|
232
|
+
this.lazyHoists.set(line, { name, decl });
|
|
233
|
+
this.hoisted.push(line);
|
|
234
|
+
}
|
|
221
235
|
/**
|
|
222
236
|
* JS evaluates operands left to right, but a lowered Value is a C expression read where it is used.
|
|
223
237
|
* When lowering a later operand emitted statements (from line `mark` on, e.g. a pop() or a helper call),
|
|
@@ -301,6 +315,7 @@ export class EmitterBase {
|
|
|
301
315
|
const saved = {
|
|
302
316
|
lines: this.lines.length,
|
|
303
317
|
hoisted: this.hoisted.length, // a probed helper call may hoist declarations
|
|
318
|
+
outlined: this.outlinedLoops.length,
|
|
304
319
|
temp: this.temp,
|
|
305
320
|
diagnostics: this.reporter.diagnostics.length,
|
|
306
321
|
scopes: this.scopes.length,
|
|
@@ -318,6 +333,7 @@ export class EmitterBase {
|
|
|
318
333
|
finally {
|
|
319
334
|
this.lines.length = saved.lines;
|
|
320
335
|
this.hoisted.length = saved.hoisted;
|
|
336
|
+
this.outlinedLoops.length = saved.outlined;
|
|
321
337
|
this.temp = saved.temp;
|
|
322
338
|
this.reporter.diagnostics.length = saved.diagnostics;
|
|
323
339
|
this.scopes.length = saved.scopes;
|
|
@@ -343,6 +359,23 @@ export class EmitterBase {
|
|
|
343
359
|
exportName(node) {
|
|
344
360
|
return ts.isIdentifier(node) ? this.imports.get(node.text) : undefined;
|
|
345
361
|
}
|
|
362
|
+
/**
|
|
363
|
+
* `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut, storeBorsh and BigVec writes follow a native program, which
|
|
364
|
+
* writes data in place and leaves writability to the runtime (ReadonlyDataModified when a read-only account's data
|
|
365
|
+
* changed) and lets one account be viewed twice. Without it they check writability (3006) and claim the account
|
|
366
|
+
* once (2040) up front.
|
|
367
|
+
*/
|
|
368
|
+
nativeAccountWrites() {
|
|
369
|
+
return this.model.constants.get("NATIVE_ACCOUNT_WRITES")?.value === true;
|
|
370
|
+
}
|
|
371
|
+
/** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
|
|
372
|
+
isEpochRewards(node) {
|
|
373
|
+
if (ts.isParenthesizedExpression(node))
|
|
374
|
+
return this.isEpochRewards(node.expression);
|
|
375
|
+
if (ts.isIdentifier(node))
|
|
376
|
+
return this.lookup(node.text)?.type.kind === "epochRewards";
|
|
377
|
+
return ts.isCallExpression(node) && this.exportName(node.expression) === "epochRewards";
|
|
378
|
+
}
|
|
346
379
|
/**
|
|
347
380
|
* `acct!.field` on an optional account: the same access without `!` (using the account checks that it was passed,
|
|
348
381
|
* failing with 5115 otherwise). Returns undefined for anything else.
|
|
@@ -11,3 +11,10 @@ export declare function borshIdentical(t: FieldType, model: Pick<ProgramModel, "
|
|
|
11
11
|
export declare function borshMinSize(s: StructDef, model: Pick<ProgramModel, "structs">): number;
|
|
12
12
|
/** C for `ts_unpack_<S>` and `ts_pack_<S>` of every `@layout borsh` struct. */
|
|
13
13
|
export declare function emitBorshCodecs(model: ProgramModel): string[];
|
|
14
|
+
/**
|
|
15
|
+
* C for `ts_bdec_<S>` / `ts_benc_<S>` of the structs `loadBorsh` / `storeBorsh` use (model.borshNative): the same
|
|
16
|
+
* straight-line codec, failing with a bare nonzero return (no log) so that the call site fails with BorshIoError.
|
|
17
|
+
*/
|
|
18
|
+
export declare function emitNativeBorshCodecs(model: ProgramModel): string[];
|
|
19
|
+
/** Why `loadBorsh<S>` / `storeBorsh` cannot take struct `s`, or undefined when they can. */
|
|
20
|
+
export declare function borshNativeStructUnsupported(s: StructDef, model: Pick<ProgramModel, "structs" | "dataEnums">): string | undefined;
|