@typesol/cli 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  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 +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. 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.
@@ -74,8 +88,9 @@ If the build refuses something, the error points at the line and, for the usual
74
88
  `typesol port` starts from your program's IDL; [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one
75
89
  program through the port.
76
90
  - Real programs checked against their mainnet binaries: [Showcase](#showcase-ports-checked-against-mainnet), with a
77
- case study each (Marginfi v2 in full: all 124 instructions, the same on 2,081 transactions; Raydium AMM v4, a native
78
- program, down to its log lines).
91
+ case study each (Marginfi v2 in full: all 124 instructions, the same on 2,081 transactions; Phoenix v1, a native
92
+ order book, the same on 3,575 transactions down to its event bytes; Raydium AMM v4, a native program, down to its log
93
+ lines).
79
94
  - To mainnet (wallet, cost, deploy, IDL, verification): [docs/mainnet.md](docs/mainnet.md).
80
95
  - With an AI coding agent: [docs/ai.md](docs/ai.md) (agent rules, [llms.txt](https://typesol.com/llms.txt), the MCP server).
81
96
 
@@ -91,7 +106,7 @@ The full reference. For a tour, start with the [README](../README.md).
91
106
  | --- | --- |
92
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) |
93
108
  | Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
94
- | 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 |
95
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)` |
96
111
  | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
97
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) |
@@ -99,11 +114,12 @@ The full reference. For a tour, start with the [README](../README.md).
99
114
  | Logging | `log("text")`, `log(value)`, `log(pubkey)` |
100
115
  | Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
101
116
  | Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack; also a struct literal's field value (`{ prices: fixedArray<u64, 16>(0n), … }`), filled in place. Elements may be structs of fixed size or `FixedString<N>` (`fixedArray<Meta, 2>({ pubkey, isSigner: false, isWritable: true })`: the fill built once and copied into each slot), and `fixedArray<T, N>(fill)` written inline feeds a chain, a list method or `for … of` (`fixedArray<u64, 3>(2n).map((x) => x * 5n).reduce(…)`) |
102
- | Local lists | `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey: k, isSigner: false, isWritable: false }])`, `const buf: FixedVec<u8, 600> = fixedVec([])`, `const pair: FixedArray<Meta, 2> = fixedArray(meta)` — a FixedVec or FixedArray of integers, booleans, Pubkeys, enums, `FixedString<N>` or fixed-size structs on the stack, with `get`, `set`, `push`, `pushAll`, `pop`, `clear`, `.length`, `for … of` and the list methods; given another list (`const y: FixedVec<Pubkey, 4> = xs`) it is a copy, as a struct local is. One list holds at most 2 KiB (the 4 KiB stack frame is shared with the rest of the function): a bigger one is a compile error naming its size |
117
+ | Local lists | `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey: k, isSigner: false, isWritable: false }])`, `const buf: FixedVec<u8, 600> = fixedVec([])`, `const pair: FixedArray<Meta, 2> = fixedArray(meta)` — a FixedVec or FixedArray of integers, booleans, Pubkeys, enums, `FixedString<N>` or fixed-size structs on the stack, with `get`, `set`, `push`, `pushAll`, `pop`, `clear`, `.length`, `for … of` and the list methods (a `FixedVec<u8, N>` is also a byte buffer: `pushLE`, `pushKey`, `pushBorsh`, `setLE`, `truncate`, see [Porting a native program](#porting-a-native-program)); given another list (`const y: FixedVec<Pubkey, 4> = xs`) it is a copy, as a struct local is. Setting one up costs about the same at any size (`fixedVec([])` of 1280 bytes about 10 CU: the free slots are zeroed by the memset syscall, the elements written in place, also as a struct literal's field). One list holds at most 2 KiB of elements (a FixedVec's u32 length aside: `FixedVec<u32, 512>` fits; the 4 KiB stack frame is shared with the rest of the function, and a frame that overflows is reported with its biggest locals): a bigger one is a compile error naming its size. `/** @heap */` on an instruction's list or struct local (`/** @heap */ const ids: FixedVec<u8, 1024> = fixedVec([])`) keeps it on the heap instead (one allocation per declaration, reused when a loop declares it again; up to the heap's size, 32 KiB or `HEAP_SIZE_KIB`; about 18 CU); not in helpers, which may run many times while the heap is never freed |
103
118
  | Strings | `string` arguments and literals; `name: FixedString<32>` in account data (u32 length + 32 bytes); `===`, `byteLength(s)`, `log(s)`, `+=`, as PDA seeds; too-long writes abort (5105). A local bound to account text keeps its own copy |
104
119
  | Copies | `a.home = b.home`, `a.trail.set(0n, a.home)` copy whole structs / arrays of the same type: assignment copies (like Rust/Anchor), binding with `const` references |
105
120
  | Destructuring | `const { owner, pos: p } = acct` (or `let` for scalars to change) from a name or a field path — one declaration per name, read like `acct.owner`: scalars are copies, nested structs are references. No rest, defaults or nesting |
106
121
  | Struct values | `const p: Point = { x, y }` (or a copy of another Point) — a local struct; fields can be updated, store it with `acct.home = p` |
122
+ | File-local structs | `interface Pair { a: u64; b: u64 }` without `export`: the file's own struct, for its helpers (parameters, results, `Inout<Pair>`), locals and other such structs; left out of the IDL. What the IDL describes (account data, instruction arguments and results, events, an exported struct's field, a data enum's variant) cannot hold one: each such use is an error saying to export it |
107
123
  | Pubkey constants | `const ADMIN = pubkey("4Nd1…")` (checked at compile time) or inline `pubkey("…")`; usable as seeds |
108
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 |
109
125
  | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
@@ -117,6 +133,8 @@ The full reference. For a tour, start with the [README](../README.md).
117
133
  | Options of arrays | `Option<FixedArray<T, N>>` fields (Anchor's `Option<[u16; 3]>`): one tag byte then N elements in fixed layouts, Borsh in arguments and events |
118
134
  | Fixed-capacity lists | `owners: FixedVec<Pubkey, 8>` — any field, any number of them, in nested structs too: a u32 length and room for N elements (always 4 + N × size bytes), the same `get`, `set`, `push(v)`, `pop()`, `clear()`, `.length` and `for … of`; `push` on a full one fails (5104); `xs.pushAll(items)` appends a whole list of the same elements in one copy (another FixedVec, a FixedArray or Vec, a Vec argument, the instruction data or a slice of it: a memcpy, about 0.01 CU a byte for 1000 bytes against 11 for a `push` loop), failing with 5104 and appending nothing when it does not fit (`Vec` declares it so a Vec still passes for a FixedVec, but a Vec grows one `push` at a time); `acct.owners = fixedVec([a, b])` writes a whole one (unused slots zeroed), and `acct.owners = owners` copies a `Vec` argument (or another list of the same elements) into it, Anchor's `multisig.owners = owners` (more than N fail with 5104). In account data, returned structs and events; as an argument (`ids: FixedVec<u64, 8>`) it is a Borsh Vec of at most N elements, read like a `Vec` argument (more fail with 102) |
119
135
  | Native zero-copy lists | `validators: BigVec<ValidatorStakeInfo>` — SPL's `big_vec` (the stake pool's validator list): the last field of a fixed-layout struct read with `loadRaw` / `loadRawMut`, a u32 length then the elements, in an account allocated up front; its room is the account's (`.capacity`: (size − fixed fields − 4) / size(T)) and it is never resized. Loading checks that the length fits (ProgramError::AccountDataTooSmall), and every access afterwards is bounded by the room as well: a length written again after the load (writeData, another view, storeBorsh) is read as at most `.capacity`, so `.length`, `get` / `set`, the loops, `slice` and `retain` never reach past the account. `get` / `set` (5104 past the length), `push(v)` (AccountDataTooSmall when full, as BigVec::push), `retain((x) => keep)` (in place, one pass, kept runs moved with the memmove syscall; bytes past the new end keep what they held, as BigVec::retain), `for … of`, the list callbacks (`findIndex`, `find(f)!.field` on struct elements), `.length`. `list.slice(start, end?)` is BigVec::deserialize_mut_slice(start, end − start), used where it is written (`for (const v of l.validators.slice(skip, skip + n))`, `.slice(a, b).forEach(…)`, `.get(i)`, `.length`); out of range fails with AccountDataTooSmall instead of clamping. Elements are references into the account. Not an account parameter, an argument, a local, nested, or in a `@layout borsh` struct |
136
+ | Views at run-time offsets | A native account whose parts start where its header says (Phoenix's market at byte 576, trees sized by `market_size_params`, Serum's slabs): `loadRawAt<T>(acct, offset)` / `loadRawMutAt<T>(acct, offset)` are `loadRaw` / `loadRawMut` at a byte offset known only at run time, and `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt<T>(…)` are `capacity` elements of a fixed-size type (integers, booleans, Pubkeys, enums, `FixedString<N>`, structs) packed in place from there, the count a run-time u64: `get` / `set` (5104 past the count), `.length` (the capacity), `for … of` and the list methods, structs by reference. The bounds are checked once, when the view is made (`offset + size`, with overflow, within the data: ProgramError::AccountDataTooSmall), and element access is pointer arithmetic. Owner (3007), writability and the one-mutable-view claim (2040) are `loadRaw` / `loadRawMut`'s, so several mutable views of one account need `NATIVE_ACCOUNT_WRITES`, as a native port declares. Bind them with const; not helper parameters. A view (and anything read through it) is not used after `closeRaw` or `resizeAccount` of an account it may view, or after a helper that may close or resize one it is given: its bounds were checked against the old length, so it is a compile error saying to take the view again |
137
+ | lib-sokoban's RedBlackTree | `const bids = rbTreeMutAt<FIFOOrderId, FIFORestingOrder>(market, offset, capacity, compareOrders)` (or `rbTreeAt` to read): lib-sokoban 0.3's `RedBlackTree<K, V, N>` over account bytes, byte for byte (root, allocator, 1-based nodes of registers + key + value; freed nodes keep their key and value; LIFO free list ending at the bump index), checked against the crate after every operation of recorded traces (test/verification/rbtree-trace.test.ts). `length`, `capacity`, `initialize()`, `get(k)` (the value in place, or null), `insert(k, v)` (the node index, or null when a new key finds it full; an equal key takes the value), `remove(k)` (the value, read in the freed node, or null), `removeAt(i)` (the node at index `i` from `addrOf` or a node's `.index`, removed with `remove`'s writes without searching again: 144 CU less per cancel in test/language/phx-costs.test.ts; null for 0 or a node in no tree), `min()` / `max()` (a node: `.key`, `.value`, `.index`, or null), `addrOf(k)` (0 when absent), `nodeAt(i)` (Phoenix keeps a trader's node index), `for (const e of tree)` / `tree.reversed()` with `break` / `continue`. The comparator, a function of the program `(a: K, b: K) => i8` (any signed integer result; an unsigned one is refused, as it could never say "less"), is called as `compare(searchedKey, nodeKey)` (Phoenix's FIFOOrderId orders by the left key's side); without one, keys are ordered as Rust derives Ord (fields in order, integers by value, Pubkeys bytewise). A reference into the tree (`get`, `min`, a node, however it is bound: `c ? t.min() : t.max()`, `t.get(k)!`; a node is bound with const) cannot be used after an `insert` (it may reuse a freed node), and a `for … of` body cannot insert, remove or initialize on the tree it walks, nor on any tree view of an account that may be the walked one's (another view of the same tree; under `NATIVE_ACCOUNT_WRITES` any account may be), nor call a helper that takes accounts and makes an `rbTreeMutAt` view (compile errors, as Rust's borrows). Panics as sokoban's (see [Porting a native program](#porting-a-native-program)) |
120
138
  | Struct arguments | `order: Order`, `ids: FixedArray<u8, 4>`, `orders: Vec<Order>` — fixed layouts, Borsh-identical, validated on entry (bools, enums, option tags, string lengths, enum tags; 102) and read-only. A struct holding a FixedVec that is only ever an argument is read as Anchor sends it (its FixedVec a Borsh Vec, as `@layout borsh`). A struct holding Options (at any depth, Anchor's `BankConfigOpt`) that is not account data is Borsh on the wire as Anchor sends it, an empty Option one byte; read its Some values after narrowing (`if (c.rate !== null && c.rate.zero_util !== null) …`), also an `Option<FixedArray<T, N>>` (`.get(i)`, or copied whole into a `FixedArray` field). An argument may itself be an `Option<S>` of such a struct (Anchor's `Option<WrappedI80F48>`): a tag byte, then the struct when Some; read its fields after `x !== null`; helpers take the struct, not the Option. Likewise `Option<Vec<T>>` (or `Vec<T> | null`, or of a FixedVec; Anchor's `Option<Vec<u8>>`): a tag byte, then the Vec when Some; check `x !== null` before reading it as a list or passing it to a helper that takes the list. An event may hold one too (`keys: Option<Vec<Pubkey>>`, given `null`, such an argument or a list), and a nested struct written as a literal in an event (`header: { signer: who.key, … }`) goes out as Borsh, its Options one byte when empty. A `Vec<u8>` is `bytes` in the IDL, as Anchor writes it (clients pass a Buffer) |
121
139
  | Accounts created by hand | `systemProgram.createAccount(…)`, or `allocate(account, space, seeds?)` + `assign(account, owner, seeds?)` for an address someone pre-funded, then `const data = initAccount<T>(account)` (Anchor's `load_init`: owned by this program 3007, writable 3006, large enough 3003, no discriminator yet 3000) gives the struct to fill: for accounts whose address is decided at run time (a PDA or a signing keypair), as Raydium's pools are. `Init<T>` covers the usual case |
122
140
  | Remaining accounts | `remainingAccounts()` — `.length`, `.get(i)` → `key`, `owner`, `lamports` (writes check writability), `isSigner`, `isWritable`; `loadAccount<T>` / `loadAccountMut<T>` give checked struct views (also of an `AccountInfo` parameter, Anchor's `AccountLoader::try_from` on an `UncheckedAccount`; the view is also its account: `.key`, `.lamports`, and it passes to a helper taking `Account<T>` / `Mut<T>`; a second `loadAccountMut` of one account is refused, 2040, but a view declared in a loop body ends with its iteration, and `loadAccountMut<Dup<T>>` in a loop also accepts an account passed more than once, one view at a time, as a route back through one pool needs); pass one to a helper that takes a `RemainingAccount` parameter (it reads the key, owner, lamports, data length and data, and loads structs from it; a `loadAccountMut` there claims the account for the rest of the instruction, so a second one fails with 2040), or all of them to one that takes `RemainingAccounts` (`.length`, `.get(i)`, passed on to other helpers; spreading them into a CPI stays in the instruction); pass them to `invoke`, one at a time or spread: `...remainingAccounts()` (each with the flags it was passed with), `...readonly(rest)` / `...writable(rest)` (all with that role), `rest.slice(a, b)` for part of them; a CPI lists at most as many accounts as an instruction takes (5113) |
@@ -124,22 +142,24 @@ The full reference. For a tour, start with the [README](../README.md).
124
142
  | Struct references | `const o = side === Side.Bid ? book.bids.get(i) : book.asks.get(i)` — aliases account data like a JS object reference (no copy); replacing the referenced place (`book.bids.set(i, …)`, `pop()`, `clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JS would keep the old object |
