@typesol/cli 0.43.0 → 0.44.1

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/NOTICE +71 -0
  3. package/README.md +25 -11
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +4 -0
  9. package/dist/compiler/emit/alias.d.ts +16 -2
  10. package/dist/compiler/emit/alias.js +70 -6
  11. package/dist/compiler/emit/base.d.ts +3 -1
  12. package/dist/compiler/emit/base.js +20 -3
  13. package/dist/compiler/emit/borsh.js +11 -5
  14. package/dist/compiler/emit/calls.d.ts +13 -0
  15. package/dist/compiler/emit/calls.js +105 -14
  16. package/dist/compiler/emit/cpi-core.d.ts +9 -1
  17. package/dist/compiler/emit/cpi-core.js +51 -10
  18. package/dist/compiler/emit/create.js +22 -11
  19. package/dist/compiler/emit/expressions.js +6 -1
  20. package/dist/compiler/emit/function.js +15 -5
  21. package/dist/compiler/emit/metaplex.js +17 -4
  22. package/dist/compiler/emit/shared.d.ts +17 -0
  23. package/dist/compiler/emit/shared.js +36 -3
  24. package/dist/compiler/emit/statements.js +17 -4
  25. package/dist/compiler/emit/storage.d.ts +2 -0
  26. package/dist/compiler/emit/storage.js +16 -8
  27. package/dist/compiler/emit/token.js +64 -39
  28. package/dist/compiler/index.d.ts +15 -1
  29. package/dist/compiler/index.js +40 -3
  30. package/dist/compiler/toolchain.d.ts +41 -1
  31. package/dist/compiler/toolchain.js +102 -3
  32. package/dist/testing-stake.d.ts +2 -1
  33. package/dist/testing-stake.js +2 -1
  34. package/dist/testing.js +6 -4
  35. package/dist/tools/clientgen.d.ts +15 -0
  36. package/dist/tools/clientgen.js +173 -7
  37. package/dist/tools/cpigen.d.ts +0 -15
  38. package/dist/tools/cpigen.js +19 -8
  39. package/dist/tools/doctor.d.ts +17 -2
  40. package/dist/tools/doctor.js +64 -4
  41. package/dist/tools/portgen.js +43 -18
  42. package/dist/workspace.d.ts +20 -0
  43. package/dist/workspace.js +173 -6
  44. package/docs/ai.md +10 -5
  45. package/docs/architecture.md +1 -1
  46. package/docs/audit.md +103 -18
  47. package/docs/case-study-escrow.md +1 -1
  48. package/docs/case-study-phoenix.md +10 -10
  49. package/docs/case-study-raydium-amm.md +3 -3
  50. package/docs/case-study-spl-stake-pool.md +5 -5
  51. package/docs/cli.md +17 -8
  52. package/docs/client.md +11 -3
  53. package/docs/errors.md +2 -2
  54. package/docs/language.md +16 -9
  55. package/docs/mainnet.md +21 -10
  56. package/docs/migrate-from-anchor.md +2 -1
  57. package/docs/runtime.md +11 -1
  58. package/docs/security-model.md +79 -12
  59. package/docs/stability.md +21 -2
  60. package/docs/testing.md +25 -0
  61. package/docs/troubleshooting.md +12 -0
  62. package/llms-full.txt +216 -63
  63. package/llms.txt +1 -1
  64. package/package.json +3 -1
  65. package/runtime/typesol_rt.h +30 -18
  66. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/llms-full.txt CHANGED
@@ -20,37 +20,51 @@ in `programs/`, tests in `tests/`; `typesol.json` lists the programs.
20
20
 
21
21
  ## Checking your work
22
22
 
23
- - `npx typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a
23
+ - `npx --no-install typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a
24
24
  `hint` that says what to write instead. Fix those first; they are faster than a build.
25
- - `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx typesol build`
25
+ - `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx --no-install typesol build`
26
26
  writes `target/<name>/`: the `.so`, the IDL and a typed client.
27
- - The MCP server (`npx typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,
27
+ - The MCP server (`npx --no-install typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,
28
28
  the IDL and the docs as tools.
29
- - The language reference: `node_modules/typesol/docs/language.md`, or https://typesol.com/llms-full.txt.
29
+ - The language reference: `node_modules/typesol/docs/language.md` (after `npm install`), or https://typesol.com/llms-full.txt.
30
30
 
31
31
  ## Quick start
32
32
 
33
- You need Node.js 22.12 or later and the Agave CLI (`sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)"`).
34
- Run `cargo-build-sbf --version` once; this downloads the platform-tools that TypeSOL compiles with. Rust is not needed.
33
+ You need Node.js 22.12 or later and the Agave CLI with its platform-tools, which hold the clang TypeSOL compiles with.
34
+ Rust is not needed. TypeSOL is tested with **Agave 3.1.10 and platform-tools v1.52** (clang 20.1.7); to install exactly
35
+ those:
36
+
37
+ ```sh
38
+ sh -c "$(curl -sSfL https://release.anza.xyz/v3.1.10/install)"
39
+ cargo-build-sbf --install-only --force-tools-install --tools-version v1.52
40
+ ```
41
+
42
+ Other versions work, but their binaries are not covered by the project's tests: `typesol build` warns once when the
43
+ clang is another one (`--toolchain-strict` or `TYPESOL_TOOLCHAIN=strict` makes that an error), and every build records
44
+ its clang, platform-tools and host in `<name>.build.json`.
35
45
 
36
46
  ```sh
37
47
  npx @typesol/cli init my-app --name counter # typesol.json, programs/counter.ts, tests/counter.test.ts, tsconfig
38
48
  cd my-app && npm install
39
49
  npm test # builds the program and runs it in LiteSVM, an in-process Solana runtime
40
- npx typesol build # target/counter/{counter.so, counter.json (IDL), counter.client.ts, counter.build.json}
50
+ npx --no-install typesol build # target/counter/{counter.so, counter.json (IDL), counter.client.ts, counter.build.json}
41
51
  ```
42
52
 
43
- `npx typesol doctor` checks all of this (Node.js, platform-tools, Solana CLI, keypair, RPC) and prints the command
44
- that fixes anything missing. To deploy, on devnet:
53
+ `npx --no-install typesol doctor` checks all of this (Node.js, platform-tools and whether they are the tested ones, Solana CLI, keypair, RPC) and prints the command
54
+ that fixes anything missing. Inside a project, `npx --no-install typesol …` (or `npm run build`, `npm run deploy`) runs the
55
+ project's own copy; outside one, use `npx @typesol/cli …`. Plain `npx typesol` is not TypeSOL: `typesol` is not the npm
56
+ package's name, so where the project's copy is not installed npx would fetch whatever package has that name.
57
+
58
+ To deploy, on devnet:
45
59
 
46
60
  ```sh
47
61
  solana-keygen new # once, if you have no keypair (~/.config/solana/id.json)
48
62
  solana airdrop 2 --url devnet # test SOL for the rent (rate-limited: https://faucet.solana.com also works)
49
- npx typesol deploy --url devnet
63
+ npx --no-install typesol deploy --url devnet
50
64
  ```
51
65
 
52
66
  or on a local validator: `solana-test-validator` in another terminal, `solana airdrop 5 --url localhost`, then
53
- `npx typesol deploy --url localhost`. `deploy` checks the RPC and the payer's balance before sending anything.
67
+ `npx --no-install typesol deploy --url localhost`. `deploy` checks the RPC and the payer's balance before sending anything.
54
68
 
55
69
  `--template vault` or `--template escrow` starts from a SOL vault or an SPL token escrow instead of the counter, each
56
70
  with a passing LiteSVM test.
@@ -92,7 +106,7 @@ The full reference. For a tour, start with the [README](../README.md).
92
106
  | --- | --- |
93
107
  | Instruction | an exported function returning `void`, one integer / boolean / `Pubkey`, a `string` (a Borsh String), or a fixed-size struct (sent as return data, at most 1024 bytes; `returns` in the IDL, and the generated client decodes it) |
94
108
  | Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
95
- | Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
109
+ | Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits; the amount, also in `<<=` / `>>=`, may be any integer type). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit), `min` / `max`, `switch` and as a list index (5104 past u64); a shift amount or an exponent is a u128 or smaller (compile error); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
96
110
  | Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