125
143
  | Other programs' accounts | `const pool = loadForeign<Pool>(account, AMM_PROGRAM)` — owner, `account:Pool` discriminator and size checked (3007 / 3002 / 3003); `readData<u64>(account, offset)` for raw little-endian reads (bounds-checked, 3003); `writeData<u64>(account, offset, value)` writes one into a `Mut<AccountInfo>` of this program (bounds-checked, 3003): raw layouts such as Marginfi's monitor archive |
126
144
  | Ternaries | `const fee = vip ? 0n : 30n` — only the chosen branch runs. Between accounts too: `const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or `RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a remaining account does (typed CPIs, `readData`, `loadRaw` / `loadRawMut`, `loadBorsh`, helpers taking a `RemainingAccount`) |
127
- | Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL) |
145
+ | Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL); an integer constant may be computed from literals and constants declared before it, here or in an imported file (`const EVENT_ROOM = 1280n - 34n`, `const ASKS_AT: u64 = BIDS_AT + 2n * BOOK`: `+ - * / % ** & \| ^ << >>`, unary `-` and `~`), folded when the program is compiled; a typed one is computed in its type, every step checked (`const X: u64 = 1n - 2n + 5n` is an error; `const M: u8 = ~1n` is 254, `~` within the width), and division by zero, a negative exponent or a shift past the width are compile errors |
146
+ | Type aliases | `type Price = u64`, `type Key = Pubkey`, `type Buf = FixedVec<u8, 32>`, `type MaybePoint = Point \| null`, an alias of another alias — another name for one type, replaced by it wherever it is used (layouts, arguments, the IDL: all the type's own); exported or not, imported like any name (the aliased type keeps the names of the file declaring it). Not generic. A union of named types (`type Event = Fill \| Place`) is neither an alias nor a data enum: write the variants as object types, below |
128
147
  | Data enums | `export type Action = { kind: "Deposit"; amount: u64 } \| { kind: "Pause" }` — `a.kind === "Deposit"`, `switch (a.kind)`, TypeScript narrowing picks the variant (checked again at runtime, 5112); Borsh enums in arguments/events, fixed `{ tag, payload }` in account data. A variant may hold a `string` (`{ kind: "Say"; text: string }`): such an enum works in arguments, events and locals (Borsh, as Anchor encodes it) but not in account data |
129
148
  | Option of structs | `home: Option<Point>` in account data — `=== null`, `p.home.x` after narrowing, `p.home = null` / `{ x, y }`; once narrowed, `p.home` (or an `Option<FixedArray>`) also passes to a helper that takes the struct (or array) |
130
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 |
131
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 |
132
- | 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; `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) |
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) |
133
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) (mainnet program unless `SwitchboardFeed<"devnet">`) |
134
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 |
135
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 |
136
- | Loops | `for (let i = 0n; i < n; i++)`, `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 |
137
- | Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `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. 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) |
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 |
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) |
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 |
138
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) |
139
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) |
140
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) |
141
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) |
142
- | 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) |
143
163
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
144
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) |
145
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) |
@@ -220,7 +240,9 @@ of a position, as Raydium CLMM's tick arrays).
220
240
  come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
221
241
  `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
222
242
  `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
223
- - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
243
+ - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts (the destination
244
+ is another writable account; the account is not used after it in the function, except its `key`: compile errors, or
245
+ 2040 at run time in a helper given one account twice)
224
246
  - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
225
247
  stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
226
248
  among up to 256 addresses for the same seeds
@@ -265,7 +287,10 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
265
287
  lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
266
288
  - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
267
289
  wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
268
- signer([…, bump])`.
290
+ signer([…, bump])`. A named list, and one given to a helper, holds its seeds as they were when it was written (JS
291
+ evaluates the array then): a field or local changed afterwards does not change what it signs for. A list written in
292
+ a call (`transfer(…, signer([…]))`, `create(payer, [...], space)`) holds them as they were when the list was read,
293
+ even when a later argument changes a seed.
269
294
  - `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
270
295
  - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
271
296
  A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
@@ -354,7 +379,13 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
354
379
  hand-encoded `invoke` data.
355
380
  - Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
356
381
  byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
357
- original's own checks (an exact size, its error codes) before the load. Structs are packed, as `#[repr(C, packed)]`.
382
+ original's own checks (an exact size, its error codes) before the load. A read-only view can be read where it is
383
+ made, `loadRaw<Header>(market).inner.b` or `loadRawAt<Prefix>(market, 576n).tick` (its checks made there); a
384
+ writable one claims its account once per instruction, so it is bound to a const first. The owner check of these views (and of
385
+ `loadRawAt`, `rawArrayAt`, `rbTreeAt` below) is made every time, but the last account found this program's passes
386
+ again with one pointer compare instead of 32 bytes until a CPI or an owner write (`assignOwner`, `closeRaw`,
387
+ `close`): helpers that each view the market again, and views in loops, pay about 3 compute units for it instead of
388
+ about 14. Structs are packed, as `#[repr(C, packed)]`.
358
389
  - Borsh accounts without a discriminator (SPL Stake Pool's `StakePool`, read with `try_from_slice_unchecked` and
359
390
  written with `serialize`): `const pool = loadBorsh<StakePool>(acct)` decodes the data from byte 0 into a local
360
391
  struct (a copy: fields updated, Options narrowed and set to null or a value, data enums switched, copied, passed to
@@ -374,6 +405,54 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
374
405
  `for (const v of list.validators.slice(skip, skip + len))` (`deserialize_mut_slice(skip, len)`). The load fails with
375
406
  AccountDataTooSmall when the stored length does not fit, where the Rust would only panic on reaching such an element:
376
407
  check the length first (`readData<u32>(acct, offset)`) where the original returns an error of its own before that.
408
+ - Parts at offsets the account's header gives: `loadRawAt<T>(acct, offset)` / `loadRawMutAt<T>(…)` for a struct,
409
+ `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt<T>(…)` for a run-time number of elements, each bounds-checked
410
+ once when it is made (ProgramError::AccountDataTooSmall; `loadRaw`'s fixed size check stays 3003, the error of a
411
+ view whose size is known when the program is compiled), as Phoenix slices `&data[576..]` after checking the
412
+ account's size itself. `rbTreeAt(…).length` and `.capacity` read a tree made for the one read; anything else on a
413
+ tree or a raw array is done on a const bound to it. The checks a Rust original makes first (a size, its own error code) go before the view.
414
+ - lib-sokoban's trees (Phoenix's order books and trader seats): `rbTreeMutAt<K, V>(acct, offset, capacity, compare?)`,
415
+ every write the crate's own, so the account matches the original after every instruction:
416
+
417
+ ```ts
418
+ /** Phoenix's FIFOOrderId Ord: a bid's sequence number is stored inverted (top bit set); bids descend, asks ascend. */
419
+ function orderCmp(a: FIFOOrderId, b: FIFOOrderId): i8 {
420
+ if (a.order_sequence_number >> 63n === 1n) {
421
+ // a bid (the left key's side decides): `other.cmp(self)`
422
+ if (a.price_in_ticks !== b.price_in_ticks) return b.price_in_ticks < a.price_in_ticks ? -1n : 1n;
423
+ return b.order_sequence_number < a.order_sequence_number ? -1n : b.order_sequence_number > a.order_sequence_number ? 1n : 0n;
424
+ }
425
+ if (a.price_in_ticks !== b.price_in_ticks) return a.price_in_ticks < b.price_in_ticks ? -1n : 1n;
426
+ return a.order_sequence_number < b.order_sequence_number ? -1n : a.order_sequence_number > b.order_sequence_number ? 1n : 0n;
427
+ }
428
+ const bids = rbTreeMutAt<FIFOOrderId, FIFORestingOrder>(market, 880n, n, orderCmp);
429
+ const best = bids.min(); // the best bid, or null
430
+ if (best !== null && best.value.num_base_lots > 0n) best.value.num_base_lots -= fill;
431
+ const index = traders.addrOf(trader); // a seat's node index, 0 when absent
432
+ // a cancel: find the order, check it, then remove that node (no second search)
433
+ const at = bids.addrOf(orderId);
434
+ if (at !== 0n && bids.nodeAt(at).value.trader_index === traderIndex) bids.removeAt(at);
435
+ ```
436
+
437
+ The C runs sokoban's get_addr / _insert / _remove / rotations / allocator statement for statement, with the node
438
+ stride a constant (512 entries: get 166 CU, insert 493, remove 294, min 94; 4096: 215 / 595 / 355 / 112, against
439
+ 300 / 604 / 497 / 191 and 384 / 742 / 618 / 225 for lib-sokoban built with cargo-build-sbf). sokoban's panics are
440
+ Rust panics in the original; the tree reproduces each as solana-program up to 1.17 reports one (Phoenix's build):
441
+ the log line `panicked at '<message>', <file>:<line>:<column>`, then the runtime's abort ("SBF program panicked",
442
+ ProgramFailedToComplete), with sokoban's messages and source lines as Phoenix's binary holds them (`src/…`):
443
+ `initialize()` on an allocator that is not all zero, "Cannot reinitialize NodeAllocator" (src/node_allocator.rs:249:13);
444
+ an empty tree's insert with no room (capacity 0, or a damaged allocator), "Buffer is full, size N" (:269:17); and on
445
+ damaged registers only, "Nodes are not connected" (src/red_black_tree.rs:429:13), "assertion failed:
446
+ self.is_root(parent)" (:503:17), "assertion failed: self.is_leaf(max_left)" (:598:17), a size going below zero
447
+ ("attempt to subtract with overflow", src/node_allocator.rs:291:9). A node index outside 1..capacity, from `nodeAt`
448
+ or a damaged register, panics as Rust's `nodes[i - 1]` would ("index out of bounds: the len is N but the index is
449
+ I", src/node_allocator.rs:255:10; index 0, "attempt to subtract with overflow", :255:21: locations read from the
450
+ source, not from a binary), so a damaged tree never reads outside the account. A port makes the original's checks
451
+ in the original's order before the tree call, and these lines follow on their own. Iteration keeps its stack on the
452
+ program's stack (64 nodes, more than any red-black tree a u32 index can address holds on one path); a deeper,
453
+ damaged tree panics where the Rust's heap stack would grow. A walk costs about 34 compute units per node, a sum in
454
+ its body included (each node's index checked once, when the walk reaches it). A tree is a const of the function that makes it, not
455
+ a helper parameter (make it again in the helper from the account).
377
456
  - Writes as the original makes them: `export const NATIVE_ACCOUNT_WRITES = true` (anywhere in the program; opt-in, for
378
457
  native ports). A native program writes account data in place and the runtime judges afterwards: a read-only account
379
458
  whose data actually changed fails the instruction (`ReadonlyDataModified`, or an access violation at the write under
@@ -394,6 +473,23 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
394
473
  included; the flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position or
395
474
  another, is 2040 without it). `.lamports` on remaining accounts, `loadAccountMut`, CPI account metas and the checks of
396
475
  `Mut<…>` parameters stay as they are, and programs without the flag compile exactly as before.
476
+ - Accounts closed, reassigned and resized by hand, on remaining accounts and `AccountInfo` parameters:
477
+ `closeRaw(account, receiver)` is what Phoenix's Tombstone writes, in its order: `receiver.lamports +=
478
+ account.lamports` (checked), `account.lamports = 0`, `assign(&system_program::id())`, `realloc(0, false)`. Unlike
479
+ `close` the data is not zeroed first (a realloc to 0 drops it, and the runtime then accepts the new owner), so it
480
+ costs a few compute units whatever the account's size, and the account ends as the original's does (gone, its
481
+ lamports in the receiver; test/language/native-close.test.ts compares it with Phoenix's own Tombstone).
482
+ `assignOwner(account, owner)` is `AccountInfo::assign` (the runtime accepts it for a writable account of this program
483
+ whose data is empty or zeroed), and `resizeAccount(account, size)` also takes a remaining account (`realloc(size,
484
+ true)`: new bytes zeroed, at most 10 KiB past the size it had when the instruction started, 3016; that size is the one
485
+ the entrypoint records in the account's record, as solana_program 1.14's does, only in programs that resize a
486
+ remaining account). A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node
487
+ or a struct read through one) is a compile error to use after it: its bounds were checked against the old length, so
488
+ take the view again. Without `NATIVE_ACCOUNT_WRITES` the accounts are checked as other writes the compiler cannot see
489
+ are: writable (3006; a parameter must be `Mut<AccountInfo>`), passed once (2040), the closed or reassigned account
490
+ this program's (3007), and not closed into itself (2040). With it nothing is checked and the runtime judges, as for
491
+ the original (`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`),
492
+ and plain `AccountInfo` parameters are enough.
397
493
  - Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
398
494
  `ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
399
495
  built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
@@ -403,10 +499,65 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
403
499
  runtime's `abort` syscall, which logs "SBF program panicked" with no location; `const PANIC_ON_OVERFLOW = true`
404
500
  makes arithmetic overflow and division by zero panic as `checked_*().unwrap()` does instead of failing with 5100 /
405
501
  5101.
502
+ - Panics as an older solana-program writes them: `export const PANIC_STYLE = "solana-1.14"` (a program built with
503
+ solana-program 1.14 to 1.17, whose rustc formats a panic before 1.73 did: Phoenix v1) makes `panic(message,
504
+ location)` log `panicked at '<message>', <location>` and then abort, so the runtime's last line is "SBF program
505
+ panicked" with no location, as that panic handler leaves it (`panic(null, …)` is refused there: the handler always
506
+ logs; without a location the TypeScript line and column are used). `PANIC_ON_OVERFLOW`'s panics abort too.
507
+ - Overflow panics with Rust's message and location: `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
508
+ checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
509
+ "attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder
510
+ with a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow" and "attempt to shift
511
+ left / right with overflow" for a shift amount past the width), logged as `panic` logs (`PANIC_STYLE` above, else
512
+ the message and sol_panic_ at the location), instead of failing with 5100 / 5101; with or without
513
+ `PANIC_ON_OVERFLOW`, which applies outside it. Rust reports the location of the expression the operator belongs
514
+ to, so the wrapper goes around that expression: only the operators written inside it take the location (not those
515
+ of the helpers it calls), an inner `panicsAt` gives its operators their own (`panicsAt(A, x + panicsAt(B, y * z))`),
516
+ and as a statement it takes an assignment, `panicsAt(LOC, total += fee);`. A Rust newtype's operator panics at its
517
+ `impl` (Phoenix's `QuoteLots + QuoteLots` at the macro line in quantities.rs, wherever the addition is written): give
518
+ the port a helper, `function addQuoteLots(a: u64, b: u64): u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`. The
519
+ bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks them
520
+ differently, or with other messages).
521
+ test/language/rust-panics.test.ts checks the lines against the Phoenix binary's own panics.
406
522
  - Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
407
- "Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`);
523
+ "Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`); `null`
524
+ logs no failure line at all, as a native program returns an error its own checks already explained (Phoenix): the
525
+ program's errors and codes its helpers return (`ERROR_LOG_PREFIX = null`), built-in ProgramErrors and `programAt`'s
526
+ check (`PROGRAM_ERROR_LOG_PREFIX = null`), each about 110 CU cheaper than a logged one (constraint errors and the
527
+ compiler's own checks still log);
408
528
  `logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
409
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
529
+ `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address);
530
+ `logComputeUnits()` is `sol_log_compute_units()`: the runtime writes "Program consumption: N units remaining" at
531
+ that point, as for the original (Phoenix's cancel and withdraw paths log it).
532
+ - Byte strings built by hand (instruction data for a self-CPI, a log record, return data) in a `FixedVec<u8, N>`, a
533
+ local list or one in account data: `buf.pushLE(x)` appends an integer's little-endian bytes at its width (u8 … u128,
534
+ i8 … i128; a literal needs one: `buf.pushLE<u16>(1n)` or `buf.pushLE(u16(1n))`), `buf.pushKey(key)` a Pubkey's 32
535
+ bytes, `buf.pushBorsh(value)` a value's Borsh encoding with the codecs `invoke`, events and `storeBorsh` use (a
536
+ struct, or an object literal given its type, `buf.pushBorsh<Header>({ … })`; a data enum, its tag then the variant's
537
+ fields; a FixedArray; a list, its u32 count then the elements; integers, booleans, Pubkeys, strings and Options; a
538
+ data-enum literal of a fixed-size variant costs what the same bytes cost with `pushLE`: its fields evaluated in
539
+ order, then one room check and a store of each),
540
+ `buf.setLE(offset, x)` (or `setLE<u16>(offset, x)`) overwrites bytes within the length, as Rust's
541
+ `data[a..b].copy_from_slice(…)`, and `buf.truncate(n)` keeps the first `n`. Past the room (or, for `setLE` and
542
+ `truncate`, past the length) fails with 5104 and the length does not move. Phoenix's event recorder, which the test
543
+ checks byte for byte against the Phoenix binary's batches:
544
+
545
+ ```ts
546
+ const data: FixedVec<u8, 1280> = fixedVec([15n]); // PhoenixInstruction::Log
547
+ data.pushBorsh<PhoenixMarketEvent>({ kind: "Header", instruction, sequenceNumber, timestamp: now(), slot: currentSlot(), market, signer, totalEvents: 0n });
548
+ // … for each event, the batch sent first if it would not fit: data.pushBorsh<PhoenixMarketEvent>({ kind: "Fill", index, … });
549
+ data.setLE(91n, u16(batchSize)); // total_events of this batch
550
+ invokeInstruction(programId(), metas, data, rest, ["log", bump]);
551
+ data.truncate(93n); // back to the header
552
+ ```
553
+ - Return data as the original sets it: `setReturnData(bytes)` is `set_return_data(&bytes)`, the bytes as they are, from
554
+ the `@fallback` entry, a helper or a void instruction (Phoenix's Borsh `Vec<FIFOOrderId>` of the orders that rested,
555
+ built in a local `FixedVec<u8, N>`). `bytes` is a list of u8: a local FixedVec, a Vec or FixedVec in account data, or
556
+ the instruction data or a slice of it. The last call wins and an empty list clears it; a CPI made afterwards replaces
557
+ it with the callee's (call it after the last CPI, as Rust must). More than 1024 bytes fails as the Rust call does: the
558
+ runtime refuses it ("Return data too large (1025 > 1024)"). An instruction that returns a value cannot call it (a
559
+ compile error: its return value is its return data); a helper it calls may, and the instruction's return value, set
560
+ last, replaces what the helper set.
410
561
 