97
111
  | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
98
112
  | Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+ (`/** @code 6200 */` before a member jumps to that code, Anchor's `Name = 200`; `Name = ""` has no message in the IDL); `require(cond, "message")` makes an error of its own (`RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL); `require(cond, AnchorError.RequireKeysEqViolated)` fails with one of Anchor's own codes (2502 here; any anchor-lang `ErrorCode` can be raised this way); `require(cond, code)` with a `u32` value fails with that code as computed at run time (a helper returning its error: `require(r.err === 0n, r.err)`). See [errors.md](errors.md) |
@@ -110,7 +124,7 @@ The full reference. For a tour, start with the [README](../README.md).
110
124
  | Events | `emit<Deposited>({ owner: owner.key, amount })` — Anchor-format `Program data:` logs, listed under `events` in the IDL; event structs may hold `string`, `Option`, `FixedVec<T, N>` (its fixed layout, as in account data), `Vec<T>` (Borsh: from a Vec argument or a list in account data) and `Option<Vec<T>>`; a nested struct given as a literal is Borsh too |
111
125
  | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
112
126
  | Options | `best: Option<u64>` (or `u64 \| null`) — `null`, `=== null`, TypeScript narrowing; `===` between options or with a value follows JS (null equals null, empty never equals a value); empty use aborts (5108); `acct?.field` on an optional account and `x.home?.field` on an `Option<struct>` give an Option (empty when the account was left out / the option is empty), `a ?? b` takes b only when a is empty (b runs only then; the result is an Option when b can be null), `x!` is the value or aborts with 5108; `${opt}` prints the value or `null`. Borsh `option` in arguments/events, fixed `{ is_some, value }` in account data |
113
- | Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
127
+ | Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it, also when it was made through another parameter that may be the same account: a `Dup<…>` pair, a read-only and a writable account of one type, a struct loaded with `loadAccount` / `loadAccountMut`). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
114
128
  | Anchor's account bytes | `/** @layout borsh */` on an account struct stores it as Anchor does (Borsh: a `FixedString<N>` is a String, a `FixedVec<T, N>` or `Vec<T>` a Vec, an `Option` one byte when empty, and the fields after them move), so a TypeSOL program can take over accounts an Anchor program wrote and the IDL lists Anchor's own types. The instruction unpacks it into the usual fixed layout when it starts (bad bytes fail with 3003) and packs it back when it returns (3004 when the account is too small for the new value), so everything else works on it unchanged. A `Vec<T>` field (any position; integers, booleans, Pubkeys, unit enums or fixed-size structs) is Anchor's own: held on the heap while the instruction runs, growing as Rust's Vec does, bounded only by the account when it is written back (3004); its elements move when it grows, so a reference into one cannot outlive a `push` or an assignment. `Init` of such a struct takes its space, `create(payer, seeds, space)`. Programs invoked from the body (CPIs) see the account's bytes as they were when the instruction started. Costs more compute than the fixed layout (the whole account is read and written each time; see the benchmarks); nested structs and list elements must be fixed-size (FixedString elements allowed). The same struct is Borsh as a whole instruction argument (checked like Borsh deserialization, UTF-8 included), as return data and as an event; as those (not as account data) it may also hold `string` fields and data enums carrying strings, Anchor's `String` and enums in argument structs (account data takes data enums without strings); not inside list or enum arguments or `loadAccount`, and a struct holding a `Vec<T>` is account data or a whole argument, not return data or an event |
115
129
  | A native program's Borsh accounts | `const pool = loadBorsh<StakePool>(acct)` / `storeBorsh(acct, pool)`: Borsh from byte 0 with no discriminator and no owner check, read into a local struct and written back, as Rust's `try_from_slice_unchecked` and `serialize` do (trailing bytes ignored when reading, left as they were when writing; invalid bytes or an account too small fail with `ProgramError.BorshIoError`). Any struct of integers, booleans, Pubkeys, enums, FixedArrays, FixedStrings, FixedVecs, Options, data enums with fixed-size payloads and nested structs of those; see [Porting a native program](#porting-a-native-program) |
116
130
  | Zero-copy types as Anchor's IDL describes them | `/** @repr c */` (`@repr c packed`, `@repr c align 8`, `@repr rust` on an enum) and `/** @serialization bytemuck */` on a struct or enum put the IDL's `repr` and `serialization` there, as Anchor's `#[account(zero_copy)]` / `#[repr(C)]` types have them. TypeSOL stores fields back to back, so an unpacked `@repr c` struct must have its fields where C puts them: a field off its alignment, or a size that is not a multiple of the struct's, is a compile error naming the padding to add (Anchor zero-copy types spell their padding out as `_pad` fields, so a port matches). A 16-byte integer's alignment differs between targets: hold it as below or mark the struct packed |
@@ -135,17 +149,17 @@ The full reference. For a tour, start with the [README](../README.md).
135
149
  | Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58; an `Option` of an integer, boolean, Pubkey or Hash as its value, or `null` when empty, as JS prints it: after `x !== null` that is the value) — built on the 32 KiB heap (5110 when full): a template is joined in one allocation, text known at compile time (literals, string and Pubkey constants) is folded in, and `s += …` grows the newest heap string in place |
136
150
  | `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
137
151
  | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash` (a PDA seed too: its 32 bytes, as Marginfi seeds an order with the hash of its bank keys); `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump, or both from one search with `const [address, bump] = findProgramAddressWithBump(seeds, program)` (Rust's `let (address, bump) = …`; each separate search costs about 450 CU per bump tried); `programId()` → this program's address; `a.compare(b)` orders Pubkeys and Hashes as Rust orders their 32 bytes (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
138
- | Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted) (mainnet program unless `SwitchboardFeed<"devnet">`) |
152
+ | Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted; staleness counts slots from the feed's `result.slot`; the 18-decimal result is scaled to `decimals` rounding toward zero) (mainnet program unless `SwitchboardFeed<"devnet">`). Neither reader checks the price's sign or zero, the confidence (Pyth's `conf`, Switchboard's spread of samples), or a publish time or result slot in the future (it counts as fresh): check what your program relies on |
139
153
  | Randomness | A chain has no secret randomness of its own: slot hashes and timestamps are known to, or chosen by, the block producer. `SwitchboardRandomness` (Switchboard On-Demand's RandomnessAccountData; owner, discriminator and size checked) gives verifiable randomness by commit and reveal: commit while `r.seedSlot === currentSlot() - 1n` and store `r.key` and `r.seedSlot`; settle in a later transaction after checking both, with `r.value()` (32 bytes) or `r.valueU64()`, which fail (5111) unless the value was revealed in this slot. See test/fixtures/coinflip.ts |
140
154
  | Multiple files | `import { Side, min } from "./math"` — structs, enums, constants and helpers can live in other files; only the entry file's exported functions are instructions; names are program-wide, so imports from TypeSOL files cannot be renamed; error codes number imported files first |
141
155
  | Loops | `for (let i = 0n; i < n; i++)` (or two counters, `for (let i = 0n, j = n; i < j; i++, j--)`: several declarations, and comma-separated updates run in order after each pass, `continue` included), `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