411
562
  ## Not supported yet
412
563
 
@@ -444,7 +595,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
444
595
  | 2016 / 2017 / 2018 | mint authority / freeze authority / decimals mismatch (2018: an existing mint `createIfNeeded` found) |
445
596
  | 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
446
597
  | 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…) |
447
- | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
598
+ | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount); also `close(a, b)` in a helper given one account for both |
448
599
  | 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` |
449
600
  | 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
450
601
  | 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
@@ -647,24 +798,33 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
647
798
 
648
799
  | Command | What it does |
649
800
  | --- | --- |
650
- | `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. |
801
+ | `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. |
651
802
  | `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. |
652
- | `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. |
653
- | `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. |
654
- | `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. |
655
- | `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). |
803
+ | `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. |
804
+ | `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. |
805
+ | `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. |
806
+ | `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). |
656
807
  | `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. |
657
808
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
658
- | `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. |
659
- | `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`). |
809
+ | `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). |
810
+ | `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. |
811
+ | `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. |
660
812
  | `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. |
661
813
  | `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`). |
662
814
  | `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). |
663
- | `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. |
815
+ | `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). |
664
816
  | `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). |
665
817
  | `typesol help <command>` | Same as `typesol <command> --help`. |
666
818
  | `typesol --version` | Print the version. |
667
819
 
820
+ `clone`, `client --address`, `verify` and `idl publish` give up on an RPC request after 30 seconds
821
+ (`TYPESOL_RPC_TIMEOUT=<seconds>` changes it) and, like `doctor` and `deploy`, name only the RPC's host and the cause
822
+ when one fails (an RPC URL can carry an API key). A `--config` file that does not exist is a usage error everywhere.
823
+
824
+ Builds (`build`, `deploy`, `verify`, `typesol/testing`) compare the active clang with the one the release is tested
825
+ with (`TESTED_TOOLCHAIN` in `typesol/compiler`: Agave 3.1.10, platform-tools v1.52): another one gets one warning per
826
+ process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `warn` is the default.
827
+
668
828
  ## typesol.json
669
829
 
670
830
  ```json
@@ -778,6 +938,11 @@ integers and floats are `number`, `Pubkey` is kit's `Address`, `string` and `Fix
778
938
  as in the program. Names are camelCase. For Anchor IDLs, data enums use `__kind`, as Codama-generated clients do. The
779
939
  file uses no TypeScript-only syntax (no `enum`), so it also runs under Node's type stripping.
780
940
 
941
+ Anchor IDLs can also hold types a TypeSOL program does not: `u256`/`i256` are `bigint` (32 bytes, little-endian), and
942
+ `Option<Option<T>>` is `Option<T> | null` with kit's `Option` inside, so the three values stay apart: `null` is None,
943
+ `none()` is Some(None) and `some(x)` (or `x`) is Some(Some(x)). A type that holds itself through a Vec or an Option
944
+ (`enum Shape { Dot, Rec { kids: Vec<Shape> } }`) is encoded and decoded to any depth.
945
+
781
946
  ## Safety
782
947
 
783
948
  An IDL can come from anywhere, so `typesol client` refuses one whose names are not identifiers, whose discriminators or
@@ -791,9 +956,12 @@ Anchor IDLs are refused with a hint to convert them (`anchor idl convert`).
791
956
  `Program data:` line only while this program is the innermost one running, and `eventsOf` reads only the `emitCpi`
792
957
  inner instructions that call this program (it needs `tx.transaction`'s account keys for that). `parseCpiEvents(data)`
793
958
  on its own does not check the program: give it this program's inner instructions only.
794
- - **Not filled in automatically** (pass them): PDAs seeded from struct fields (Anchor cannot seed with them either),
795
- PDAs whose program is another account's field, and a PDA seeded from its own fields (derive it with its `pdas`
796
- helper from the values). `typesol client` prints a note for each.
959
+ - **Not filled in by the builder** (pass them): PDAs seeded from a field of another account's data (`state.owner`;
960
+ `resolve` reads the account and derives them), PDAs whose program is another account's field, and a PDA seeded from
961
+ its own fields (derive it with its `pdas` helper from the values). `typesol client` prints a note for each. PDAs
962
+ seeded from a field of a struct argument, at any depth (`params.inner.id`), are filled in.
963
+ - **Left out, with a note**: instructions, accounts and types using `Option<Option<Option<T>>>` or deeper, and types
964
+ the client cannot express (listed by `typesol client`).
797
965
  - **Anchor IDLs**: zero-copy (`bytemuck`) accounts decode and encode at their `#[repr(C)]` offsets as the program sees
798
966
  them on SBF (padding included; `packed` and `align` honored; 128-bit integers align to 8). Generic types become one
799
967
  type per use with concrete arguments (`Pair<u64, 2>` is `PairU64N2`). Left out, with a note: zero-copy types with