142
- | Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
156
+ | Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place. Pubkey, Option, string and u256 parameters are passed by pointer too (the SBF target passes a C struct as a pointer to the caller's object and does not copy it); a helper that can write (it takes accounts, remaining accounts or `Inout<T>` places) gets a copy taken at the call, unless the argument is a local, a temporary, an instruction argument, a constant, an account's key, the program id or a parameter of the calling helper, which nothing it is given reaches; a helper that writes nothing reads the caller's value in place. Text a string argument views in account data or in an `Inout<T>` place is copied for such a helper too; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
143
157
  | `Inout<T>` parameters | `function addEvent(rec: Inout<Recorder>, e: Event): void { rec.count += 1n; … }` is Rust's `rec: &mut Recorder`: the helper gets the caller's place itself (a pointer, no copy: about the compute units of the same code written inline) and the caller sees its writes after the call, as JS shares an object passed to a function. `T` is a fixed-size struct, a `FixedArray<T, N>` or a `FixedVec<T, N>` (its `push`, `pop` and `clear` included). The argument is a writable place: a local struct or list, a `loadBorsh` local, a field path of a local, of a `loadRawMut` view or of a `Mut<T>` account, a list element (`book.levels.get(i)`, a narrowed Option's value), another `Inout` parameter (passed on), or a literal (a fresh value nobody else sees); a read-only one (a field of an `Account<T>`, a `loadRaw` view, an instruction argument, a read-only parameter) is a compile error naming what to change. At each call, so that the helper's parameter is the only way to the place while it runs: no other argument may share storage with an Inout one (one place inside the other; two elements of one list, whatever their indexes, a BigVec slice's elements included; an account and a place inside it; a read-only struct argument inside it: pass a copy); an element of a `Vec` or `BigVec` is refused when the call may resize or filter that list (the helper takes writable or remaining accounts), since its elements would move; and a reference into the place (`const e = p.items.get(0n)`) that is read after the call is refused, since the helper may replace what it points at (copy the fields first, or read them through the place). Places that differ in the source but may be one account at run time (two `Dup<…>` accounts, a writable and a read-only account, two native views under `NATIVE_ACCOUNT_WRITES`: `loadRawMut`, `loadRawMutAt`, `rawArrayMutAt` elements, `rbTreeMutAt` nodes, a helper's own account parameters) are compared before the call: 2040 when they overlap. The comparison covers an Inout argument against every other argument passed in place (another Inout one, a read-only struct, array or list, an account), so a read-only argument cannot change under the helper while it writes; one copied for the call (a helper that takes accounts gets a copy of account data) shares nothing and is not compared. One pair is left to run time: a place in a `loadRawMut` view passed with the `RemainingAccount` it was loaded from (without `NATIVE_ACCOUNT_WRITES` a second `loadRawMut` of it in the helper fails, 2040; with the flag the helper can load and write the same bytes, the flag's trade-off). Integers, Pubkeys, strings and Options are values, which JS copies into a function too: return the new value (`x = f(x)`) or keep it in a struct and take `Inout<ThatStruct>`. `Vec<T>`, `BigVec<T>`, accounts and data enums are refused with what to write instead, and so is `Inout<T>` anywhere but a helper's parameter. Closures (and helpers expanded because they were given one) take `Inout<T>` the same way; their struct parameters were references already |
144
158
  | Arrow functions and closures | `const fee = (x: u64): u64 => x / 100n` (or `const f = function (…) {…}`) at the top level or inside a function. One that reads or writes the enclosing function's variables (a closure: `let total = 0n; const add = (v: u64): void => { total += v; }`) is expanded where it is called: its names mean what they meant where it was declared, struct parameters are references, `return` leaves the closure; it cannot call itself. One that captures nothing becomes a helper. Parameter types may be left out on closures (taken from the arguments). Functions are values where they can be expanded: `const h = g` names the same function, and a function that returns one (`function adder(n: u64): (x: u64) => u64 { return (x) => x + n; }`) makes a closure where it is called (`const add5 = adder(5n)`, or `adder(5n)(x)`). A function can be chosen at run time between named ones, `const g = k === 1n ? dbl : inc` (the condition is read once, there; a call runs only the chosen one), and a list of named functions can be run in turn, `for (const f of [dbl, inc]) total += f(x)` (unrolled; `continue` and `break` work) |
145
159
  | Functions as arguments | a helper may take a function parameter (`function applyTwice(f: (x: u64) => u64, v: u64): u64`): it is compiled once per named function passed (a helper or a local function that captures nothing). An arrow written at the call works too (`applyTwice((x) => x * 3n, v)`: its types come from the parameter) when it reads none of the function's variables. Given a closure (one that reads them), the helper is expanded where it is called instead, like a closure, so it runs where the closure can (its type parameters bound from the call, its accounts the caller's) |
146
160
  | List callbacks | on a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument: `forEach`, `some`, `every`, `find` (an Option of the element; scalar elements; on struct elements read a field with `xs.find(f)!.qty`, which aborts with 5108 when nothing matched, or `xs.find(f)?.qty`, an Option), `findIndex` (i64, -1 when absent), `reduce(fn, initial)`, `includes(value)`, `indexOf(value)` (i64), `map` and `filter`. The arrow written at the call is expanded into a loop (elements as `list.get(i)` gives them, structs by reference) and may read and write the function's variables. A `map` / `filter` chain used right away (`xs.filter(f).map(g).reduce(h, 0n)`, `.length`, `for … of`) is one loop that stores nothing; callbacks after a filter get the index among the elements it let through. Stored (`const ys = xs.filter(f)`), it is a FixedVec on the stack as big as the list it starts from; from a `Vec`, give the size: `const ys: FixedVec<u64, 16> = …` (at most 2 KiB; one element more aborts with 5104). `map` gives integers, booleans, Pubkeys or enums; stored with a `FixedVec<Struct, N>` or `FixedVec<FixedString<N>, M>` annotation it gives structs (`(o) => ({ qty: o.qty })`) or text, and inside a chain it gives structs when the callback names its struct, `xs.map((o): Scored => ({ … })).filter(…).reduce(…)` (one struct per element, nothing stored) |
147
161
  | Generic helpers | `function max<T extends bigint>(a: T, b: T): T` — compiled once per set of types it is called with (`max(a, b)` with u64 arguments, or `max<u128>(x, 1n)` when only literals tell); a type parameter stands for an integer, boolean, Pubkey, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: `return (a + b) as T` (`as` names a type the value already has; it never converts) |
148
- | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) |
162
+ | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list callback writing it) |
149
163
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
150
164
  | Sysvars | `now()`, `currentSlot()`, `currentEpoch()`, `epochStartTimestamp()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()`; `epochRewards()` (EpochRewards through its syscall, Rust's `EpochRewards::get()`, no account: a read-only copy with `distributionStartingBlockHeight`, `numPartitions`, `parentBlockhash` (Hash), `totalPoints` (u128), `totalRewards`, `distributedRewards`, `active`; `const er = epochRewards()` or `epochRewards().active` inline, not a helper parameter); `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
151
165
  | Account size | `realloc(account, newSize, payer)` on a `Mut<Struct>` — growing charges the payer the extra rent (at most 10 KiB per instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a growable `Vec` (its push / pop / clear size the account). `resizeAccount(account, newSize)` on a `Mut<AccountInfo>` of this program is Rust's `AccountInfo::resize`: the length only, new bytes zeroed, no rent moved (fund it first: `rentExempt(newSize)`), at most 10 KiB of growth (3016) |
@@ -181,7 +195,7 @@ The full reference. For a tour, start with the [README](../README.md).
181
195
  | `Migrate<From, To>` | Anchor 1.0's `Migration`: an existing `From` account (owner, discriminator, size) rewritten as `To` by `acct.migrate(payer, value)`, a top-level statement the instruction must reach. `acct.from` (read-only) before it, `acct.to` after; the value is built in full before the rewrite, so it may read `acct.from`. Resized to `To` (the payer tops up rent when it grows, at most 10 KiB; shrinking keeps the lamports; growing needs `SystemProgram`). Fixed-layout structs without growable Vecs; no constraints yet; the account cannot be passed to a helper (use `acct.to` fields in the instruction). An account already migrated fails with 3002. Keep the old struct under a new name with its discriminator: `/** @discriminator account:Counter */ interface CounterV1 { … }` |
182
196
  | `Zeroed<T>` | accounts (up to 10 MiB) the client allocated with System `CreateAccount`, Anchor's `zero`: discriminator still zero (2013, checked first as under Anchor), owned by this program, big enough, rent-exempt — then initialized. A `@layout borsh` struct starts empty and is written as Borsh when the instruction returns |
183
197
  | `Signed<A>` | the account must sign the transaction (Anchor's `signer` constraint, 2002), e.g. `Signed<Zeroed<Multisig>>` for an account the client creates with a fresh keypair; the IDL marks it a signer |
184
- | `Init<Mint>`, `InitIfNeeded<Mint>` | Anchor `init` / `init_if_needed` with `mint::decimals` / `mint::authority` / `mint::freeze_authority`: `const bump = mint.create(payer, ["mint", payer.key], 6n, authority, freezeAuthority \| null)` creates the mint at that PDA of this program, or with `null` seeds as a new keypair account that signs (3010 if it did not), under the instruction's token program (its only token program parameter, or one passed as the last argument of `create` / `createIfNeeded`; plus `SystemProgram`). Token-2022 extensions (Anchor's `extensions::…`) go after the freeze authority: `mint.create(payer, null, 6n, authority, null, { metadataPointer: { authority, metadataAddress: mint.key }, transferHook: { authority, programId }, closeAuthority, permanentDelegate, nonTransferable: true, defaultAccountState: true, interestBearing: { rateAuthority, rate }, transferFee: { configAuthority, withdrawAuthority, basisPoints, maximumFee }, groupPointer, groupMemberPointer })` sizes the mint for them and initializes each before InitializeMint2. With `createIfNeeded` an existing mint must carry groupPointer / groupMemberPointer / metadataPointer / closeAuthority / permanentDelegate / transferHook with those keys (Anchor's 2024–2039); extensions not listed are not looked at, so an existing mint may carry others (a permanent delegate, say). `createIfNeeded(…)` returns whether it created it; an existing one must be that PDA and have those decimals and authorities (2018 / 2016 / 2017) |
198
+ | `Init<Mint>`, `InitIfNeeded<Mint>` | Anchor `init` / `init_if_needed` with `mint::decimals` / `mint::authority` / `mint::freeze_authority`: `const bump = mint.create(payer, ["mint", payer.key], 6n, authority, freezeAuthority \| null)` creates the mint at that PDA of this program, or with `null` seeds as a new keypair account that signs (3010 if it did not), under the instruction's token program (its only token program parameter, or one passed as the last argument of `create` / `createIfNeeded`; plus `SystemProgram`). Token-2022 extensions (Anchor's `extensions::…`) go after the freeze authority: `mint.create(payer, null, 6n, authority, null, { metadataPointer: { authority, metadataAddress: mint.key }, transferHook: { authority, programId }, closeAuthority, permanentDelegate, nonTransferable: true, defaultAccountState: true, interestBearing: { rateAuthority, rate }, transferFee: { configAuthority, withdrawAuthority, basisPoints, maximumFee }, groupPointer, groupMemberPointer })` sizes the mint for them (as Token-2022 does: extensions adding up to a Multisig's 355 bytes give a 357-byte mint) and initializes each before InitializeMint2; a `null` authority is sent as Token-2022's empty COption. With `createIfNeeded` an existing mint must carry groupPointer / groupMemberPointer / metadataPointer / closeAuthority / permanentDelegate / transferHook with those keys (Anchor's 2024–2039); extensions not listed are not looked at, so an existing mint may carry others (a permanent delegate, say). `createIfNeeded(…)` returns whether it created it; an existing one must be that PDA and have those decimals and authorities (2018 / 2016 / 2017) |
185
199
  | `Init<TokenAccount>`, `InitIfNeeded<TokenAccount>` (no `Ata<…>`) | Anchor `init` / `init_if_needed` with `token::mint` / `token::authority`: `vault.create(payer, ["vault", mint.key], mint, authority)` (the authority may be `vault.key` itself) creates a token account at that PDA (or a keypair account with `null`), sized for the mint's extensions under Token-2022. `createIfNeeded` checks an existing one has that mint and owner (2014 / 2015), not its delegate or close authority (as Anchor) |
186
200
  | `TokenAccount` / `Mut<TokenAccount>` | owned by SPL Token or Token-2022 (extensions allowed, multisig accounts refused), initialized (an account never created: 3012, as Anchor; a `Mint` likewise); `mint`, `owner`, `amount`, `delegate`, `delegatedAmount`, `isFrozen`, `isNative`, `closeAuthority`, `tokenProgram` |
187
201
  | `Mint` / `Mut<Mint>` | owned by SPL Token or Token-2022, initialized; `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
@@ -204,7 +218,9 @@ Two writable parameters can never be the same account: aliasing is refused with
204
218
  account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
205
219
  (Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed
206
220
  or `@layout borsh`; a close destination may be one, the rent reaching it through either): a write through either is
207
- seen through the other, so read what you need before writing. A remaining account
221
+ seen through the other, so read what you need before writing. A reference into one of them (`const e = a.entries.get(i)`)
222
+ cannot be used after a push, pop or clear through the other moved that data, as with one name (compile error); copy
223
+ the fields first. A remaining account
208
224
  can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
209
225
  with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
210
226
  `AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
@@ -226,7 +242,9 @@ of a position, as Raydium CLMM's tick arrays).
226
242
  come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
227
243
  `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
228
244
  `initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`; and the Token Group interface: `initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize)` (a collection mint with a GroupPointer to itself; fund the rent for the group, which Token-2022 adds to the account), `initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority)`, `updateGroupMaxSize(group, authority, maxSize)`, `updateGroupAuthority(group, authority, next | null)`. Each takes optional signerSeeds
229
- - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
245
+ - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts (the destination
246
+ is another writable account; the account is not used after it in the function, except its `key`: compile errors, or
247
+ 2040 at run time in a helper given one account twice)
230
248
  - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
231
249
  stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
232
250
  among up to 256 addresses for the same seeds
@@ -271,7 +289,10 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
271
289
  lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
272
290
  - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
273
291
  wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
274
- signer([…, bump])`.
292
+ signer([…, bump])`. A named list, and one given to a helper, holds its seeds as they were when it was written (JS
293
+ evaluates the array then): a field or local changed afterwards does not change what it signs for. A list written in
294
+ a call (`transfer(…, signer([…]))`, `create(payer, [...], space)`) holds them as they were when the list was read,
295
+ even when a later argument changes a seed.
275
296
  - `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
276
297
  - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
277
298
  A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
@@ -576,7 +597,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
576
597
  | 2016 / 2017 / 2018 | mint authority / freeze authority / decimals mismatch (2018: an existing mint `createIfNeeded` found) |
577
598
  | 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
578
599
  | 2024–2039 | an existing mint `createIfNeeded` found lacks a Token-2022 extension it was given, or holds other keys in it: group pointer 2024–2026, group member pointer 2027–2029, metadata pointer 2030–2032, close authority 2033–2034, permanent delegate 2035–2036, transfer hook 2037–2039 (the first code of each: the extension is missing; the next: the authority / address differs) (ConstraintMint…Extension…) |
579
- | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
600
+ | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount); also `close(a, b)` in a helper given one account for both |
580
601
  | 0 (from the System Program) | an `Init` / `create` on an address already in use (AccountAlreadyInUse): the System Program refuses it, as under Anchor's `init` |
581
602
  | 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
582
603
  | 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
@@ -590,7 +611,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
590
611
  | 3010 | account must sign (AccountNotSigner; also a new keypair account a `create(payer, null, …)` makes) |
591
612
  | 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
592
613
  | 3012 | account not initialized: empty system account where a program account, a token account or a mint was expected (AccountNotInitialized; not for zero-copy accounts, which Anchor's AccountLoader reports as 3007) |
593
- | 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
614
+ | 3016 | account would grow more than 10 KiB in one instruction (counted from its length when the instruction started), or grow without a payer (AccountReallocExceedsLimit) |
594
615
  | 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
595
616
  | 4102 | cast overflow (InvalidNumericConversion) |
596
617
  | 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
@@ -779,24 +800,33 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
779
800
 
780
801
  | Command | What it does |
781
802
  | --- | --- |
782
- | `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin), `.vscode/settings.json` (the workspace TypeScript, so the plugin loads) and `.gitignore`. `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
803
+ | `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin), `.vscode/settings.json` (the workspace TypeScript, so the plugin loads), `.gitignore`, the rules for AI coding agents (`AGENTS.md`, `CLAUDE.md` importing it, `.cursor/rules/typesol.mdc`) and the MCP server configuration (`.mcp.json`, `.cursor/mcp.json`; see [ai.md](ai.md)). `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
783
804
  | `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name. |
784
- | `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools, the Solana CLI, its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
785
- | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. |
786
- | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. A project program's `.ts` builds as that program. |
787
- | `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
805
+ | `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools (and a `toolchain` row: the tested ones, or untested with both versions), the Solana CLI, its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
806
+ | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--toolchain-strict] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. |
807
+ | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
808
+ | `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`, always (a missing file or unreadable `--files` input is a diagnostic too, exit 1 or 2); `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
788
809
  | `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
789
810
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
790
- | `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …]` | Build, then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. Before sending anything it checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
791
- | `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`). |
811
+ | `typesol mcp` | Serve the Model Context Protocol on stdio for AI coding agents: tools to check a program (errors with hints), read its IDL, search the docs and read the rules a TypeSOL program follows. The `.mcp.json` / `.cursor/mcp.json` that `init` writes start it as `npx --no-install typesol mcp` (the project's own copy); see [ai.md](ai.md). |
812
+ | `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …] [--toolchain-strict]` | Build (`--toolchain-strict` as for `build`), then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. It needs a cluster, `--url` or `json_rpc_url` in the Solana CLI config: it never falls back to the CLI's default. Before sending anything it prints the cluster's host and the payer, checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
813
+ | `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`); it prints the cluster's host and the payer before sending. |
792
814
  | `typesol cpi <idl.json> [--out <file.ts>] [--prefix <name>] [--address <base58>]` | Generate TypeSOL helpers that call another program from its IDL. Unsupported instructions are listed on stderr. |