@@ -817,8 +985,9 @@ original side by side, the checks run against it and its cost, see [Case study:
817
985
  ```sh
818
986
  anchor build # in the Anchor project: target/idl/my_program.json
819
987
  npx @typesol/cli init my-program && cd my-program
988
+ npm install # the project's own TypeSOL, run below as npx --no-install typesol
820
989
  rm programs/my_program.ts tests/my_program.test.ts # the counter template's program and test
821
- npx typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
990
+ npx --no-install typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
822
991
  ```
823
992
 
824
993
  `typesol port` writes the account structs, enums, errors and one function per instruction with its accounts and
@@ -947,6 +1116,7 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
947
1116
  | a closure `\|x\| x + offset`, `let fee = \|x: u64\| x / 100;` | `const f = (x: u64): u64 => x + offset` (it may read and write the function's variables), `const fee = (x: u64): u64 => x / 100n;` |
948
1117
  | `x.unwrap_or(d)` | `x ?? d` |
949
1118
  | `fn max<T: PartialOrd>(a: T, b: T) -> T` | `function max<T extends bigint>(a: T, b: T): T` (one copy per type used) |
1119
+ | `fn add_event(rec: &mut EventRecorder, e: &Event)` | `function addEvent(rec: Inout<EventRecorder>, e: Event): void` (structs, FixedArray and FixedVec; a `&mut u64` becomes a returned value or a struct field) |
950
1120
 
951
1121
  ## Tooling
952
1122
 
@@ -970,6 +1140,18 @@ and next to `cargo-build-sbf` on PATH; set `TYPESOL_SBF_SDK` to a `platform-tool
970
1140
 
971
1141
  **"platform-tools missing" / "no SBPF v2 libraries"** — `cargo-build-sbf --force-tools-install`.
972
1142
 
1143
+ **"warning: this build uses clang … TypeSOL is tested with clang 20.1.7-rust-dev …"** — the active platform-tools are
1144
+ 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
1145
+ generates is only checked against that clang: another one can compile it to other bytes, and what the C relies on
1146
+ includes backend details (how the SBF backend passes struct arguments was behind a defect fixed after 0.43.0). Install the tested ones with
1147
+ `cargo-build-sbf --install-only --force-tools-install --tools-version v1.52`; `typesol doctor` shows which are active.
1148
+ In CI, `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) turns the warning into an error.
1149
+
1150
+ **`typesol verify` says MISMATCH** — first make sure the same sources (imports included), TypeSOL version and SBPF
1151
+ version are used. Then the toolchain: verify prints the rebuild's clang and platform-tools, and the deployed build's
1152
+ when a `<name>.build.json` describes the deployed bytes (`--manifest <file>`, one next to a given `.so`, or the local
1153
+ build's). A program on chain carries no such record, so keep the build manifest of every deployment.
1154
+
973
1155
  **Windows** — not tested; use WSL2 with the Linux Agave CLI.
974
1156
 
975
1157
  **Node errors such as `ERR_UNKNOWN_FILE_EXTENSION` or `ERR_REQUIRE_ESM`** — use Node.js 22.12 or newer.
@@ -1001,8 +1183,11 @@ uses. Publishing works on mainnet-beta. The error shows the failing transaction'
1001
1183
  SBPF v0 (the default) every function gets a fixed 4 KiB stack frame, and going past it corrupts memory, so the build
1002
1184
  refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`) grow frames dynamically, so this limit does not apply there. Large structs and arrays copied into typed
1003
1185
  locals (`const q: Big = acct.big`) are the usual cause: bind them without a type (`const q = acct.big`, a reference
1004
- into the account data) or move the work into helpers. Helpers are often inlined into their instruction, so their
1005
- locals count toward its frame.
1186
+ into the account data). The message lists the biggest locals (clang's frame layout: a local's name and the source
1187
+ line near it; the locals of an inlined helper show as unnamed, with the helpers' locals that may be them). Helpers are
1188
+ often inlined into their instruction, so their locals count toward its frame: mark one `/** @noinline */` to give it a
1189
+ 4 KiB frame of its own (a few compute units per call), or declare a large local list or struct of an instruction
1190
+ `/** @heap */` to keep it on the heap (about 18 CU for the allocation).
1006
1191
 
1007
1192
  <!-- docs/mainnet.md -->
1008
1193
 
@@ -1010,9 +1195,18 @@ locals count toward its frame.
1010
1195
 
1011
1196
  From an empty directory to a program on Solana mainnet-beta: create, test, deploy, publish the IDL, then check that
1012
1197
  the deployed binary is the one your source builds. The program here is the counter that `typesol init` creates
1013
- (13.2 KiB); any TypeSOL project works the same way.
1198
+ (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
1199
+ slightly); any TypeSOL project works the same way.
1200
+
1201
+ You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Quick start).
1014
1202
 
1015
- You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Requirements).
1203
+ **The toolchain you deploy with.** The binary is what the platform-tools' clang makes of the generated C, so the
1204
+ toolchain is part of what you trust. Deploy with the one TypeSOL is tested with (Agave 3.1.10, platform-tools v1.52;
1205
+ `typesol doctor` says whether yours is, and `typesol deploy --toolchain-strict` refuses another). Keep
1206
+ `target/my_app/my_app.build.json` with each deployment, next to the commit you deployed: it records the TypeSOL,
1207
+ TypeScript, clang and platform-tools versions and the host, and the deployed bytes' sha256. Step 6's `verify` matches
1208
+ only when it rebuilds with the same TypeSOL version and toolchain, and on a mismatch `--manifest` with that file shows
1209
+ what differs.
1016
1210
 
1017
1211
  ## 1. Create and test
1018
1212
 
@@ -1029,7 +1223,7 @@ Write your program in `programs/my_app.ts` and keep the tests passing before you
1029
1223
  ## 2. Build
1030
1224
 
1031
1225
  ```sh
1032
- npx typesol build
1226
+ npx --no-install typesol build
1033
1227
  ```
1034
1228
 
1035
1229
  This writes `target/my_app/`: the program (`my_app.so`), its Anchor IDL (`my_app.json`), a TypeScript client
@@ -1054,8 +1248,10 @@ ever close the program:
1054
1248
  solana rent $(wc -c < target/my_app/my_app.so)
1055
1249
  ```
1056
1250
 
1057
- The counter needs 0.069 SOL of rent. During the deploy the program is first written to a buffer account that holds
1058
- the same amount again; it is returned when the deploy finishes. Fund about twice the rent plus 0.01 SOL for fees.
1251
+ For the counter that is about 0.080 SOL (rent is (128 + size) × 6,960 lamports at the current rate: 80,234,880
1252
+ lamports for 11,400 bytes; the program data account holds 45 bytes more). During the deploy the program is first
1253
+ written to a buffer account that holds the same amount again; it is returned when the deploy finishes. Fund about
1254
+ twice the rent plus 0.01 SOL for fees: 0.17 SOL for the counter.
1059
1255
 
1060
1256
  The public mainnet RPC is rate-limited; for deploys, set `--url` (or `solana config set --url`) to your RPC
1061
1257
  provider's endpoint.
@@ -1063,8 +1259,8 @@ provider's endpoint.
1063
1259
  ## 4. Deploy
1064
1260
 
1065
1261
  ```sh
1066
- npx typesol deploy --dry-run # builds and prints the solana command it will run
1067
- npx typesol deploy
1262
+ npx --no-install typesol deploy --dry-run # builds and prints the solana command it will run
1263
+ npx --no-install typesol deploy
1068
1264
  ```
1069
1265
 
1070
1266
  It runs `solana program deploy` at the address in `target/deploy/my_app-keypair.json`, with your wallet as payer and
@@ -1076,7 +1272,7 @@ with `solana program close <buffer address>`, or list yours with `solana program
1076
1272
  ## 5. Publish the IDL
1077
1273
 
1078
1274
  ```sh
1079
- npx typesol idl publish
1275
+ npx --no-install typesol idl publish
1080
1276
  ```
1081
1277
 
1082
1278
  It writes the IDL to the Program Metadata program, signed by the upgrade authority, where Anchor clients and
@@ -1085,12 +1281,12 @@ explorers look for it. It costs a few thousandths of a SOL of rent.
1085
1281
  ## 6. Verify
1086
1282
 
1087
1283
  ```sh
1088
- npx typesol verify my_app
1284
+ npx --no-install typesol verify my_app
1089
1285
  ```
1090
1286
 
1091
1287
  `verify` rebuilds the program from `programs/my_app.ts`, reads the deployed one at the address in `typesol.json` from
1092
1288
  the cluster in your Solana CLI config, and compares the bytes. `match` means anyone with your source and the same
1093
- TypeSOL version gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
1289
+ TypeSOL version and toolchain gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
1094
1290
  published in step 5. Anyone can run it against your program with `--address <program id> --url mainnet-beta`.
1095
1291
 
1096
1292
  ## 7. Call it
@@ -1121,7 +1317,7 @@ auditors, [SECURITY.md](../SECURITY.md) how to report a problem.
1121
1317
  | --- | --- |
1122
1318
  | The program's author | the program's logic: what it allows, to whom, for how much |
1123
1319
  | TypeSOL (this repository) | that the binary does what the source and these guarantees say, and nothing an attacker can steer beyond it |
1124
- | The toolchain | the TypeScript compiler API (parsing, types), Agave platform-tools (clang, lld), Node.js |
1320
+ | 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 |
1125
1321
  | The Solana runtime | account ownership and signer flags as passed, the loader's account serialization, CPI privilege rules, sysvars |
1126
1322
 
1127
1323
  Everything a transaction carries is attacker-controlled: the instruction data, which accounts are passed in which
@@ -1159,7 +1355,8 @@ Each holds for every instruction of every program the compiler accepts. A break
1159
1355
  7. **Bounds.** Every index into an array, Vec, FixedVec or remaining-account list is checked (5104); a
1160
1356
  growable Vec's stored length is checked against the account's size before it is used (3003).
1161
1357
  8. **Account creation.** `create` / `createIfNeeded` is a top-level statement, and the account cannot be read or
1162
- written before it (compile error). Creation refuses an account that already exists (3000), and an address someone
1358
+ written before it (compile error). Creation refuses an account that already exists (the System Program's
1359
+ own error, custom 0; `initAccount<T>` over an account already holding a T is 3000), and an address someone
1163
1360
  pre-funded still gets created. `createIfNeeded` on an existing account re-derives the canonical PDA and checks
1164
1361
  owner, discriminator and size (token accounts: mint and owner; mints: decimals, authorities and the extensions it
1165
1362
  names). A `Migrate<From, To>` account is checked as an existing `From`; `migrate(…)` is a top-level statement every
@@ -1167,14 +1364,18 @@ Each holds for every instruction of every program the compiler accepts. A break
1167
1364
  errors).
1168
1365
  9. **Writes through references.** A place is never written after the code that computes its value may have moved it:
1169
1366
  replacing or resizing what a live reference points into is a compile error, as is writing a Vec element with a
1170
- right side that may resize the Vec.
1367
+ right side that may resize the Vec. A helper given a writable struct account may replace anything in it, however
1368
+ the account is named at the call (a parameter, an account group's field, a struct loaded with `loadAccountMut`): a
1369
+ reference into it read after the call is a compile error. A helper that can write gets its Pubkey, Option and
1370
+ string arguments as they were at the call (a copy unless nothing it is given reaches them), and a closed account
1371
+ is not used after `close()` (compile error).
1171
1372
  10. **Remaining accounts.** Writing one (`.lamports`, `loadAccountMut`) checks it is writable (3006) and not another
1172
1373
  account of the instruction (2040); `loadAccountMut` loads a given account once per instruction (2040);
1173
1374
  `loadAccount<T>` checks owner, discriminator and size, and validates the data as instruction arguments are.
1174
1375
  11. **Growth.** An account grows by at most 10 KiB per instruction (3016), the payer is a `Mut<Signer>`, new bytes are
1175
1376
  zero and the new rent is paid; shrinking keeps the lamports in the account.
1176
1377
  12. **CPIs.** A program signs only for its own PDAs (the runtime enforces it; the seeds are those written in the
1177
- source). `invoke` marks an account writable or signer only when the parameter is `Mut` / `Signer` or the program
1378
+ source, with the values they had where the list was written, also for a named list or one given to a helper). `invoke` marks an account writable or signer only when the parameter is `Mut` / `Signer` or the program
1178
1379
  signs for it; remaining accounts keep the flags they were passed with, or are checked for the role requested.
1179
1380
  `invokeInstruction` is the exception by design: its program, account flags and data come from values (stored in
1180
1381
  account data or passed in), so the compiler cannot check them; the runtime does, refusing any account the
@@ -1218,10 +1419,37 @@ Each holds for every instruction of every program the compiler accepts. A break
1218
1419
  - Arithmetic overflow returns an error code (5100) in every build; Anchor aborts the program, and only when
1219
1420
  overflow checks are enabled.
1220
1421
 
1422
+ ## Review of 0.43.0 (2026-11-11)
1423
+
1424
+ An internal review of 0.43.0 found that some of the guarantees above did not hold in every case; the defects are
1425
+ listed in [audit.md](audit.md#0430-2026-11-11) and fixed in 0.44.0. Programs built with 0.43.0 or
1426
+ earlier should be rebuilt with it and redeployed: the fixes change the binary of programs that have a helper
1427
+ 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
1428
+ binary, 41 to another).
1429
+
1430
+ The defect that can break an authorization check is the first: a Pubkey, Option, string or u256 argument of a
1431
+ helper was not a copy. A program was exposed where all of these hold:
1432
+
1433
+ - a helper takes a parameter of one of those types and also an account it writes (or remaining accounts, or an
1434
+ `Inout` place);
1435
+ - a call passes that parameter a field of the same account (`rotate(v, v.admin, caller)`), or a value stored in it;
1436
+ - the helper reads the parameter after writing the field (`v.admin = v.pending`, then a check on `admin`): it read
1437
+ the new value;
1438
+ - the helper was not inlined. A `/** @noinline */` helper never is; for the others it was clang's choice, which the
1439
+ source does not show, so count every such call as exposed.
1440
+
1441
+ Each of the other defects needs the construct it names: a seed list bound to a name, given to a helper or written
1442
+ beside an argument with side effects; a reference held across a helper that is given an account-group field or a
1443
+ loaded account; Borsh input with an Option of a struct that holds an Option (a bounded read past the input, no
1444
+ write); a closure or callback that changes a local read before it; a string viewing an `Inout` place; `close()` into
1445
+ the account itself, `Dup<…>` on a closed account, or an account used after `close()`. A program without them was not
1446
+ exposed to them.
1447
+
1221
1448
  ## Status
1222
1449
 
1223
- The compiler and runtime have had internal security reviews; the findings of the latest are fixed in 0.25.0
1224
- (CHANGELOG). The releases after it have not had such a review yet, and there has been no external audit: see
1450
+ The compiler and runtime have had internal security reviews, the latest of 0.43.0 (above); its findings are fixed in
1451
+ 0.44.0. It was an internal review, not an independent audit, and it did not cover the Metaplex and
1452
+ token CPI wrappers' emitters, the oracles, SBPF v1/v2 builds or Windows. There has been no external audit: see
1225
1453
  [audit.md](audit.md).
1226
1454
 
1227
1455
  <!-- docs/ai.md -->
@@ -1251,7 +1479,8 @@ own project notes below them in AGENTS.md.
1251
1479
  ([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
1252
1480
  and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
1253
1481
  in one file, to paste into a chat or give to a model as context. Both also ship in the npm package
1254
- (`node_modules/typesol/llms-full.txt`).
1482
+ (`node_modules/typesol/llms-full.txt` in a project `typesol init` created, which installs `@typesol/cli` under the
1483
+ name `typesol`; `node_modules/@typesol/cli/llms-full.txt` where it is installed under its own name).
1255
1484
 
1256
1485
  ## Errors an agent can fix by itself
1257
1486
 
@@ -1262,13 +1491,17 @@ in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on ch
1262
1491
  ## The MCP server
1263
1492
 
1264
1493
  `typesol mcp` serves the [Model Context Protocol](https://modelcontextprotocol.io) on stdio. `typesol init` writes
1265
- `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx typesol mcp`. Other clients take the
1266
- same command:
1494
+ `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx --no-install typesol mcp`: the
1495
+ project's own copy, after `npm install`. `--no-install` matters: `typesol` is not the npm package's name, and without
1496
+ it npx would fetch whatever package is published as `typesol` when the project's copy is missing. Other clients take
1497
+ the same command, run in the project directory:
1267
1498
 
1268
1499
  ```json
1269
- { "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
1500
+ { "mcpServers": { "typesol": { "command": "npx", "args": ["--no-install", "typesol", "mcp"] } } }
1270
1501
  ```
1271
1502
 
1503
+ Outside a project, start it from the published package by its full name: `npx -y @typesol/cli mcp`.
1504
+
1272
1505
  | Tool | What it does |
1273
1506
  | --- | --- |
1274
1507
  | `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
@@ -1276,7 +1509,7 @@ same command:
1276
1509
  | `docs` | searches the docs and returns the best-matching sections |
1277
1510
  | `rules` | the rules above |
1278
1511
 
1279
- Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
1512
+ Building and testing stay in the shell (`npm test`, `npx --no-install typesol build`): they need the platform-tools and write
1280
1513
  files, which an agent should do in the open.
1281
1514
 
1282
1515
  <!-- docs/stability.md -->
@@ -1294,8 +1527,9 @@ From 1.0 on, within a major version:
1294
1527
 
1295
1528
  - **Sources keep compiling.** A program that compiles with 1.x compiles with every later 1.y, to a program with the same
1296
1529
  account layouts, IDL, instruction and account discriminators and error codes. New releases add; they do not take away.
1297
- - **Binaries are reproducible and only change for a reason.** A release that changes the binary of a program that uses
1298
- none of its new features says so, with the release manifest's diff (`binary-diff.txt`) as the evidence.
1530
+ - **Binaries are reproducible and only change for a reason.** With the same TypeSOL release and the toolchain it is
1531
+ tested with, a source builds to the same bytes. A release that changes the binary of a program that uses none of
1532
+ its new features says so, with the release manifest's diff (`binary-diff.txt`) as the evidence.
1299
1533
  - **The checks stay.** No check a program gets from its parameter types (owner, discriminator, signer, writability,
1300
1534
  aliasing, checked arithmetic, constraints) is removed or weakened.
1301
1535
  - **The tools keep their interfaces**: `typesol build`, `test` (via `typesol/testing`), `check --json`, `deploy`,
@@ -1314,6 +1548,24 @@ Meant to stay as they are; a change before 1.0 would be a breaking change listed
1314
1548
  - CPIs: System, SPL Token, Token-2022, Associated Token, Memo, generic `invoke` with PDA signing.
1315
1549
  - Layouts: account data (Anchor's discriminator and fixed or `@layout borsh` layout), the IDL, the client.
1316
1550
 
1551
+ ## What a release gives you now
1552
+
1553
+ - **The npm package is the one that was checked.** From 0.43.0 on, `releases/<version>.json` in the repository holds
1554
+ the published tarball's shasum and integrity and every file's sha256, packed from a clean export of the release tag
1555
+ after install, build and lint. `npm pack` is reproducible here, so anyone can pack the tag again and compare, or
1556
+ compare the registry with `node scripts/release-check.ts <version> --verify --registry`
1557
+ ([docs/testing.md](testing.md#the-npm-tarball)).
1558
+ - **The tests cover one toolchain.** Each release declares the Agave and platform-tools it is tested with
1559
+ (`TESTED_TOOLCHAIN`, exported from `typesol/compiler`; Agave 3.1.10 and platform-tools v1.52 now). A binary built with
1560
+ another clang is outside what the tests cover: `typesol build` and `deploy` warn once, `--toolchain-strict` (or
1561
+ `TYPESOL_TOOLCHAIN=strict`) refuses it, and `typesol doctor` shows which one is active.
1562
+ - **A build says what made it.** `<name>.build.json` records the TypeSOL, TypeScript, clang and platform-tools versions,
1563
+ the host, the SBPF version and the sha256 of every source and of the binary. `typesol verify` uses it to say, on a
1564
+ mismatch, whether the toolchains differ. A program on chain records none of this: keep the file with the deployment.
1565
+ - **Fixes come as patches of the latest minor.** From 0.44.0 on, a release that only fixes soundness or security
1566
+ defects is a patch (0.44.1, …) with no new language surface, and its notes carry the binary diff against the
1567
+ previous release ([SECURITY.md](../SECURITY.md#fix-releases)). Older minors are not maintained.
1568
+
1317
1569
  ## Experimental
1318
1570
 
1319
1571
  Useful today, but may still change before 1.0 (each change listed in the CHANGELOG):
@@ -1323,13 +1575,33 @@ Useful today, but may still change before 1.0 (each change listed in the CHANGEL
1323
1575
  `createProgramAddress`.
1324
1576
  - `loadBorsh` / `storeBorsh` (0.42.0): a native program's Borsh accounts read into a local struct and written back.
1325
1577
  - `BigVec<T>` (0.42.0): SPL's `big_vec`, a list over the rest of a native account.
1578
+ - Views at run-time offsets (0.43.0): `loadRawAt` / `loadRawMutAt`, `rawArrayAt` / `rawArrayMutAt`; a read-only
1579
+ view read where it is made (`loadRaw<T>(a).field`, `rbTreeAt(…).length`), and the owner check's cache the views share.
1580
+ - The built-in RedBlackTree (0.43.0): `rbTreeAt` / `rbTreeMutAt`, lib-sokoban 0.3's byte layout and algorithms,
1581
+ its panics in solana-program 1.14–1.17's format, `removeAt(index)` (what it gives for a node in no tree may change).
1326
1582
  - `panic(null, location)` (no log line) and `abort()` (Rust's abort, "SBF program panicked") (0.42.0).
1583
+ - Failures without a log line (0.43.0): `ERROR_LOG_PREFIX = null` / `PROGRAM_ERROR_LOG_PREFIX = null`.
1584
+ - `findProgramAddressWithBump` (0.43.0), with `const [address, bump] = …` its only array destructuring.
1585
+ - Plain type aliases (0.43.0): `type Price = u64`, replaced by the type they name.
1586
+ - File-local structs (0.43.0): `interface Pair { … }` without `export`, for helpers and locals, out of the IDL.
1587
+ - Constant expressions (0.43.0): top-level integer constants folded from literals and earlier constants, a typed
1588
+ one computed in its type.
1589
+ - Comma-separated `for` updates and initializers (0.43.0).
1590
+ - Stack room (0.43.0): `/** @noinline */` helpers and `/** @heap */` locals.
1327
1591
  - Local `FixedVec` / `FixedArray` lists of structs, `FixedVec.pushAll`, the instruction data as a list (`slice`,
1328
- `InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0).
1592
+ `InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0); local FixedVecs given for read-only
1593
+ `FixedVec<T, N>` / `Vec<T>` helper parameters (0.43.0).
1329
1594
  - `epochRewards()` and `EpochRewards` (0.42.0): the EpochRewards sysvar through its syscall.
1330
1595
  - `NATIVE_ACCOUNT_WRITES` (0.42.0): opt-in native write semantics for `loadRawMut`, `storeBorsh` and BigVec writes
1331
1596
  (writability and aliasing left to the runtime). It drops checks a program would otherwise get, so it stays outside
1332
1597
  "the checks stay" promise above: it only applies to programs that declare it.
1598
+ - `Inout<T>` helper parameters (0.43.0): a helper that changes a struct, FixedArray or FixedVec of the caller's
1599
+ that is not an account (a local, a `loadBorsh` local, a field of a `loadRawMut` view, a list element), with the
1600
+ aliasing rules at each call. It settles the open edge of helpers taking a writable struct that is not an account,
1601
+ which were refused; the rules (what counts as overlapping, which places may move) may still be refined.
1602
+ - For native ports (0.43.0): `setReturnData` and `logComputeUnits` in a native entry; `closeRaw`, `assignOwner`
1603
+ and `resizeAccount` on remaining accounts; the byte builders of `FixedVec<u8, N>` (`pushLE`, `pushKey`, `pushBorsh`,
1604
+ `setLE`, `truncate`); `PANIC_STYLE = "solana-1.14"` and `panicsAt(location, expression)`.
1333
1605
  - Metaplex CPIs (Token Metadata, Core, Bubblegum), oracles (Pyth, Switchboard), the Stake program.
1334
1606
  - `programAt<P>` / `sysvarAt<S>` and remaining accounts in the typed CPIs (System, Token, ATA, Memo, Stake); a ternary
1335
1607
  between remaining accounts and `AccountInfo` parameters (0.42.0).
@@ -1344,7 +1616,6 @@ Useful today, but may still change before 1.0 (each change listed in the CHANGEL
1344
1616
  - **An external audit** of the compiler and runtime ([audit package](audit.md)), its findings fixed and published.
1345
1617
  - **Settle the open edges**, each either supported or refused with a clear error:
1346
1618
  - a struct holding a FixedVec as both an argument and account data (two layouts, one IDL type);
1347
- - helpers that take a writable struct which is not an account (a `loadRaw` view, a local), now refused;
1348
1619
  - `require` with an error code computed at run time that is 0: fails as an overflow (5100) today, where a native
1349
1620
  program returns CUSTOM_ZERO;
1350
1621
  - which experimental parts above become stable, and which stay outside the 1.0 promise.