793
815
  | `typesol port <idl.json> [--out <file.ts>]` | A TypeSOL program skeleton from an Anchor IDL (0.30+/1.x), to port an Anchor program: account structs, enums, errors, events and one function per instruction with its accounts and arguments, each body `require(false, …NotPorted)` until written. Instruction discriminators (an explicit `@discriminator` when the name derives another), account names and error codes are kept, so existing clients keep working where the layouts match; notes on stderr list where they do not (Borsh `String`/`Option` in account data, a `Vec` that is not the last field). Error codes that skip ahead are kept with `@code`, and zero-copy types keep their IDL `repr`, `serialization` and field names (`@repr`, `@serialization`, `@idlName`). |
794
816
  | `typesol client <idl.json> [--out <file.ts>] [--address <base58>]`, `typesol client --address <program id> [--url <rpc>] [--config <cli config>] [--out <file.ts>]` | Generate a typed TypeScript client on `@solana/kit` from an Anchor IDL (0.30+/1.x or TypeSOL); the IDL is validated first, and what the client leaves out is printed as notes. Without a file, the IDL is read from the chain: the canonical Program Metadata IDL, else Anchor's IDL account. See [client.md](client.md). |
795
- | `typesol verify <program\|file.ts> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <cli config>] [--sbpf …]` | Rebuild and compare with what is deployed. Without a `.so`, reads the program from the cluster (`--url`, cluster monikers such as `mainnet-beta` included, else the Solana CLI config) at `--address` or the address `typesol.json` records, under any loader (v2, upgradeable v3, v4); prints the upgrade authority (or that the program is immutable) and the last deploy slot, and compares the IDL published with `typesol idl publish` (a published IDL that differs is a mismatch). With a `.so` (e.g. `solana program dump`), compares with that file. Trailing zero padding is ignored; the SBPF version is read from the deployed ELF unless `--sbpf` is given. |
817
+ | `typesol verify <program\|file.ts> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <cli config>] [--sbpf …] [--manifest <name.build.json>]` | Rebuild and compare with what is deployed. Without a `.so`, reads the program from the cluster (`--url`, cluster monikers such as `mainnet-beta` included, else the Solana CLI config) at `--address` or the address `typesol.json` records, under any loader (v2, upgradeable v3, v4); prints the upgrade authority (or that the program is immutable) and the last deploy slot, and compares the IDL published with `typesol idl publish` (a published IDL that differs is a mismatch). With a `.so` (e.g. `solana program dump`), compares with that file. Trailing zero padding is ignored; the SBPF version is read from the deployed ELF unless `--sbpf` is given. On a mismatch it prints the rebuild's toolchain (clang, platform-tools, host, TypeSOL) and the deployed build's when a build manifest's binary hash is the deployed bytes' (`--manifest`, `<deployed>.build.json` next to a given `.so`, or the local build's), and what differs; otherwise it says the deployed side's toolchain is unknown (a program on chain records none). |
796
818
  | `typesol profile <logs.txt\|-> [--program <id>]` | Compute units per TypeScript line from the logs of a `--profile` build's transaction (exit 1 when the logs have no markers). |
797
819
  | `typesol help <command>` | Same as `typesol <command> --help`. |
798
820
  | `typesol --version` | Print the version. |
799
821
 
822
+ `clone`, `client --address`, `verify` and `idl publish` give up on an RPC request after 30 seconds
823
+ (`TYPESOL_RPC_TIMEOUT=<seconds>` changes it) and, like `doctor` and `deploy`, name only the RPC's host and the cause
824
+ when one fails (an RPC URL can carry an API key). A `--config` file that does not exist is a usage error everywhere.
825
+
826
+ Builds (`build`, `deploy`, `verify`, `typesol/testing`) compare the active clang with the one the release is tested
827
+ with (`TESTED_TOOLCHAIN` in `typesol/compiler`: Agave 3.1.10, platform-tools v1.52): another one gets one warning per
828
+ process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `warn` is the default.
829
+
800
830
  ## typesol.json
801
831
 
802
832
  ```json
@@ -910,6 +940,11 @@ integers and floats are `number`, `Pubkey` is kit's `Address`, `string` and `Fix
910
940
  as in the program. Names are camelCase. For Anchor IDLs, data enums use `__kind`, as Codama-generated clients do. The
911
941
  file uses no TypeScript-only syntax (no `enum`), so it also runs under Node's type stripping.
912
942
 
943
+ Anchor IDLs can also hold types a TypeSOL program does not: `u256`/`i256` are `bigint` (32 bytes, little-endian), and
944
+ `Option<Option<T>>` is `Option<T> | null` with kit's `Option` inside, so the three values stay apart: `null` is None,
945
+ `none()` is Some(None) and `some(x)` (or `x`) is Some(Some(x)). A type that holds itself through a Vec or an Option
946
+ (`enum Shape { Dot, Rec { kids: Vec<Shape> } }`) is encoded and decoded to any depth.
947
+
913
948
  ## Safety
914
949
 
915
950
  An IDL can come from anywhere, so `typesol client` refuses one whose names are not identifiers, whose discriminators or
@@ -923,9 +958,12 @@ Anchor IDLs are refused with a hint to convert them (`anchor idl convert`).
923
958
  `Program data:` line only while this program is the innermost one running, and `eventsOf` reads only the `emitCpi`
924
959
  inner instructions that call this program (it needs `tx.transaction`'s account keys for that). `parseCpiEvents(data)`
925
960
  on its own does not check the program: give it this program's inner instructions only.
926
- - **Not filled in automatically** (pass them): PDAs seeded from struct fields (Anchor cannot seed with them either),
927
- PDAs whose program is another account's field, and a PDA seeded from its own fields (derive it with its `pdas`
928
- helper from the values). `typesol client` prints a note for each.
961
+ - **Not filled in by the builder** (pass them): PDAs seeded from a field of another account's data (`state.owner`;
962
+ `resolve` reads the account and derives them), PDAs whose program is another account's field, and a PDA seeded from
963
+ its own fields (derive it with its `pdas` helper from the values). `typesol client` prints a note for each. PDAs
964
+ seeded from a field of a struct argument, at any depth (`params.inner.id`), are filled in.
965
+ - **Left out, with a note**: instructions, accounts and types using `Option<Option<Option<T>>>` or deeper, and types
966
+ the client cannot express (listed by `typesol client`).
929
967
  - **Anchor IDLs**: zero-copy (`bytemuck`) accounts decode and encode at their `#[repr(C)]` offsets as the program sees
930
968
  them on SBF (padding included; `packed` and `align` honored; 128-bit integers align to 8). Generic types become one
931
969
  type per use with concrete arguments (`Pair<u64, 2>` is `PairU64N2`). Left out, with a note: zero-copy types with
@@ -949,8 +987,9 @@ original side by side, the checks run against it and its cost, see [Case study:
949
987
  ```sh
950
988
  anchor build # in the Anchor project: target/idl/my_program.json
951
989
  npx @typesol/cli init my-program && cd my-program
990
+ npm install # the project's own TypeSOL, run below as npx --no-install typesol
952
991
  rm programs/my_program.ts tests/my_program.test.ts # the counter template's program and test
953
- npx typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
992
+ npx --no-install typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
954
993
  ```
955
994
 
956
995
  `typesol port` writes the account structs, enums, errors and one function per instruction with its accounts and
@@ -1103,6 +1142,18 @@ and next to `cargo-build-sbf` on PATH; set `TYPESOL_SBF_SDK` to a `platform-tool
1103
1142
 
1104
1143
  **"platform-tools missing" / "no SBPF v2 libraries"** — `cargo-build-sbf --force-tools-install`.
1105
1144
 
1145
+ **"warning: this build uses clang … TypeSOL is tested with clang 20.1.7-rust-dev …"** — the active platform-tools are
1146
+ not the ones the release is tested with (platform-tools v1.52, from Agave 3.1.10). The build goes on, but the C TypeSOL
1147
+ generates is only checked against that clang: another one can compile it to other bytes, and what the C relies on
1148
+ includes backend details (how the SBF backend passes struct arguments was behind a defect fixed after 0.43.0). Install the tested ones with
1149
+ `cargo-build-sbf --install-only --force-tools-install --tools-version v1.52`; `typesol doctor` shows which are active.
1150
+ In CI, `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) turns the warning into an error.
1151
+
1152
+ **`typesol verify` says MISMATCH** — first make sure the same sources (imports included), TypeSOL version and SBPF
1153
+ version are used. Then the toolchain: verify prints the rebuild's clang and platform-tools, and the deployed build's
1154
+ when a `<name>.build.json` describes the deployed bytes (`--manifest <file>`, one next to a given `.so`, or the local
1155
+ build's). A program on chain carries no such record, so keep the build manifest of every deployment.
1156
+
1106
1157
  **Windows** — not tested; use WSL2 with the Linux Agave CLI.
1107
1158
 
1108
1159
  **Node errors such as `ERR_UNKNOWN_FILE_EXTENSION` or `ERR_REQUIRE_ESM`** — use Node.js 22.12 or newer.
@@ -1146,9 +1197,18 @@ often inlined into their instruction, so their locals count toward its frame: ma
1146
1197
 
1147
1198
  From an empty directory to a program on Solana mainnet-beta: create, test, deploy, publish the IDL, then check that
1148
1199
  the deployed binary is the one your source builds. The program here is the counter that `typesol init` creates
1149
- (13.2 KiB); any TypeSOL project works the same way.
1200
+ (11,400 bytes, 11.1 KiB, built with TypeSOL 0.43.0 and platform-tools clang 20.1.7 for SBPF v0; other versions differ
1201
+ slightly); any TypeSOL project works the same way.
1202
+
1203
+ You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Quick start).
1150
1204
 
1151
- You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Requirements).
1205
+ **The toolchain you deploy with.** The binary is what the platform-tools' clang makes of the generated C, so the
1206
+ toolchain is part of what you trust. Deploy with the one TypeSOL is tested with (Agave 3.1.10, platform-tools v1.52;
1207
+ `typesol doctor` says whether yours is, and `typesol deploy --toolchain-strict` refuses another). Keep
1208
+ `target/my_app/my_app.build.json` with each deployment, next to the commit you deployed: it records the TypeSOL,
1209
+ TypeScript, clang and platform-tools versions and the host, and the deployed bytes' sha256. Step 6's `verify` matches
1210
+ only when it rebuilds with the same TypeSOL version and toolchain, and on a mismatch `--manifest` with that file shows
1211
+ what differs.
1152
1212
 
1153
1213
  ## 1. Create and test
1154
1214
 
@@ -1165,7 +1225,7 @@ Write your program in `programs/my_app.ts` and keep the tests passing before you
1165
1225
  ## 2. Build
1166
1226
 
1167
1227
  ```sh
1168
- npx typesol build
1228
+ npx --no-install typesol build
1169
1229
  ```
1170
1230
 
1171
1231
  This writes `target/my_app/`: the program (`my_app.so`), its Anchor IDL (`my_app.json`), a TypeScript client
@@ -1190,8 +1250,10 @@ ever close the program:
1190
1250
  solana rent $(wc -c < target/my_app/my_app.so)
1191
1251
  ```
1192
1252
 
1193
- The counter needs 0.069 SOL of rent. During the deploy the program is first written to a buffer account that holds
1194
- the same amount again; it is returned when the deploy finishes. Fund about twice the rent plus 0.01 SOL for fees.
1253
+ For the counter that is about 0.080 SOL (rent is (128 + size) × 6,960 lamports at the current rate: 80,234,880
1254
+ lamports for 11,400 bytes; the program data account holds 45 bytes more). During the deploy the program is first
1255
+ written to a buffer account that holds the same amount again; it is returned when the deploy finishes. Fund about
1256
+ twice the rent plus 0.01 SOL for fees: 0.17 SOL for the counter.
1195
1257
 
1196
1258
  The public mainnet RPC is rate-limited; for deploys, set `--url` (or `solana config set --url`) to your RPC
1197
1259
  provider's endpoint.
@@ -1199,8 +1261,8 @@ provider's endpoint.
1199
1261
  ## 4. Deploy
1200
1262
 
1201
1263
  ```sh
1202
- npx typesol deploy --dry-run # builds and prints the solana command it will run
1203
- npx typesol deploy
1264
+ npx --no-install typesol deploy --dry-run # builds and prints the solana command it will run
1265
+ npx --no-install typesol deploy
1204
1266
  ```
1205
1267
 
1206
1268
  It runs `solana program deploy` at the address in `target/deploy/my_app-keypair.json`, with your wallet as payer and
@@ -1212,7 +1274,7 @@ with `solana program close <buffer address>`, or list yours with `solana program
1212
1274
  ## 5. Publish the IDL
1213
1275
 
1214
1276
  ```sh
1215
- npx typesol idl publish
1277
+ npx --no-install typesol idl publish
1216
1278
  ```
1217
1279
 
1218
1280
  It writes the IDL to the Program Metadata program, signed by the upgrade authority, where Anchor clients and
@@ -1221,12 +1283,12 @@ explorers look for it. It costs a few thousandths of a SOL of rent.
1221
1283
  ## 6. Verify
1222
1284
 
1223
1285
  ```sh
1224
- npx typesol verify my_app
1286
+ npx --no-install typesol verify my_app
1225
1287
  ```
1226
1288
 
1227
1289
  `verify` rebuilds the program from `programs/my_app.ts`, reads the deployed one at the address in `typesol.json` from
1228
1290
  the cluster in your Solana CLI config, and compares the bytes. `match` means anyone with your source and the same
1229
- TypeSOL version gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
1291
+ TypeSOL version and toolchain gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
1230
1292
  published in step 5. Anyone can run it against your program with `--address <program id> --url mainnet-beta`.
1231
1293
 
1232
1294
  ## 7. Call it
@@ -1257,7 +1319,7 @@ auditors, [SECURITY.md](../SECURITY.md) how to report a problem.
1257
1319
  | --- | --- |
1258
1320
  | The program's author | the program's logic: what it allows, to whom, for how much |
1259
1321
  | TypeSOL (this repository) | that the binary does what the source and these guarantees say, and nothing an attacker can steer beyond it |
1260
- | The toolchain | the TypeScript compiler API (parsing, types), Agave platform-tools (clang, lld), Node.js |
1322
+ | The toolchain | the TypeScript compiler API (parsing, types), Agave platform-tools (clang, lld), Node.js. The guarantees are tested with one platform-tools release (v1.52, from Agave 3.1.10); a build with another warns, or fails with `--toolchain-strict`, and `<name>.build.json` records which one built a binary |
1261
1323
  | The Solana runtime | account ownership and signer flags as passed, the loader's account serialization, CPI privilege rules, sysvars |
1262
1324
 
1263
1325
  Everything a transaction carries is attacker-controlled: the instruction data, which accounts are passed in which
@@ -1295,7 +1357,8 @@ Each holds for every instruction of every program the compiler accepts. A break
1295
1357
  7. **Bounds.** Every index into an array, Vec, FixedVec or remaining-account list is checked (5104); a
1296
1358
  growable Vec's stored length is checked against the account's size before it is used (3003).
1297
1359
  8. **Account creation.** `create` / `createIfNeeded` is a top-level statement, and the account cannot be read or
1298
- written before it (compile error). Creation refuses an account that already exists (3000), and an address someone
1360
+ written before it (compile error). Creation refuses an account that already exists (the System Program's
1361
+ own error, custom 0; `initAccount<T>` over an account already holding a T is 3000), and an address someone
1299
1362
  pre-funded still gets created. `createIfNeeded` on an existing account re-derives the canonical PDA and checks
1300
1363
  owner, discriminator and size (token accounts: mint and owner; mints: decimals, authorities and the extensions it
1301
1364
  names). A `Migrate<From, To>` account is checked as an existing `From`; `migrate(…)` is a top-level statement every
@@ -1303,14 +1366,25 @@ Each holds for every instruction of every program the compiler accepts. A break
1303
1366
  errors).
1304
1367
  9. **Writes through references.** A place is never written after the code that computes its value may have moved it:
1305
1368
  replacing or resizing what a live reference points into is a compile error, as is writing a Vec element with a
1306
- right side that may resize the Vec.
1369
+ right side that may resize the Vec. A helper given a writable struct account may replace anything in it, however
1370
+ the account is named at the call (a parameter, an account group's field, a struct loaded with `loadAccountMut`): a
1371
+ reference into it read after the call is a compile error. Data that moves (a Vec of the account resized, so the
1372
+ Vecs after it shift, or a helper given the account) moves under every name of the account: a reference made
1373
+ through another parameter that may be the same account (a `Dup<…>` pair, a read-only and a writable account of one
1374
+ type, a struct loaded with `loadAccount` / `loadAccountMut`) is held to the same rule. A helper that can write gets its Pubkey, Option and
1375
+ string arguments as they were at the call (a copy unless nothing it is given reaches them), and a closed account
1376
+ is not used after `close()` (compile error).
1307
1377
  10. **Remaining accounts.** Writing one (`.lamports`, `loadAccountMut`) checks it is writable (3006) and not another
1308
1378
  account of the instruction (2040); `loadAccountMut` loads a given account once per instruction (2040);
1309
1379
  `loadAccount<T>` checks owner, discriminator and size, and validates the data as instruction arguments are.
1310
- 11. **Growth.** An account grows by at most 10 KiB per instruction (3016), the payer is a `Mut<Signer>`, new bytes are
1311
- zero and the new rent is paid; shrinking keeps the lamports in the account.
1380
+ 11. **Growth.** An account grows by at most 10 KiB per instruction (3016), counted from its length when the
1381
+ instruction started, the payer is a `Mut<Signer>`, new bytes are zero and the new rent is paid; shrinking keeps
1382
+ the lamports in the account.
1312
1383
  12. **CPIs.** A program signs only for its own PDAs (the runtime enforces it; the seeds are those written in the
1313
- source). `invoke` marks an account writable or signer only when the parameter is `Mut` / `Signer` or the program
1384
+ source, with the values they had where the list was written, also for a named list or one given to a helper; a
1385
+ wrapper's arguments are evaluated left to right, as JS evaluates them, the seeds after the arguments before
1386
+ them). Token-2022 and SPL Token instruction data is laid out as the program reads it (a `COption` key that is
1387
+ None is one byte). `invoke` marks an account writable or signer only when the parameter is `Mut` / `Signer` or the program
1314
1388
  signs for it; remaining accounts keep the flags they were passed with, or are checked for the role requested.
1315
1389
  `invokeInstruction` is the exception by design: its program, account flags and data come from values (stored in
1316
1390
  account data or passed in), so the compiler cannot check them; the runtime does, refusing any account the
@@ -1333,15 +1407,23 @@ Each holds for every instruction of every program the compiler accepts. A break
1333
1407
  - **`requirePda(account, seeds, bump)`.** Any valid bump passes (Anchor's `bump = expr`). Use a stored bump, never one
1334
1408
  from the arguments.
1335
1409
  - **`Dup<…>`.** A parameter marked `Dup` may be the same account as another writable one. Reads see every write
1336
- (both are the same bytes), so a value read before a write through the other slot is stale: read, then write.
1410
+ (both are the same bytes), so a value read before a write through the other slot is stale: read, then write. (A
1411
+ reference held across a resize through the other slot is a compile error, guarantee 9.)
1337
1412
  - **`NATIVE_ACCOUNT_WRITES`.** A program that declares it gives up the up-front writability check and the
1338
1413
  one-view-per-account refusal for `loadRawMut`, `storeBorsh` and BigVec writes, as a native program has neither: the
1339
1414
  runtime still refuses a changed read-only account, but two loads of one account alias each other. Make the
1340
1415
  original's address and type checks before loading.
1341
1416
  - **Instruction introspection.** The Instructions sysvar holds what the transaction's author put there. Require things
1342
1417
  of the transaction with it (that a repay instruction follows), never treat it as proof of who did what.
1343
- - **Oracles.** `pythPrice` checks verification, feed and age (pass the exponent you scale by); the raw `update.*`
1344
- fields are unchecked. `switchboardValue` needs the expected feed; set `minSamples`.
1418
+ - **Oracles.** `pythPrice` checks the owner and account type, full verification, the feed id, the age and (when
1419
+ passed) the exponent; the raw `update.*` fields are unchecked. `switchboardValue` checks the owner, the account
1420
+ type, the expected feed, the sample count (`minSamples`, default 1) and staleness, measured in slots from the
1421
+ feed's `result.slot`. Neither checks, and both leave to the author:
1422
+ - the price's sign and zero: a negative or zero price is returned as it is;
1423
+ - the confidence: Pyth's `conf` and Switchboard's spread of samples are not compared with anything;
1424
+ - a publish time (Pyth) or result slot (Switchboard) in the future: it counts as fresh;
1425
+ - rounding: `switchboardValue` scales the 18-decimal result to `decimals` rounding toward zero, and a price scaled
1426
+ by its exponent in the program rounds as that code does.
1345
1427
  - **`merkleVerify`.** Leaves and inner nodes hash alike: build leaves as `keccak256(keccak256(data))` in the program.
1346
1428
  - **Existing accounts in `createIfNeeded`.** An existing token account's delegate and close authority, and a mint's
1347
1429
  extensions the call does not name, are not checked (as in Anchor).
@@ -1354,11 +1436,58 @@ Each holds for every instruction of every program the compiler accepts. A break
1354
1436
  - Arithmetic overflow returns an error code (5100) in every build; Anchor aborts the program, and only when
1355
1437
  overflow checks are enabled.
1356
1438
 
1439
+ ## Review of 0.44.0 (2026-11-11)
1440
+
1441
+ A second internal review, of 0.44.0, found guarantees 9 and 12 and the token wrappers' instruction data broken in the
1442
+ cases listed in [audit.md](audit.md#0440-2026-11-11); they are fixed in 0.44.1. Of the 76 programs of the 0.44.0
1443
+ sources, 74 build to the same binary with 0.44.1 and 2 to another (mint-close-authority and allow-block-list-token);
1444
+ none is refused. A program was exposed only if it uses the construct a defect names:
1445
+
1446
+ - `mint.create` / `createIfNeeded` with `transferFee` whose config or withdraw authority is `null` or a run-time None
1447
+ (the mint got another fee and no withdraw authority: check the mint), or extensions adding up to 355 bytes (the
1448
+ call always failed);
1449
+ - a `Dup<…>` pair, a read-only and a writable account of one struct type, or a struct loaded with `loadAccount` /
1450
+ `loadAccountMut`, with a reference made through one held across a push, pop or clear (or a helper given the
1451
+ account) through the other, when the transaction passes one account for both;
1452
+ - a token or Stake wrapper call with signer seeds and an argument that runs code (a helper call, an assignment) whose
1453
+ effects the seeds, the amount or a metadata string read;
1454
+ - `updateExtraAccountMetas` after the account was already grown in the same instruction.
1455
+
1456
+ A program that uses none of them was not exposed to these defects; rebuilding it with 0.44.1 gives the same binary.
1457
+
1458
+ ## Review of 0.43.0 (2026-11-11)
1459
+
1460
+ An internal review of 0.43.0 found that some of the guarantees above did not hold in every case; the defects are
1461
+ listed in [audit.md](audit.md#0430-2026-11-11) and fixed in 0.44.0. Programs built with 0.43.0 or
1462
+ earlier should be rebuilt with it and redeployed: the fixes change the binary of programs that have a helper
1463
+ taking a Pubkey, Option, string or u256, exposed or not (35 of the 76 programs of the 0.43.0 sources build to the same
1464
+ binary, 41 to another).
1465
+
1466
+ The defect that can break an authorization check is the first: a Pubkey, Option, string or u256 argument of a
1467
+ helper was not a copy. A program was exposed where all of these hold:
1468
+
1469
+ - a helper takes a parameter of one of those types and also an account it writes (or remaining accounts, or an
1470
+ `Inout` place);
1471
+ - a call passes that parameter a field of the same account (`rotate(v, v.admin, caller)`), or a value stored in it;
1472
+ - the helper reads the parameter after writing the field (`v.admin = v.pending`, then a check on `admin`): it read
1473
+ the new value;
1474
+ - the helper was not inlined. A `/** @noinline */` helper never is; for the others it was clang's choice, which the
1475
+ source does not show, so count every such call as exposed.
1476
+
1477
+ Each of the other defects needs the construct it names: a seed list bound to a name, given to a helper or written
1478
+ beside an argument with side effects; a reference held across a helper that is given an account-group field or a
1479
+ loaded account; Borsh input with an Option of a struct that holds an Option (a bounded read past the input, no
1480
+ write); a closure or callback that changes a local read before it; a string viewing an `Inout` place; `close()` into
1481
+ the account itself, `Dup<…>` on a closed account, or an account used after `close()`. A program without them was not
1482
+ exposed to them.
1483
+
1357
1484
  ## Status
1358
1485
 
1359
- The compiler and runtime have had internal security reviews; the findings of the latest are fixed in 0.25.0
1360
- (CHANGELOG). The releases after it have not had such a review yet, and there has been no external audit: see
1361
- [audit.md](audit.md).
1486
+ The compiler and runtime have had internal security reviews, the latest of 0.44.0 (above); its findings are fixed in
1487
+ 0.44.1. It was an internal review, not an independent audit; it covered the token, Token-2022, Metaplex and Stake
1488
+ wrappers, the oracles and SBPF v1/v2 builds of the examples that the review of 0.43.0 left out, but not the Metaplex
1489
+ wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. There has been no
1490
+ external audit: see [audit.md](audit.md).
1362
1491
 
1363
1492
  <!-- docs/ai.md -->
1364
1493
 
@@ -1387,7 +1516,8 @@ own project notes below them in AGENTS.md.
1387
1516
  ([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
1388
1517
  and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
1389
1518
  in one file, to paste into a chat or give to a model as context. Both also ship in the npm package
1390
- (`node_modules/typesol/llms-full.txt`).
1519
+ (`node_modules/typesol/llms-full.txt` in a project `typesol init` created, which installs `@typesol/cli` under the
1520
+ name `typesol`; `node_modules/@typesol/cli/llms-full.txt` where it is installed under its own name).
1391
1521
 
1392
1522
  ## Errors an agent can fix by itself
1393
1523
 
@@ -1398,13 +1528,17 @@ in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on ch
1398
1528
  ## The MCP server
1399
1529
 
1400
1530
  `typesol mcp` serves the [Model Context Protocol](https://modelcontextprotocol.io) on stdio. `typesol init` writes
1401
- `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx typesol mcp`. Other clients take the
1402
- same command:
1531
+ `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx --no-install typesol mcp`: the
1532
+ project's own copy, after `npm install`. `--no-install` matters: `typesol` is not the npm package's name, and without
1533
+ it npx would fetch whatever package is published as `typesol` when the project's copy is missing. Other clients take
1534
+ the same command, run in the project directory:
1403
1535
 
1404
1536
  ```json
1405
- { "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
1537
+ { "mcpServers": { "typesol": { "command": "npx", "args": ["--no-install", "typesol", "mcp"] } } }
1406
1538
  ```
1407
1539
 
1540
+ Outside a project, start it from the published package by its full name: `npx -y @typesol/cli mcp`.
1541
+
1408
1542
  | Tool | What it does |
1409
1543
  | --- | --- |
1410
1544
  | `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
@@ -1412,7 +1546,7 @@ same command:
1412
1546
  | `docs` | searches the docs and returns the best-matching sections |
1413
1547
  | `rules` | the rules above |
1414
1548
 
1415
- Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
1549
+ Building and testing stay in the shell (`npm test`, `npx --no-install typesol build`): they need the platform-tools and write
1416
1550
  files, which an agent should do in the open.
1417
1551
 
1418
1552
  <!-- docs/stability.md -->
@@ -1430,8 +1564,9 @@ From 1.0 on, within a major version:
1430
1564
 
1431
1565
  - **Sources keep compiling.** A program that compiles with 1.x compiles with every later 1.y, to a program with the same
1432
1566
  account layouts, IDL, instruction and account discriminators and error codes. New releases add; they do not take away.
1433
- - **Binaries are reproducible and only change for a reason.** A release that changes the binary of a program that uses
1434
- none of its new features says so, with the release manifest's diff (`binary-diff.txt`) as the evidence.
1567
+ - **Binaries are reproducible and only change for a reason.** With the same TypeSOL release and the toolchain it is
1568
+ tested with, a source builds to the same bytes. A release that changes the binary of a program that uses none of
1569
+ its new features says so, with the release manifest's diff (`binary-diff.txt`) as the evidence.
1435
1570
  - **The checks stay.** No check a program gets from its parameter types (owner, discriminator, signer, writability,
1436
1571
  aliasing, checked arithmetic, constraints) is removed or weakened.
1437
1572
  - **The tools keep their interfaces**: `typesol build`, `test` (via `typesol/testing`), `check --json`, `deploy`,
@@ -1450,6 +1585,24 @@ Meant to stay as they are; a change before 1.0 would be a breaking change listed
1450
1585
  - CPIs: System, SPL Token, Token-2022, Associated Token, Memo, generic `invoke` with PDA signing.
1451
1586
  - Layouts: account data (Anchor's discriminator and fixed or `@layout borsh` layout), the IDL, the client.
1452
1587
 
1588
+ ## What a release gives you now
1589
+
1590
+ - **The npm package is the one that was checked.** From 0.43.0 on, `releases/<version>.json` in the repository holds
1591
+ the published tarball's shasum and integrity and every file's sha256, packed from a clean export of the release tag
1592
+ after install, build and lint. `npm pack` is reproducible here, so anyone can pack the tag again and compare, or
1593
+ compare the registry with `node scripts/release-check.ts <version> --verify --registry`
1594
+ ([docs/testing.md](testing.md#the-npm-tarball)).
1595
+ - **The tests cover one toolchain.** Each release declares the Agave and platform-tools it is tested with
1596
+ (`TESTED_TOOLCHAIN`, exported from `typesol/compiler`; Agave 3.1.10 and platform-tools v1.52 now). A binary built with
1597
+ another clang is outside what the tests cover: `typesol build` and `deploy` warn once, `--toolchain-strict` (or
1598
+ `TYPESOL_TOOLCHAIN=strict`) refuses it, and `typesol doctor` shows which one is active.
1599
+ - **A build says what made it.** `<name>.build.json` records the TypeSOL, TypeScript, clang and platform-tools versions,
1600
+ the host, the SBPF version and the sha256 of every source and of the binary. `typesol verify` uses it to say, on a
1601
+ mismatch, whether the toolchains differ. A program on chain records none of this: keep the file with the deployment.
1602
+ - **Fixes come as patches of the latest minor.** From 0.44.0 on, a release that only fixes soundness or security
1603
+ defects is a patch (0.44.1, …) with no new language surface, and its notes carry the binary diff against the
1604
+ previous release ([SECURITY.md](../SECURITY.md#fix-releases)). Older minors are not maintained.
1605
+
1453
1606
  ## Experimental
1454
1607
 
1455
1608
  Useful today, but may still change before 1.0 (each change listed in the CHANGELOG):