@typesol/cli 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.md +9 -5
  3. package/dist/ai.d.ts +10 -0
  4. package/dist/ai.js +43 -0
  5. package/dist/cli.js +15 -1
  6. package/dist/compiler/analyze.js +44 -3
  7. package/dist/compiler/diagnostics.d.ts +2 -0
  8. package/dist/compiler/emit/base.d.ts +40 -7
  9. package/dist/compiler/emit/base.js +33 -0
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +102 -2
  13. package/dist/compiler/emit/calls.js +671 -50
  14. package/dist/compiler/emit/cpi-core.d.ts +9 -3
  15. package/dist/compiler/emit/cpi-core.js +12 -7
  16. package/dist/compiler/emit/cpi.js +8 -14
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +51 -2
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +7 -2
  24. package/dist/compiler/emit/shared.d.ts +35 -1
  25. package/dist/compiler/emit/shared.js +9 -1
  26. package/dist/compiler/emit/statements.d.ts +31 -0
  27. package/dist/compiler/emit/statements.js +272 -14
  28. package/dist/compiler/emit/storage.d.ts +27 -1
  29. package/dist/compiler/emit/storage.js +124 -11
  30. package/dist/compiler/emit/token.d.ts +11 -8
  31. package/dist/compiler/emit/token.js +233 -104
  32. package/dist/compiler/hints.js +6 -0
  33. package/dist/compiler/model.d.ts +20 -1
  34. package/dist/compiler/model.js +5 -0
  35. package/dist/testing-stake.d.ts +216 -0
  36. package/dist/testing-stake.js +526 -0
  37. package/dist/testing.d.ts +1 -0
  38. package/dist/testing.js +1 -0
  39. package/dist/tools/mcp.d.ts +11 -0
  40. package/dist/tools/mcp.js +208 -0
  41. package/dist/workspace.js +8 -0
  42. package/docs/ai.md +52 -0
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +16 -14
  45. package/docs/case-study-raydium-cp-swap.md +77 -41
  46. package/docs/case-study-spl-stake-pool.md +122 -0
  47. package/docs/errors.md +1 -1
  48. package/docs/language.md +107 -14
  49. package/docs/security-model.md +4 -0
  50. package/docs/stability.md +69 -0
  51. package/docs/test-your-program.md +47 -0
  52. package/docs/testing.md +19 -0
  53. package/lib/typesol.d.ts +241 -40
  54. package/llms-full.txt +1352 -0
  55. package/llms.txt +30 -0
  56. package/package.json +4 -2
  57. package/runtime/typesol_rt.h +69 -0
package/llms-full.txt ADDED
@@ -0,0 +1,1352 @@
1
+ # TypeSOL: the rules and the reference
2
+
3
+ ## Writing TypeSOL
4
+
5
+ TypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live
6
+ in `programs/`, tests in `tests/`; `typesol.json` lists the programs.
7
+
8
+ - Exported functions are instructions; their parameters are the accounts (`Signer`, `Account<T>`, `Mut<T>`,
9
+ `Init<T>`, token accounts, programs) and then the arguments. Account data types are exported interfaces.
10
+ - Integers are bigint: `u8` … `u128`, `i8` … `i128` (write `1n`, never `1`; take `u64`, never `number`).
11
+ Arithmetic is checked: an overflow fails the instruction. There is no floating point.
12
+ - Import everything from `"typesol"`: types, and functions such as `require`, `log`, `min`, `max`,
13
+ `fixedArray`, `emit`, `invoke`.
14
+ - Fail with `require(condition, MyError.Name)` (an exported string enum of messages) or `require(condition, "message")`.
15
+ There is no `throw`, `try`, `async`, `class`, `console` or `Math`.
16
+ - An account the instruction changes is `Mut<T>`; one it creates is `Init<T>` (`acct.create(payer, seeds)`).
17
+ - Lists: `FixedArray<T, N>`, `FixedVec<T, N>`, `Vec<T>`; read with `.get(i)` and write with `.set(i, v)`
18
+ (`i` a bigint), not `xs[i]`. `map`, `filter`, `find`, `some`, `reduce` work on them.
19
+ - Strings are `FixedString<N>` in account data; `Option<T>` (`T | null`) for optional values.
20
+
21
+ ## Checking your work
22
+
23
+ - `npx typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a
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`
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,
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.
30
+
31
+ ## Quick start
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.
35
+
36
+ ```sh
37
+ npx @typesol/cli init my-app --name counter # typesol.json, programs/counter.ts, tests/counter.test.ts, tsconfig
38
+ cd my-app && npm install
39
+ 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}
41
+ ```
42
+
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:
45
+
46
+ ```sh
47
+ solana-keygen new # once, if you have no keypair (~/.config/solana/id.json)
48
+ solana airdrop 2 --url devnet # test SOL for the rent (rate-limited: https://faucet.solana.com also works)
49
+ npx typesol deploy --url devnet
50
+ ```
51
+
52
+ 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.
54
+
55
+ `--template vault` or `--template escrow` starts from a SOL vault or an SPL token escrow instead of the counter, each
56
+ with a passing LiteSVM test.
57
+
58
+ The npm package is [`@typesol/cli`](https://www.npmjs.com/package/@typesol/cli). Projects install it under the name
59
+ `typesol`, which is what programs import (`import { … } from "typesol"`); `typesol init` sets that up. To add it to an
60
+ existing project: `npm install -D typesol@npm:@typesol/cli`.
61
+
62
+ Deploying again upgrades the program in place. Keep `target/deploy/<name>-keypair.json`: that keypair is your
63
+ program's address.
64
+
65
+ **Your first change.** Open `programs/counter.ts`, add an instruction (say `decrement`, with
66
+ `require(counter.count >= 1n, …)` before `counter.count -= 1n`), call it from `tests/counter.test.ts` and run `npm test`.
67
+ If the build refuses something, the error points at the line and, for the usual first mistakes (`1` instead of `1n`,
68
+ `console.log`, a missing import, `async`), adds a `hint:` with what to write instead; your editor shows the same.
69
+
70
+ **Where next**
71
+ - The language, every type and built-in: [docs/language.md](docs/language.md).
72
+ - Tests with `typesol/testing` (accounts by name, plain values): [docs/test-your-program.md](docs/test-your-program.md).
73
+ - Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, and
74
+ `typesol port` starts from your program's IDL; [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one
75
+ program through the port.
76
+ - 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).
79
+ - To mainnet (wallet, cost, deploy, IDL, verification): [docs/mainnet.md](docs/mainnet.md).
80
+ - With an AI coding agent: [docs/ai.md](docs/ai.md) (agent rules, [llms.txt](https://typesol.com/llms.txt), the MCP server).
81
+
82
+ <!-- docs/language.md -->
83
+
84
+ # The TypeSOL language
85
+
86
+ The full reference. For a tour, start with the [README](../README.md).
87
+
88
+ ## Types and statements
89
+
90
+ | Concept | TypeSOL |
91
+ | --- | --- |
92
+ | 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
+ | 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 |
95
+ | 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
+ | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
97
+ | 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) |
98
+ | Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit. A cast is a value: import `u64`, not `type u64` (one import serves as both) |
99
+ | Logging | `log("text")`, `log(value)`, `log(pubkey)` |
100
+ | Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
101
+ | 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 |
103
+ | 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
+ | 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
+ | 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
+ | 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` |
107
+ | Pubkey constants | `const ADMIN = pubkey("4Nd1…")` (checked at compile time) or inline `pubkey("…")`; usable as seeds |
108
+ | 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
+ | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
110
+ | Options | `best: Option<u64>` (or `u64 \| null`) — `null`, `=== null`, TypeScript narrowing; `===` between options or with a value follows JS (null equals null, empty never equals a value); empty use aborts (5108); `acct?.field` on an optional account and `x.home?.field` on an `Option<struct>` give an Option (empty when the account was left out / the option is empty), `a ?? b` takes b only when a is empty (b runs only then; the result is an Option when b can be null), `x!` is the value or aborts with 5108; `${opt}` prints the value or `null`. Borsh `option` in arguments/events, fixed `{ is_some, value }` in account data |
111
+ | Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
112
+ | Anchor's account bytes | `/** @layout borsh */` on an account struct stores it as Anchor does (Borsh: a `FixedString<N>` is a String, a `FixedVec<T, N>` or `Vec<T>` a Vec, an `Option` one byte when empty, and the fields after them move), so a TypeSOL program can take over accounts an Anchor program wrote and the IDL lists Anchor's own types. The instruction unpacks it into the usual fixed layout when it starts (bad bytes fail with 3003) and packs it back when it returns (3004 when the account is too small for the new value), so everything else works on it unchanged. A `Vec<T>` field (any position; integers, booleans, Pubkeys, unit enums or fixed-size structs) is Anchor's own: held on the heap while the instruction runs, growing as Rust's Vec does, bounded only by the account when it is written back (3004); its elements move when it grows, so a reference into one cannot outlive a `push` or an assignment. `Init` of such a struct takes its space, `create(payer, seeds, space)`. Programs invoked from the body (CPIs) see the account's bytes as they were when the instruction started. Costs more compute than the fixed layout (the whole account is read and written each time; see the benchmarks); nested structs and list elements must be fixed-size (FixedString elements allowed). The same struct is Borsh as a whole instruction argument (checked like Borsh deserialization, UTF-8 included), as return data and as an event; as those (not as account data) it may also hold `string` fields and data enums carrying strings, Anchor's `String` and enums in argument structs (account data takes data enums without strings); not inside list or enum arguments or `loadAccount`, and a struct holding a `Vec<T>` is account data or a whole argument, not return data or an event |
113
+ | A native program's Borsh accounts | `const pool = loadBorsh<StakePool>(acct)` / `storeBorsh(acct, pool)`: Borsh from byte 0 with no discriminator and no owner check, read into a local struct and written back, as Rust's `try_from_slice_unchecked` and `serialize` do (trailing bytes ignored when reading, left as they were when writing; invalid bytes or an account too small fail with `ProgramError.BorshIoError`). Any struct of integers, booleans, Pubkeys, enums, FixedArrays, FixedStrings, FixedVecs, Options, data enums with fixed-size payloads and nested structs of those; see [Porting a native program](#porting-a-native-program) |
114
+ | Zero-copy types as Anchor's IDL describes them | `/** @repr c */` (`@repr c packed`, `@repr c align 8`, `@repr rust` on an enum) and `/** @serialization bytemuck */` on a struct or enum put the IDL's `repr` and `serialization` there, as Anchor's `#[account(zero_copy)]` / `#[repr(C)]` types have them. TypeSOL stores fields back to back, so an unpacked `@repr c` struct must have its fields where C puts them: a field off its alignment, or a size that is not a multiple of the struct's, is a compile error naming the padding to add (Anchor zero-copy types spell their padding out as `_pad` fields, so a port matches). A 16-byte integer's alignment differs between targets: hold it as below or mark the struct packed |
115
+ | Field names and bytes for the IDL | `/** @bytes */` on an integer field: stored as the integer (little-endian), shown in the IDL as `[u8; N]` (Marginfi's `WrappedI80F48 { value: [u8; 16] }`, read and written as an `i128`); on a FixedArray of integers, each element as its bytes (`[[u8; 8]; 16]` for a `FixedArray<u64, 16>`). `/** @idlName _pad0 */`: the field's IDL name where the source cannot use it (a leading `_`). A field named like an account member plus `_` (`key_`, `lamports_`) is `key` / `lamports` in the IDL |
116
+ | Floats in events and accounts | `f64` holds a 64-bit float as its IEEE bits (Borsh writes those 8 bytes; the IDL says `f64`). There is no float arithmetic: `f64FromBits(bits)` makes one from bits the program computed in integers (Marginfi's events report I80F48 amounts this way), `f64Bits(x)` reads them back |
117
+ | 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
+ | 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
+ | 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 |
120
+ | 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
+ | 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
+ | 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) |
123
+ | Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
124
+ | 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
+ | 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
+ | 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) |
128
+ | 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
+ | 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
+ | 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
+ | `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) |
133
+ | 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
+ | 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
+ | 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) |
138
+ | 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
+ | 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
+ | 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
+ | 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()`) |
143
+ | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
144
+ | 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
+ | 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) |
146
+ | Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferFeeInverse(mint, amountReceived)` (the fee when the recipient is to get that much: spl-token-2022's `calculate_inverse_epoch_fee`), `transferFeeBasisPoints(mint)` / `transferFeeMaximum(mint)` (this epoch's; 0 without the extension), `extensionsWithin(account, [1n, 18n, …])` (every extension is one of those types), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
147
+ | Events through CPI | `emitCpi<Paid>({ … }, eventAuthority, self)` with `eventAuthority: EventAuthority, self: SelfProgram` parameters — Anchor `emit_cpi!`: the event rides in a self-CPI (inner instruction), not in logs; the program accepts Anchor's event instruction (2002 / 2006 otherwise) |
148
+ | Heap | 32 KiB by default; `const HEAP_SIZE_KIB = 64n` (32–256) lets the program use more, when clients add ComputeBudget `requestHeapFrame` |
149
+ | Docs | JSDoc on instructions, `@param`, structs, fields and data enums becomes `docs` in the IDL |
150
+ | Metaplex Core | `core: MplCoreProgram` — `createCollection`, `createAsset` (in a collection, PDA authorities via signerSeeds), `transferAsset`, `burnAsset` (`null` leaves an optional account out); plugins as a literal list after the uri (`[{ kind: "Royalties", basisPoints: 500n, creators: [{ address, percentage: 100n }] }, { kind: "PermanentFreezeDelegate", frozen: false, authority: studio.key }]`), and `addPlugin` / `updatePlugin` / `removePlugin(…, "FreezeDelegate")` with their `…CollectionPlugin` forms. Plugins: Royalties (with an optional `ruleSet: { programAllowList \| programDenyList: [...] }`), FreezeDelegate, BurnDelegate, TransferDelegate, UpdateDelegate, PermanentFreezeDelegate, Attributes, PermanentTransferDelegate, PermanentBurnDelegate, Edition, MasterEdition (collections: `maxSupply?`, `name?`, `uri?`), AddBlocker, ImmutableMetadata, VerifiedCreators, Autograph, BubblegumV2, FreezeExecute, PermanentFreezeExecute (Groups is kept by Core's group instructions); `authority` is `"owner"`, `"updateAuthority"`, `"none"` or a Pubkey; `coreAssetOwner(asset)`, `coreAssetCollection(asset)`. External plugin adapters: `addExternalPlugin` / `removeExternalPlugin` / `writeExternalPluginData` (and the Collection forms) with `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle", baseAddress, checks: [{ event: "transfer", canReject: true }], resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram, checks, extraAccounts?, dataAuthority?, schema? }` and the Linked forms; a key names one (`{ kind: "AppData", dataAuthority }`, `{ kind: "Oracle", address }`); data is a string, a `Vec<u8>` argument or `null` (Core currently answers lifecycle hooks with NotAvailable, 23) |
151
+ | Compressed NFTs | `bubblegum: BubblegumProgram` — V1 (trees on SPL Account Compression): `createTree`, `mint` (MintV1, no collection/creators), `mintToCollection` (MintToCollectionV1: into a verified Token Metadata collection), `transfer`, `burn`, `delegate` (the leaf owner or delegate signs; a PDA owner signs with the seeds). V2 (trees on mpl-account-compression with mpl-noop): `createTreeV2`, `mintV2(…, { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable? }, { collection, authority, cpiSigner }?)` (into a Core collection that has the `BubblegumV2` plugin), `transferV2`, `burnV2`, `delegateV2`, `freezeV2` / `thawV2`, `setNonTransferableV2`, `updateMetadataV2(…, currentMetadata, { name?, symbol?, uri?, creators?, … })`, `verifyCreatorV2` / `unverifyCreatorV2`, `setCollectionV2`. Each takes the leaf (`{ root, dataHash, creatorHash, assetDataHash?, flags?, nonce, index }`, or `{ root, assetDataHash?, flags?, nonce, index }` with the leaf's current metadata for the metadata instructions) and its proof as `remainingAccounts()` / `rest.slice(a)` |
152
+
153
+ ## Account parameters and the checks they emit
154
+
155
+ | Parameter type | Checked before your code runs |
156
+ | --- | --- |
157
+ | `Signer` / `Mut<Signer>` | signed (and writable) |
158
+ | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable). A zero-copy type (`@serialization bytemuck`) is checked as Anchor's `AccountLoader` checks it: owner first (3007, also for an account never created), then a discriminator to read (3001) and match (3002), then the size |
159
+ | `Init<T>` | writable; `create(payer, seeds)` derives the PDA, verifies it, funds rent, writes the discriminator (up to 10 KiB); `create(payer, null)` creates a new keypair account that signs the transaction instead (3010 if it did not; a signer in the IDL); a third argument is Anchor's `space = …` (discriminator included, at least 8 + the struct's size). A seed may be an Option integer argument with a default, `opt ?? 0n` (the IDL records `opt.unwrap_or(0)`, as Anchor's does). The creates a body starts with (after its `constraint(…)` lines) run before the other accounts' constraints, as Anchor creates `init` accounts first; a create after other statements runs where it is |
160
+ | `InitIfNeeded<T>` | `const created = acct.createIfNeeded(payer, seeds)` — creates once; afterwards re-derives the PDA and checks owner, discriminator and size (Anchor `init_if_needed`); `acct.pdaBump` after create. An existing account is used as it is: check the fields you rely on |
161
+ | `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL. The data is a read-only list of u8: `for (const b of data)`, `map` / `filter` / `reduce` / `some` and the other list methods, `data.slice(start, end?)` (a view, nothing copied; unlike JS it does not clamp: past the length fails with 5104), `out.pushAll(data.slice(a, b))` into a local FixedVec, and a helper takes it or a slice as an `InstructionBytes` parameter |
162
+ | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`) or another group (`p.fees.vault`; the IDL nests it too, the client flattens it to `pFeesVault`); a group may not be optional or a helper parameter. An instruction with a group checks in Anchor's order: its arguments first (102), then each account in order, a group's constraints right after the group's accounts (as a composite's `try_accounts` does), the other constraints last |
163
+ | `constraint(acct, condition, error?)` | Anchor's `constraint = condition @ error` on `acct`: statements at the very start of the body, run with that account's checks (after its `has_one`, before the next account; with the other constraints after the creates the body starts with), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
164
+ | `HasOne<A, "owner">`, `Seeds<A, ["vault", "@owner"], "bump">`, `CloseTo<A, "owner">` | declarative constraints like Anchor's `has_one`, `seeds`/`bump` and `close`: checked before the body (2001 / 2006), close runs when the instruction succeeds; `"@name"` = account key or argument bytes (`"@name:be"`: an integer's bytes most significant first, Rust's `to_be_bytes()`; the IDL records the argument, as Anchor's does, so clients that derive the address from the IDL get it wrong: pass such accounts explicitly), `"@acct.field"` = a Pubkey, integer or unit enum field of a struct account parameter (also the account's own: `["offer", "@maker", "@offer.id"]`), other strings are literals; recorded as `relations` / `pda` in the IDL. a bump stored in another struct account is named `"@acct.field"` (Anchor `bump = multisig.nonce`), or `"@acct.field.inner"` when it is in a struct field of it (Anchor `bump = config.bumps.vault`); `acct.pdaBump` is the bump (Anchor `ctx.bumps.acct`): the stored field when one is named, else the canonical bump the check found — use it to sign as the PDA |
165
+ | `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` | one of your errors instead of Anchor's code, as Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the constraints Anchor lets you name an error for); a member of one of the program's error enums. For several `HasOne` fields with different errors, nest them: `HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>` |
166
+ | `HasOne<TokenAccount, "mint" \| "owner">`, `HasOne<Mint, "mintAuthority" \| "freezeAuthority">` | token constraints (2014 / 2015 / 2016 / 2017) against the parameter with that name; `TokenOf<TokenAccount, "mintParam", "authorityParam", "tokenProgramParam">` / `MintOf<Mint, "authorityParam", "freezeParam", "tokenProgramParam">` name the parameters, as Anchor's `token::mint = …` / `mint::authority = …` / `…::token_program = …` do (`never` leaves one out; the token program one: owned by that token program, 2021 / 2022) |
167
+ | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL); the owner may be a Pubkey field of a struct account parameter, `"@config.wallet"` (Anchor's `associated_token::authority = config.load()?.wallet`; the IDL names the account, as Anchor's does) |
168
+ | `Ata<Init<TokenAccount>, "owner", "mint">`, `Ata<InitIfNeeded<TokenAccount>, "owner", "mint">` | Anchor `init` / `init_if_needed` with `associated_token::…`: `acct.create(payer)` creates the ATA (fails if it exists); `const created = acct.createIfNeeded(payer)` creates it only when missing, otherwise checks it is that ATA (2009). Then it is a `TokenAccount` of that mint and owner (2014 / 2015). Needs `AssociatedTokenProgram`, `SystemProgram` and a token program parameter; call it at the top level before using the account |
169
+ | `Address<A, "4Nd1…">` | exact address (2012; `address` in the IDL) |
170
+ | `Owner<A, "Tokenkeg…">`, `Executable<A>` | owner program (2004), executable (2007). On a struct account, `Owner<Account<T>, "…">` is another program's account (Anchor's `Account` / `AccountLoader` of a `declare_program!` type): loaded with that program as its owner (3007) and Anchor's discriminator for `T`'s name, its fields read and `HasOne` checked as for this program's own; the IDL lists `T` among its types, not its accounts (an error named on such an `Owner` is not used: the load fails with 3007). Such a struct may carry a shorter discriminator, `/** @discriminator 0x01 */` (1 to 8 bytes, as Anchor's `discriminator = &[1]`; Solend's reserve), its fields then starting right after it; this program's own accounts keep 8 |
171
+ | `Seeds<A, ["metadata", "@mint"], never, "@metadataProgram">` | the fourth argument derives the PDA under another program (a program parameter or a base58 address; `pda.program` in the IDL) |
172
+ | `A \| null` / `Optional<A>` | optional account (Anchor `Option<Account>`): the client passes this program's id to leave it out; its checks and constraints run only when present (a `constraint(other, …)` that mentions it runs as written: `x === null` is checked when it is missing); `x !== null` before use, or `x!` / `x!.field` to assert it was passed (5115 otherwise); `optional` in the IDL |
173
+ | `ProgramData` | this program's ProgramData (address derived from the program id, upgradeable-loader owner and state checked); `upgradeAuthority`, `deploySlot` — gate admin setup on `programData.upgradeAuthority === admin.key` |
174
+ | `EventAuthority`, `SelfProgram` | Anchor's `["__event_authority"]` PDA, and this program's own address, for `emitCpi` |
175
+ | `Migrate<From, To>` | Anchor 1.0's `Migration`: an existing `From` account (owner, discriminator, size) rewritten as `To` by `acct.migrate(payer, value)`, a top-level statement the instruction must reach. `acct.from` (read-only) before it, `acct.to` after; the value is built in full before the rewrite, so it may read `acct.from`. Resized to `To` (the payer tops up rent when it grows, at most 10 KiB; shrinking keeps the lamports; growing needs `SystemProgram`). Fixed-layout structs without growable Vecs; no constraints yet; the account cannot be passed to a helper (use `acct.to` fields in the instruction). An account already migrated fails with 3002. Keep the old struct under a new name with its discriminator: `/** @discriminator account:Counter */ interface CounterV1 { … }` |
176
+ | `Zeroed<T>` | accounts (up to 10 MiB) the client allocated with System `CreateAccount`, Anchor's `zero`: discriminator still zero (2013, checked first as under Anchor), owned by this program, big enough, rent-exempt — then initialized. A `@layout borsh` struct starts empty and is written as Borsh when the instruction returns |
177
+ | `Signed<A>` | the account must sign the transaction (Anchor's `signer` constraint, 2002), e.g. `Signed<Zeroed<Multisig>>` for an account the client creates with a fresh keypair; the IDL marks it a signer |
178
+ | `Init<Mint>`, `InitIfNeeded<Mint>` | Anchor `init` / `init_if_needed` with `mint::decimals` / `mint::authority` / `mint::freeze_authority`: `const bump = mint.create(payer, ["mint", payer.key], 6n, authority, freezeAuthority \| null)` creates the mint at that PDA of this program, or with `null` seeds as a new keypair account that signs (3010 if it did not), under the instruction's token program (its only token program parameter, or one passed as the last argument of `create` / `createIfNeeded`; plus `SystemProgram`). Token-2022 extensions (Anchor's `extensions::…`) go after the freeze authority: `mint.create(payer, null, 6n, authority, null, { metadataPointer: { authority, metadataAddress: mint.key }, transferHook: { authority, programId }, closeAuthority, permanentDelegate, nonTransferable: true, defaultAccountState: true, interestBearing: { rateAuthority, rate }, transferFee: { configAuthority, withdrawAuthority, basisPoints, maximumFee }, groupPointer, groupMemberPointer })` sizes the mint for them and initializes each before InitializeMint2. With `createIfNeeded` an existing mint must carry groupPointer / groupMemberPointer / metadataPointer / closeAuthority / permanentDelegate / transferHook with those keys (Anchor's 2024–2039); extensions not listed are not looked at, so an existing mint may carry others (a permanent delegate, say). `createIfNeeded(…)` returns whether it created it; an existing one must be that PDA and have those decimals and authorities (2018 / 2016 / 2017) |
179
+ | `Init<TokenAccount>`, `InitIfNeeded<TokenAccount>` (no `Ata<…>`) | Anchor `init` / `init_if_needed` with `token::mint` / `token::authority`: `vault.create(payer, ["vault", mint.key], mint, authority)` (the authority may be `vault.key` itself) creates a token account at that PDA (or a keypair account with `null`), sized for the mint's extensions under Token-2022. `createIfNeeded` checks an existing one has that mint and owner (2014 / 2015), not its delegate or close authority (as Anchor) |
180
+ | `TokenAccount` / `Mut<TokenAccount>` | owned by SPL Token or Token-2022 (extensions allowed, multisig accounts refused), initialized (an account never created: 3012, as Anchor; a `Mint` likewise); `mint`, `owner`, `amount`, `delegate`, `delegatedAmount`, `isFrozen`, `isNative`, `closeAuthority`, `tokenProgram` |
181
+ | `Mint` / `Mut<Mint>` | owned by SPL Token or Token-2022, initialized; `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
182
+ | `SystemProgram`, `TokenProgram`, `Token2022Program` | exact program address |
183
+ | `TokenInterface` | either token program |
184
+ | `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
185
+ | `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
186
+ | `TokenMetadataProgram` | Metaplex `createV3(...)` (CreateMetadataAccountV3), optionally with `{ creators: [{ address, verified, share }], collection: mint }` after `isMutable` (1–5 creators, shares adding up to 100; only the update authority, signing, can be `verified: true`; the collection is written unverified; `isCollection: true` makes the NFT a sized collection); `createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply \| null)`; `verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar)` (Verify with CollectionV1); `updateMetadataAccountsV2(metadata, updateAuthority, data \| null, newUpdateAuthority \| null, primarySaleHappened \| null, isMutable \| null)` (`data` replaces the whole DataV2: `{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`; each null leaves that part); `burnV1(authority, metadata, edition \| null, mint, token, collectionMetadata \| null, systemProgram, instructionsSysvar, tokenProgram, amount)` (Burn: the holder signs and gets the rent back; the token account and edition close, the metadata is cleared to one byte); `metadataAddress(mint)`, `masterEditionAddress(mint)` |
187
+ | `StakeProgram` | `initialize(stake, rentSysvar, staker, withdrawer, lockup?)` (`lockup`: `{ unixTimestamp, epoch, custodian }`, none when left out), `authorize(stake, clockSysvar, authority, newAuthority, "staker" \| "withdrawer", custodian?)`, `delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker)`, `split(stake, splitStake, staker, lamports)`, `deactivate(stake, clockSysvar, staker)`, `withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, custodian?)`, `merge(destination, source, clockSysvar, stakeHistorySysvar, staker)`, `getMinimumDelegation()` (a CPI, then the u64 the Stake program returns; fails as solana_program's `get_minimum_delegation` does); instruction tags and account lists as solana-stake-interface's builders; the sysvar and config accounts are parameters, as in anchor-spl's stake module, or `named(account, address)` (a native port): the instruction names `address` (`SysvarC1ock…`), as solana_program's builders do, and `account`, the slot's account, is what the runtime gets, as Rust's `invoke_signed(&ix, &[stake, clock_info, …])` passes it; the runtime looks the address up among the CPI's accounts only, so a slot holding another account fails the call (MissingAccount), as the original does, even when the sysvar is elsewhere in the transaction (`named` is valid only there); authorities and the lockup custodian sign (PDAs with signerSeeds, given last) |
188
+ | `InstructionsSysvar`, `PythPriceUpdate`, `SwitchboardFeed` | exact address (3008) / owner program + discriminator. `Address<InstructionsSysvar, "Sysvar1nstructions1111111111111111111111111">` checks the address as Anchor's `address = sysvar::instructions::ID` on an `UncheckedAccount` does (2012, with the constraints) |
189
+ | `InstructionsSysvar` (introspection) | `ixs.length`, `ixs.currentIndex()` (the top-level instruction being executed), `ixs.get(i)` → a `TransactionInstruction`: `programId`, `accountsLength`, `dataLength`, `accountKey(j)` / `accountIsSigner(j)` / `accountIsWritable(j)`, `readU8/U16/U32/U64/readPubkey(offset)` (little-endian), `is(program, "name")` (that program's instruction by its default Anchor discriminator, sha256("global:<name>"); an instruction with its own `@discriminator` is matched with `programId` and `readU64(0)` instead). Every read is bounds-checked (5104). It is the transaction author's data: require things of the transaction with it (a repay instruction after a flash loan), never treat it as proof |
190
+ | `Program<"Address…">` | exact program address + executable |
191
+ | `UncheckedProgram` | executable only — check `.key` yourself |
192
+ | `AccountInfo` / `Mut<AccountInfo>` | nothing (writable for `Mut`); `owner`, `executable` |
193
+ | `SystemAccount` / `Mut<SystemAccount>` | owned by the System Program, e.g. a wallet (Anchor `SystemAccount`, 3011) |
194
+
195
+ Every account exposes `key`, `lamports`, `dataLen`, `isSigner`, `isWritable`. At most 32 accounts per instruction (more is refused, 5113); `export const MAX_ACCOUNTS = 128n` (up to 255, Anchor takes what the runtime allows) raises it for programs that take many remaining accounts, keeping the CPI scratch lists on the heap instead of the stack (programs that do not declare it compile exactly as before).
196
+
197
+ Two writable parameters can never be the same account: aliasing is refused with error 2040 (also when a remaining
198
+ account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
199
+ (Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed
200
+ or `@layout borsh`; a close destination may be one, the rent reaching it through either): a write through either is
201
+ seen through the other, so read what you need before writing. A remaining account
202
+ can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
203
+ with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
204
+ `AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
205
+ of a position, as Raydium CLMM's tick arrays).
206
+
207
+ ## Built-ins
208
+
209
+ - `systemProgram.transfer(from, to, lamports, signerSeeds?)` (`from` is a `Mut<Signer>`, or a system-owned PDA of this
210
+ program, a SOL vault, with its seeds), `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
211
+ (the new account signs: a keypair `Mut<Signer>` or this program's PDA), `systemProgram.createPda(payer, account, space,
212
+ owner, seeds)` (Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: a `Mut<AccountInfo>`
213
+ that must be this program's PDA for `seeds` (2006), created owned by `owner`, or topped up, allocated and assigned when
214
+ someone funded the address first; returns the bump, records the PDA in the IDL, and among the creates a body starts
215
+ with runs before the constraints), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
216
+ - Token programs (`TokenProgram`, `Token2022Program`, `TokenInterface`) — pass `signerSeeds` (with the bump) when the authority is a PDA:
217
+ `transfer`, `transferChecked(from, mint, to, authority, amount)` (required by Token-2022 mints with fees/hooks), `mintTo` (the mint may be one this instruction just created), `burn`, `closeAccount` (a token account, or a Token-2022 mint with a close authority),
218
+ `approve(source, delegate, owner, amount)`, `revoke`, the checked forms `mintToChecked(mint, to, authority, amount)`,
219
+ `burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
220
+ come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
221
+ `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
222
+ `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
224
+ - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
225
+ stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
226
+ among up to 256 addresses for the same seeds
227
+
228
+ ## Implementing another program's interface (transfer hooks)
229
+
230
+ `/** @discriminator spl-transfer-hook-interface:execute */` above an instruction replaces its Anchor discriminator with
231
+ sha256(preimage)[..8] (or `@discriminator 0x…` for raw bytes), so a TypeSOL program can be a Token-2022 transfer hook:
232
+ `execute(source, mint, destination, owner, extraMetas, ...extraAccounts, amount)` plus
233
+ `initExtraAccountMetas(payer, account, mint, systemProgram, extraAccounts?)` for the validation account (an
234
+ ExtraAccountMetaList). Extra accounts are listed as `{ address, isSigner?, isWritable? }` (a fixed address) or
235
+ `{ seeds: [...], program?, isSigner?, isWritable? }` (a PDA of this program, or with `program: i` of the program at account
236
+ index i), with seeds from string literals, `seedAccountKey(i)`, `seedAccountData(i, offset, length)` and
237
+ `seedInstructionData(offset, length)`; Token-2022 resolves and checks them on every transfer. The first extra account has
238
+ index 5. `updateExtraAccountMetas(...)` rewrites and resizes an existing list. See `test/fixtures/hook.ts` and the
239
+ transfer-hook ports.
240
+
241
+ ## Calling other programs
242
+
243
+ ```ts
244
+ export function relayIncrement(authority: Signer, counter: Mut<AccountInfo>, counterProgram: Program<"JD2v…99Y2">, by: u64): void {
245
+ invoke(counterProgram, [readonlySigner(authority), writable(counter)], [sighash("increment"), by]);
246
+ }
247
+
248
+ // Sign for a PDA of this program: raw System transfer (u32 tag 2, u64 lamports) out of a treasury PDA.
249
+ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: Mut<SystemAccount>, systemProgram: SystemProgram, amount: u64, bump: u8): void {
250
+ invoke(systemProgram, [writableSigner(treasury), writable(recipient)], [u32(2n), amount], ["treasury", admin.key, bump]);
251
+ }
252
+ ```
253
+
254
+ - program: a `Program<"address">` (key and executable checked on entry), an `UncheckedProgram`, an
255
+ `Address<AccountInfo, "address">` (Anchor's `#[account(address = ID)]` on an `UncheckedAccount`: only the key is
256
+ checked, 2012), the system or a token program, or a remaining account.
257
+ - accounts: `readonly(x)`, `writable(x)`, `readonlySigner(x)`, `writableSigner(x)`. The compiler refuses `writable` on a
258
+ non-`Mut` parameter and a signer flag on an account that neither signed nor is covered by `signerSeeds`. An optional
259
+ account passed as it is (`readonly(x)` / `writable(x)` with `x: A | null`, no `!`) is left out of the list when it
260
+ was not passed, as Rust's `if let Some(x) = &self.x { accounts.push(…) }` does.
261
+ - data (Borsh): integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
262
+ Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
263
+ `sighash("name")` (Anchor discriminator), `hex("0a0b")`. Up to 1024 bytes.
264
+ - `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
265
+ lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
266
+ - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
267
+ wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
268
+ signer([…, bump])`.
269
+ - `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
270
+ - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
271
+ A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
272
+ unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
273
+ declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106.
274
+
275
+ A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
276
+ `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`):
277
+
278
+ ```ts
279
+ invokeInstruction(transaction.programId, transaction.accounts, transaction.data, remainingAccounts(), [multisig.key, multisig.nonce]);
280
+ ```
281
+
282
+ - the accounts are a list of structs with `pubkey`, `isSigner` and `isWritable` (a Vec or FixedVec in account data, a
283
+ Vec argument, a stored `map` result, or a local list built on the stack); the data a list of u8 (the same, the
284
+ instruction data or a slice of it).
285
+ - every account in the fourth argument (`remainingAccounts()` or a slice; in a helper, its `RemainingAccounts`
286
+ parameter or a slice of it) is handed to the runtime, which finds each meta's account there by key: one that is
287
+ missing fails the call, as under Rust (MissingAccount, "Instruction references an unknown account").
288
+ - so a native port builds the instruction as Rust's instruction builders do, in a helper too, with metas naming
289
+ accounts by key:
290
+
291
+ ```ts
292
+ function transfer(rest: RemainingAccounts, data: InstructionBytes, to: Pubkey): void {
293
+ const metas: FixedVec<Meta, 2> = fixedVec([{ pubkey: rest.get(0n).key, isSigner: true, isWritable: true }]);
294
+ metas.push({ pubkey: to, isSigner: false, isWritable: true });
295
+ const ix: FixedVec<u8, 12> = fixedVec([2n, 0n, 0n, 0n]); // system_instruction::transfer
296
+ ix.pushAll(data.slice(1n, 9n)); // the lamports, as sent
297
+ invokeInstruction(rest.get(2n).key, metas, ix, rest);
298
+ }
299
+ ```
300
+ - the runtime checks the privileges: a meta may be a signer or writable only as the transaction passed that account,
301
+ or as a PDA of this program the seeds (fifth argument) sign for. See `showcase/mainnet/multisig/multisig.ts`.
302
+
303
+ Typed calls from an IDL: `typesol cpi other.json --out other_cpi.ts` writes one helper per instruction
304
+ (`vaultDeposit(program, owner, vault, systemProgram, amount, seeds)`), with the account flags, discriminator and
305
+ argument encoding taken from the IDL (Anchor 0.30+ / 1.x, or TypeSOL's own). Call it with `signer([...seeds, bump])`
306
+ when a PDA of your program signs, or `signer([])`. Instructions whose arguments have no Borsh-identical TypeSOL type
307
+ (strings or Options inside structs, data-carrying enums) are listed and left out.
308
+
309
+ ## PDAs in the IDL
310
+
311
+ When an instruction calls `x.create(payer, seeds)` or `requirePda(x, seeds, bump)` and every seed is a string literal,
312
+ an integer literal, an argument, `acct.key` or a scalar field of an account, the IDL entry for `x` gets Anchor `pda.seeds`
313
+ (`const` / `arg` / `account`), so Anchor and Codama clients derive the address themselves.
314
+
315
+ ## Programs and sysvars passed as remaining accounts
316
+
317
+ A native program takes its programs and sysvars by position too. `programAt<P>(account)` checks a remaining account
318
+ (or an `AccountInfo` parameter) is that program, once, by its key, and gives it P's typed methods:
319
+
320
+ ```ts
321
+ const rest = remainingAccounts();
322
+ const stake = programAt<StakeProgram>(rest.get(12n)); // ProgramError.IncorrectProgramId if it is another account
323
+ stake.split(rest.get(3n), rest.get(4n), rest.get(1n), lamports, [pool.key, "withdraw", bump]);
324
+ const minimum = stake.getMinimumDelegation();
325
+ programAt<TokenInterface>(rest.get(10n)).mintTo(rest.get(7n), rest.get(8n), rest.get(1n), amount, seeds);
326
+ ```
327
+
328
+ - P is `StakeProgram`, `SystemProgram`, `TokenProgram`, `Token2022Program`, `TokenInterface` (either token program),
329
+ `AssociatedTokenProgram` or `MemoProgram`. Bind it with `const`, or call a method on it directly; pass it to a helper
330
+ that takes that program type.
331
+ - `sysvarAt<StakeHistorySysvar>(account)` does the same for the StakeHistory sysvar (ProgramError.InvalidArgument for
332
+ another account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)` … as on a parameter (read its fields
333
+ through a `const` bound to it; methods also work on the call itself).
334
+ - Every typed CPI (System, SPL Token and Token-2022, ATA, Memo, Stake) takes, for each account, a declared parameter,
335
+ a remaining account (`rest.get(i)`, a local bound to one, a `RemainingAccount` helper parameter), a struct loaded
336
+ from one, or an `AccountInfo` parameter where a `TokenAccount` or `Mint` goes. Declared parameters keep their
337
+ compile-time checks (writable slots need `Mut<…>`, an authority without signerSeeds a `Signer`). A remaining account
338
+ is not checked by the compiler, and unlike `invoke` the typed calls add no runtime check of their own: the runtime
339
+ refuses a CPI that makes an account writable or a signer when the transaction did not (and no seeds sign for it),
340
+ and the called program checks the rest (a token account's mint and owner, a stake account's authorities).
341
+ - The cost is the key check (four 8-byte compares) and the call itself: within a few compute units of the same call
342
+ written with `invoke`, which checks only the executable flag (test/integrations/native-cpi.test.ts measures it).
343
+
344
+ ## Porting a native program
345
+
346
+ A program written without Anchor (Raydium AMM v4, SPL programs) reads a tag byte and its arguments itself and takes its
347
+ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-amm` and `test/fixtures/native.ts`):
348
+
349
+ - One `/** @fallback */` entry: `const data = instructionData()` gives the bytes, with `data.readU8/U16/U32/U64/U128/
350
+ readPubkey(offset)` (little-endian, bounds-checked: 5104), and the list methods, `for … of`, `data.slice(a, b)`
351
+ (a view, 5104 out of range) and `out.pushAll(data.slice(a, b))` (a memcpy into a local FixedVec); a helper takes it as
352
+ an `InstructionBytes` parameter. `remainingAccounts()` gives the accounts by position.
353
+ - Calls to System, Token and Stake: `programAt<P>(acct)` and the typed methods, with remaining accounts (above), not
354
+ hand-encoded `invoke` data.
355
+ - Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
356
+ 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)]`.
358
+ - Borsh accounts without a discriminator (SPL Stake Pool's `StakePool`, read with `try_from_slice_unchecked` and
359
+ written with `serialize`): `const pool = loadBorsh<StakePool>(acct)` decodes the data from byte 0 into a local
360
+ struct (a copy: fields updated, Options narrowed and set to null or a value, data enums switched, copied, passed to
361
+ helpers), and `storeBorsh(acct, pool)` encodes it back from byte 0. As Rust: no owner check and no discriminator
362
+ (check the owner first, as the original does); bytes after the value are ignored when reading and left as they were
363
+ when writing (an Option that became None leaves its old bytes behind it); data too short, an Option tag or boolean
364
+ other than 0/1, an enum tag out of range, a String that is not UTF-8 or longer than its `FixedString<N>`, or an
365
+ account too small for the encoding fail with `ProgramError.BorshIoError`. `acct` is a remaining account, a
366
+ `RemainingAccount` helper parameter or an `AccountInfo` parameter (`Mut<AccountInfo>` for `storeBorsh`; a remaining
367
+ account must be writable, 3006). `T` may hold integers, booleans, Pubkeys, enums, FixedArrays, `FixedString<N>`,
368
+ `FixedVec<T, N>`, Options, data enums with fixed-size payloads and nested structs of those, with or without
369
+ `@layout borsh`; not `Vec<T>` or `string` (they would need the heap or a view). Each struct gets its own
370
+ straight-line decoder and encoder (no heap): about 280 CU to read a 611-byte `StakePool` and 610 CU to read and
371
+ write it back. The local lives on the stack (4 KiB per function).
372
+ - Lists over the rest of an account (SPL's `big_vec`): a struct ending in `BigVec<T>`, `const list =
373
+ loadRawMut<ValidatorList>(acct)`, then `list.validators.push(…)`, `.retain((v) => …)`, `.findIndex((v) => …)`,
374
+ `for (const v of list.validators.slice(skip, skip + len))` (`deserialize_mut_slice(skip, len)`). The load fails with
375
+ AccountDataTooSmall when the stored length does not fit, where the Rust would only panic on reaching such an element:
376
+ check the length first (`readData<u32>(acct, offset)`) where the original returns an error of its own before that.
377
+ - Writes as the original makes them: `export const NATIVE_ACCOUNT_WRITES = true` (anywhere in the program; opt-in, for
378
+ native ports). A native program writes account data in place and the runtime judges afterwards: a read-only account
379
+ whose data actually changed fails the instruction (`ReadonlyDataModified`, or an access violation at the write under
380
+ account-data direct mapping), one that was only read (or written with the bytes it held) is fine, and an account
381
+ passed twice is two `AccountInfo`s over one buffer. By default
382
+ `loadRawMut` and `storeBorsh` check writability up front (3006), `loadRawMut` claims the account once and
383
+ `storeBorsh` refuses an account passed more than once (2040, as a write to a remaining account's lamports), so a
384
+ port fails where the original succeeds (a read-only validator list that is only read; the list passed again as a
385
+ stake account, which the original skips by its address checks). With the flag, `loadRawMut`, `storeBorsh` and the
386
+ BigVec writes through a `loadRawMut` view skip both, and both take a plain `AccountInfo` parameter (no `Mut<…>`
387
+ needed). Owner and size checks stay. **The trade-off:** a write to a read-only account is reported by the runtime at
388
+ the end, not at the write, and two loads of one account are two views of the same bytes (a write through one is
389
+ read through the other), where Rust's `RefCell` would fail a second `borrow_mut()` while the first is held (a panic,
390
+ or `AccountBorrowFailed` through `try_borrow_mut_data`). The original's own address and type checks normally refuse
391
+ such a pair before it is loaded (SPL Stake Pool's PDA checks); make them in the same order, before the load. Only
392
+ data writes are affected: with or without the flag every view reads the account's bytes in place, so a `loadRaw`
393
+ of an account also loaded with `loadRawMut` (or written with `storeBorsh`) reads what was written, BigVec pushes
394
+ included; the flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position or
395
+ another, is 2040 without it). `.lamports` on remaining accounts, `loadAccountMut`, CPI account metas and the checks of
396
+ `Mut<…>` parameters stay as they are, and programs without the flag compile exactly as before.
397
+ - Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
398
+ `ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
399
+ built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
400
+ reporting that location; `panic(null, "src/lib.rs:105:19")` logs no message, for an original whose panic handler
401
+ writes none, so only the runtime's "SBF program Panicked in src/lib.rs at 105:19" is left); `abort()` for Rust's
402
+ abort (the allocator's out-of-memory error: `log("Error: memory allocation failed, out of memory"); abort();`), the
403
+ runtime's `abort` syscall, which logs "SBF program panicked" with no location; `const PANIC_ON_OVERFLOW = true`
404
+ makes arithmetic overflow and division by zero panic as `checked_*().unwrap()` does instead of failing with 5100 /
405
+ 5101.
406
+ - 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)`);
408
+ `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).
410
+
411
+ ## Not supported yet
412
+
413
+ A struct holding a FixedVec that is both an argument and account data (its bytes differ there, and the IDL describes a
414
+ type one way: declare one for each), growing an account by more than 10 KiB in one instruction (Solana's limit: realloc
415
+ again in the next instruction), `?.` and `!` on anything but optional accounts, Options and a `find` on struct elements,
416
+ functions stored in a struct, chosen from a list by index or returned from an instruction, a fused `map` to strings
417
+ (store it, annotated), floating point (by design).
418
+ They are rejected at compile time rather than half-supported.
419
+
420
+ `Init.create` handles a PDA address someone pre-funded: it tops up rent, then allocates and assigns instead of
421
+ `create_account` (which would fail).
422
+
423
+ <!-- docs/errors.md -->
424
+
425
+ # Error codes
426
+
427
+ Framework errors use Anchor's numbers where Anchor has the same check, so clients and explorers read them the same way.
428
+
429
+ | Code | Meaning |
430
+ | --- | --- |
431
+ | 100 / 101 / 102 | instruction data missing / unknown instruction / malformed arguments (InstructionMissing / FallbackNotFound / DidNotDeserialize) |
432
+ | 2000 | a `Mut<…>` / `Init<…>` account passed read-only (ConstraintMut) |
433
+ | 2001 | HasOne constraint failed (ConstraintHasOne) |
434
+ | 2002 | a `Signed<…>` account (or the event authority) did not sign (ConstraintSigner) |
435
+ | 2003 | a `constraint(acct, condition)` without its own error failed (ConstraintRaw) |
436
+ | 2004 | Owner constraint failed (ConstraintOwner) |
437
+ | 2005 | Zeroed account is not rent-exempt (ConstraintRentExempt) |
438
+ | 2006 | PDA seeds mismatch (ConstraintSeeds) |
439
+ | 2007 | Executable constraint failed (ConstraintExecutable) |
440
+ | 2009 | not the associated token account (ConstraintAssociated) |
441
+ | 2012 | not the expected address (ConstraintAddress) |
442
+ | 2013 | a `Zeroed<…>` account whose discriminator is already set (ConstraintZero; checked before its owner, as under Anchor) |
443
+ | 2014 / 2015 | token account mint / owner mismatch (ConstraintTokenMint / ConstraintTokenOwner) |
444
+ | 2016 / 2017 / 2018 | mint authority / freeze authority / decimals mismatch (2018: an existing mint `createIfNeeded` found) |
445
+ | 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
446
+ | 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) |
448
+ | 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
+ | 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
450
+ | 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
451
+ | 3002 | discriminator mismatch (AccountDiscriminatorMismatch) |
452
+ | 3003 | data too small, not an initialized token account / mint, a read past the end, or a `@layout borsh` account whose bytes are not a valid Borsh value (AccountDidNotDeserialize) |
453
+ | 3004 | a `@layout borsh` account too small for the value it would now hold (AccountDidNotSerialize) |
454
+ | 3005 | not enough accounts (AccountNotEnoughKeys) |
455
+ | 3006 | a remaining account or CPI account the program needs writable was passed read-only (AccountNotMutable) |
456
+ | 3007 | wrong owner program (AccountOwnedByWrongProgram) |
457
+ | 3008 / 3009 | wrong program address / not executable (InvalidProgramId / InvalidProgramExecutable) |
458
+ | 3010 | account must sign (AccountNotSigner; also a new keypair account a `create(payer, null, …)` makes) |
459
+ | 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
460
+ | 3012 | account not initialized: empty system account where a program account, a token account or a mint was expected (AccountNotInitialized; not for zero-copy accounts, which Anchor's AccountLoader reports as 3007) |
461
+ | 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
462
+ | 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
463
+ | 4102 | cast overflow (InvalidNumericConversion) |
464
+ | 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
465
+ | 5103 | sysvar unavailable |
466
+ | 5104 | index out of bounds (arrays, Vecs, remaining accounts, `pop()` on an empty Vec, `push` on a full FixedVec or `pushAll` past its room, a `slice` of the instruction data out of range, a stored `map` / `filter` result one element too small) |
467
+ | 5105 | string longer than the FixedString capacity |
468
+ | 5106 | missing or mismatched return data |
469
+ | 5107 | event larger than 1024 bytes |
470
+ | 5108 | empty Option used as a value |
471
+ | 5110 | out of heap building strings |
472
+ | 5111 | oracle check failed (unverified, stale, wrong feed, no samples) |
473
+ | 5112 | data enum is not the variant the code expected |
474
+ | 5113 | more accounts in one instruction (or one CPI) than the program takes: 32, or its `MAX_ACCOUNTS` |
475
+ | 5114 | a function with a result ended without returning one |
476
+ | 5115 | an optional account that was left out was used |
477
+ | 6000+ | your error enums' members, in declaration order (imported files first), then one `RequireFailed<N>` error (code 6000 + N, after the highest code) per distinct `require(cond, "message")` string |
478
+
479
+ A member's string is its message (the IDL's `msg`); `X = ""` leaves the message out, as an Anchor variant without
480
+ `#[msg]`. `/** @code 6200 */` before a member gives it that code, and the members after it continue from there (Anchor's
481
+ `Variant = 200`); codes only go up. `require(cond, "message")` errors come after the highest code.
482
+
483
+ Any of Anchor's own codes can be raised directly: `require(cond, AnchorError.RequireKeysEqViolated)` fails with 2502,
484
+ as `require_keys_eq!` does.
485
+
486
+ A code can also be computed at run time: `require(cond, code)` with a `u32` value fails with that code. This is how a
487
+ helper passes an error on as Rust's `?` does, when it returns the error as a value instead of failing (a price read
488
+ whose error the caller may record or ignore): `const r = price(feed); require(r.err === 0n, r.err);`. The code is
489
+ reported as it is (use one of your errors' codes, so clients can decode it); a zero code fails with 5100.
490
+
491
+ ## Which error a transaction gets
492
+
493
+ A transaction can break several checks; it fails with the first. Within each account's constraints the checks run in
494
+ the order Anchor's generated code runs them, so a transaction gets the same code under both:
495
+
496
+ 1. The account count (3005), then each account in parameter order: its type, signer (3010), `Mut` (2000), owner,
497
+ discriminator and size of a program account (3007 / 3012 / 3002 / 3003; a zero-copy one as Anchor's AccountLoader:
498
+ 3007 / 3001 / 3002, then 3003), token account or mint, program address.
499
+ 2. Two writable parameters naming one account (2040).
500
+ 3. The instruction's arguments (102).
501
+ 4. Each account in parameter order, its constraints in Anchor's order: seeds (2006), associated token account (owner
502
+ 2015, then address 2009), `has_one` (2001), `constraint(…)` (2003 or its error), owner (2004), executable (2007), address (2012), then `TokenOf` /
503
+ `MintOf` (2015, 2014, 2021 / 2016, 2017, 2022).
504
+
505
+ Where TypeSOL's order differs, only a transaction that breaks two of these checks at once sees it:
506
+
507
+ - Anchor decodes the arguments first, and checks `mut` with the constraints (after seeds and the associated token
508
+ account). TypeSOL keeps both earlier and later as above, which keeps binaries smaller.
509
+ - Too few accounts fails with 3005 before any account is checked; Anchor fails on the first account it cannot find.
510
+ - Accounts the instruction creates (`Init<…>`, `create(…)`) are created in the body, after every other check, where
511
+ Anchor creates them before checking the other accounts.
512
+ - TypeSOL refuses any two writable parameters naming one account (2040) unless one is `Dup<…>`, where Anchor only compares program and token
513
+ accounts: a signer passed as two writable parameters fails with 2040 here and later, or not at all, under Anchor.
514
+
515
+ <!-- docs/test-your-program.md -->
516
+
517
+ # Test your program
518
+
519
+ `typesol/testing` runs your program in LiteSVM, an in-process Solana runtime: no validator, no SOL, a few
520
+ milliseconds per transaction. Projects from `typesol init` already use it in `tests/<name>.test.ts`.
521
+
522
+ ```ts
523
+ import { testProgram, type TestProgram } from "typesol/testing";
524
+ import { beforeAll, expect, it } from "vitest";
525
+
526
+ let t: TestProgram;
527
+ beforeAll(async () => {
528
+ t = await testProgram("counter", import.meta.url); // builds the program of typesol.json and loads it
529
+ });
530
+
531
+ it("counts", async () => {
532
+ const alice = await t.wallet(); // a funded keypair (10 SOL)
533
+ const counter = await t.pda("counter", alice); // seeds: text, addresses or keypairs, bytes, bigints (u64)
534
+ t.ok(await t.send(alice, t.ix("initialize", {}, { authority: alice, counter })));
535
+ t.ok(await t.send(alice, t.ix("increment", { by: 5n }, { authority: alice, counter })));
536
+ expect((await t.account<{ count: bigint }>("Counter", counter))?.count).toBe(5n);
537
+ });
538
+ ```
539
+
540
+ ## Instructions
541
+
542
+ `t.pda(...seeds)` derives this program's PDA for the seeds; `t.pdaWithBump(...seeds)` gives `[address, bump]`, for an
543
+ instruction that takes the bump as an argument.
544
+
545
+ `t.ix(name, args, accounts, remaining?)` builds one instruction.
546
+
547
+ - **Accounts by name**, in camelCase or snake_case. Their signer and writable flags come from the IDL, and accounts
548
+ with a fixed address (the System Program, token programs, sysvars) are filled in, as are PDAs whose seeds are
549
+ constants, arguments or other accounts' keys (`t.ix("initialize", {}, { authority: alice })` derives `counter`). Pass a keypair for an account that
550
+ signs, an address otherwise, and `null` to leave an optional account out.
551
+ - **Arguments as plain values:** bigints or numbers for integers, address strings for Pubkeys, `null` for an empty
552
+ Option, objects for structs (camelCase or snake_case fields), arrays for Vecs.
553
+ - **Remaining accounts:** `[{ address, writable?, signer? }]`, where `signer` is the account's `KeyPairSigner` (it then
554
+ signs as a signer account; `writable` defaults to false).
555
+
556
+ `t.send(payer, ...ixs)` sends them in one transaction; keypairs given as accounts sign too.
557
+
558
+ ## Results
559
+
560
+ | Helper | Gives |
561
+ | --- | --- |
562
+ | `t.ok(res)` | the successful result, or throws with the error, its name (`NotAdmin`) and the program's logs |
563
+ | `t.errorCode(res)` | the custom error code of a failed transaction: 6000 + the member's index in your error enum, or a framework code ([errors.md](errors.md)) |
564
+ | `t.account(type, address)` | the account decoded by its IDL type (bigints, address strings), or `null` once closed. TypeSOL fixed layouts come back as their IDL structs: a `FixedString<N>` as `{ len, bytes }`, a `FixedVec<T, N>` as `{ len, items }` (the generated client gives strings and arrays) |
565
+ | `t.returned(instruction, res)` | the instruction's return data: an integer, boolean, Pubkey or struct |
566
+ | `t.balance(address)` | lamports |
567
+ | `t.errorName(code)` | the name of an error code: your program's, TypeSOL's or Anchor's |
568
+ | `t.connection` | `{ rpc, rpcSubscriptions }` answered by this LiteSVM, for the generated client: `counter.sendInstructions(t.connection, alice, [ix])`, `counter.accounts.Counter.fetch(t.connection.rpc, address)`, views, `resolve`, `watch` and `watchEvents` (as on a cluster: `watch` yields when a later transaction changes the account, not at once; `watchEvents` gets transactions sent after it subscribed, failed ones included in the stream and skipped by the client) |
569
+
570
+ ## Tokens and time
571
+
572
+ | Helper | Does |
573
+ | --- | --- |
574
+ | `t.mint({ authority, decimals?, supply?, freezeAuthority?, tokenProgram?, address? })` | writes a mint straight into the VM, as CreateAccount + InitializeMint2 leave it (SPL Token unless `tokenProgram` is Token-2022; no extensions), and returns its address |
575
+ | `t.tokenAccount({ mint, owner, amount?, tokenProgram?, address? })` | writes a token account holding `amount`; pass `address` for an associated token account |
576
+ | `t.tokenBalance(address)` | the amount a token account holds, or `null` when it does not exist |
577
+ | `t.warp({ unixTimestamp?, slot?, seconds? })` | moves the Clock: to a timestamp or slot, or forward by `seconds` |
578
+
579
+ ## Epochs and staking
580
+
581
+ LiteSVM's `warpToSlot` leaves `Clock.epoch` where it was, and its StakeHistory stays empty, so the Stake program takes
582
+ every delegation as fully active one epoch after it was made. For a program that stakes, these helpers make epochs and
583
+ warmup / cooldown behave as on a cluster:
584
+
585
+ | Helper | Does |
586
+ | --- | --- |
587
+ | `warpToEpoch(svm, epoch, { secondsPerSlot? })` | moves the Clock to the first slot of `epoch` by the VM's EpochSchedule (warmup epochs included): slot, epoch, leader schedule epoch, `unixTimestamp` (+0.4 s a slot by default) and `epochStartTimestamp`; expires the blockhash. `nextEpoch(svm)` moves one epoch |
588
+ | `new StakeCluster(svms, opts?)` | one or more LiteSVMs that get the same Clock, EpochSchedule and StakeHistory. `cluster.nextEpoch()` / `cluster.warpToEpoch(e)` end each epoch as a cluster does: the StakeHistory gets the epoch's entry (the sum of every stake account's activation at that epoch, plus `base`, the rest of the cluster), then the Clock moves on. `cluster.activation(stake)` gives a stake account's `{ effective, activating, deactivating }` now |
589
+ | `stakeActivation(delegation, epoch, history, newRateActivationEpoch?, { math? })` | a delegation's activation at an epoch: an exact port of the Stake program's `stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0) |
590
+ | `createVoteAccount(svm, payer, { node?, voter?, withdrawer?, commission? })` | a vote account made by the Vote program; returns its address |
591
+ | `createStakeAccount(svm, payer, { staker, withdrawer, lamports, lockup? })` | a stake account made by the Stake program, `lamports` in all (rent-exempt minimum included) |
592
+ | `delegateStake(svm, payer, { stake, vote, staker? })` | delegates it |
593
+ | `readStakeAccount(svm, address)` | the account's StakeStateV2: `{ kind: "Stake", meta, stake: { delegation, creditsObserved }, stakeFlags }`, `Initialized`, `Uninitialized` or `RewardsPool`; `null` when it does not exist |
594
+ | `readStakeHistory(svm)` / `writeStakeHistory(svms, entries)` | the StakeHistory sysvar as a `Map` of epoch → `stakeHistoryEntry(effective, activating, deactivating)` |
595
+
596
+ ```ts
597
+ const cluster = new StakeCluster([original.svm, port.svm], { base: stakeHistoryEntry(1000n * SOL) });
598
+ const vote = await createVoteAccount(original.svm, payer);
599
+ // ... the program under test delegates a stake account
600
+ cluster.nextEpoch(); // 9% of the cluster's effective stake may warm up per epoch: 90 SOL here
601
+ expect(cluster.activation(stake).effective).toBe(90n * SOL);
602
+ ```
603
+
604
+ - **The rest of the cluster.** `base` defaults to 400M SOL effective with nothing activating or deactivating: as on
605
+ mainnet, a delegation under 36M SOL warms up in one epoch. Give a smaller `effective`, or `activating` /
606
+ `deactivating` above 9% of it, to make warmup and cooldown take several epochs; `base` may also be a function of
607
+ the epoch. With `allStakeAccounts: false` only the accounts passed to `cluster.track(...)` count.
608
+ - **One history for every VM.** The delegations are read from the first VM; the Clock and EpochSchedule of the first
609
+ VM are copied to the others when the cluster is made, so a differential test's two VMs see the same sysvars.
610
+ - **No gaps.** The Stake program finds an entry by its distance from the newest one, which must be the previous
611
+ epoch's: a history that skips an epoch is misread. The cluster writes one entry per epoch it passes; it refuses a VM
612
+ whose history stops before the previous epoch or has an entry for the current epoch or a later one (an epoch that
613
+ has not ended), and `cluster.warpToEpoch` / `nextEpoch` refuse to go on once the Clock was moved past the history
614
+ some other way. Warping a VM with stake accounts by `warpToEpoch` alone leaves the history behind.
615
+ - **A new LiteSVM's slot.** Its Clock is at epoch 0 but at slot 454,464,000; the first warp moves the slot back to the
616
+ first slot of the epoch warped to (32 for epoch 1 by the default warmup schedule), the timestamps forward.
617
+ - **Float or integer.** The Stake program in LiteSVM 1.6.1 computes warmup and cooldown with f64 (the algorithm
618
+ solana-stake-interface 4.3.0 keeps as the deprecated `stake_activating_and_deactivating`); Stake program 5.1
619
+ (SIMD-0391) uses basis-point integers. They differ by a few lamports once amounts pass 2^53 lamports (about 9M SOL).
620
+ `StakeCluster` uses `math: "float"` by default, so its history and `activation` match LiteSVM to the lamport;
621
+ `stakeActivation` uses the integer algorithm unless given `{ math: "float" }`. Both take the 9% rate from epoch 0
622
+ (`newRateActivationEpoch` 0, as the Stake program has it); `null` gives the original 25%.
623
+ - **Rent.** In LiteSVM 1.6.1 the Stake program holds back the Rent sysvar's minimum for 200 bytes
624
+ (`svm.minimumBalanceForRentExemption(200n)`), which is less than the `rentExemptReserve` its Initialize stores.
625
+
626
+ ## Accounts from a cluster
627
+
628
+ To test against accounts that exist on mainnet (a mint, an oracle, another program), list them in `typesol.json` as
629
+ `"clone": ["<address>", …]` and run `typesol clone --url mainnet-beta` once (or `typesol clone <address>…`). They are
630
+ written to `tests/accounts/`, which `testProgram` loads into its LiteSVM before your first test; commit the directory so
631
+ the tests run offline. `loadClonedAccounts(svm, dir)` does the same for a LiteSVM of your own.
632
+
633
+ `t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else. `programHarness(svm, programId, idl)` gives the same helpers for a
634
+ program you loaded yourself, and `svmConnection(svm)` the RPC pair alone (for any LiteSVM, e.g. one with an Anchor
635
+ program loaded). Transactions sent through it run at once; `getProgramAccounts` (`fetchAll`) sees the accounts those
636
+ transactions named, plus any you `track(...)`.
637
+
638
+ The module needs `litesvm` and `@anchor-lang/core`, which `typesol init` adds to `devDependencies`.
639
+
640
+ <!-- docs/cli.md -->
641
+
642
+ # CLI reference
643
+
644
+ `typesol <command> --help` prints the same text for one command. Options are checked: an unknown option is an
645
+ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy, …), **2** usage error,
646
+ **3** `verify` mismatch.
647
+
648
+ | Command | What it does |
649
+ | --- | --- |
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. |
651
+ | `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). |
656
+ | `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
+ | `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`). |
660
+ | `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
+ | `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
+ | `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. |
664
+ | `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
+ | `typesol help <command>` | Same as `typesol <command> --help`. |
666
+ | `typesol --version` | Print the version. |
667
+
668
+ ## typesol.json
669
+
670
+ ```json
671
+ {
672
+ "programs": { "vault": { "path": "programs/vault.ts", "address": "…recorded on first build…" } },
673
+ "out": "target",
674
+ "sbpf": "v0"
675
+ }
676
+ ```
677
+
678
+ `"clone": ["<address>", …]` lists the cluster accounts `typesol clone` copies for the tests, and `"accounts"` where
679
+ they are kept (default `tests/accounts`). `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
680
+ safe and out of git: it is the program's address, and it is needed to deploy it again. A clone without
681
+ it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
682
+
683
+ ## Editor
684
+
685
+ `typesol init` projects load `typesol/ts-plugin` from `programs/tsconfig.json`: besides TypeScript's errors, the editor
686
+ underlines what the TypeSOL compiler refuses (an unsupported construct, a constraint that cannot hold…), for the text
687
+ being edited (unsaved changes in every open file), once TypeScript itself has nothing to report. It checks the program
688
+ entries listed in `typesol.json` and shows each problem in the file it is in, the entry or any file it imports. The
689
+ compiler runs inside the editor's TypeScript server once it has loaded (a check takes milliseconds; the first ones run
690
+ `typesol check --json --files` as a child process). Editors load tsconfig plugins from the project's own TypeScript:
691
+ `typesol init` writes `.vscode/settings.json` so VS Code offers to switch to it ("Use Workspace Version"). To add the
692
+ plugin to an existing project:
693
+
694
+ ```json
695
+ { "compilerOptions": { "plugins": [{ "name": "typesol/ts-plugin" }] } }
696
+ ```
697
+
698
+ <!-- docs/client.md -->
699
+
700
+ # TypeScript client
701
+
702
+ Every `typesol build` writes a typed client next to the program: `<out>/<name>/<name>.client.ts`. It is one file, it
703
+ depends only on [`@solana/kit`](https://github.com/anza-xyz/kit) (8.5 or later), and it is rewritten on every build, so
704
+ it always matches the program. `typesol client <idl.json>` writes the same kind of client from an Anchor IDL (Anchor 0.30+
705
+ and 1.x), so one client style covers TypeSOL programs and the Anchor programs they talk to. `typesol client --address
706
+ <program id> --url <rpc>` reads the IDL from the chain instead: the canonical Program Metadata IDL (`typesol idl
707
+ publish`, Codama), else Anchor's IDL account (`anchor idl init`), so any deployed Anchor or TypeSOL program with a
708
+ published IDL gets a client from its address alone.
709
+
710
+ ```ts
711
+ import { ledgerbook } from "./target/ledgerbook/ledgerbook.client.js";
712
+
713
+ // Instructions: fixed addresses (System Program, token programs, ...) and PDAs are filled in from the IDL.
714
+ const create = await ledgerbook.create({ admin: signer }, { title: "grants", approver: null });
715
+
716
+ // PDAs
717
+ const [book] = await ledgerbook.pdas.book({ admin: signer.address, title: "grants" });
718
+ const file = await ledgerbook.file({ who: signer, book }, { amount: 100n, note: "rent", memo: null });
719
+
720
+ // Accounts: decode bytes you already have, or fetch through an RPC.
721
+ const bookData = await ledgerbook.accounts.Book.fetch(rpc, book); // { title: string, approver: Address | null, entries: [...], ... }
722
+
723
+ // Send and confirm (one transaction, signers in the accounts sign too), or simulate
724
+ const signature = await ledgerbook.sendInstructions({ rpc, rpcSubscriptions }, signer, [create, file]);
725
+ const { err, logs, unitsConsumed, returnData } = await ledgerbook.simulate(rpc, signer, [file]);
726
+
727
+ // Errors: by name, from a kit SolanaError, a LiteSVM result, a simulation message or a code.
728
+ if (ledgerbook.isError(e, "NotApprover")) { /* ... */ }
729
+ ledgerbook.errorCode(e); // 6002
730
+
731
+ // Events written by `emit`, from a transaction's log messages
732
+ for (const ev of ledgerbook.parseEvents(logs)) if (ev.name === "Filed") ev.data.amount;
733
+
734
+ // Return data of an instruction that returns a value, or the value itself by simulation (Anchor's `.view()`)
735
+ ledgerbook.returns.total(returnDataBytes); // bigint
736
+ await ledgerbook.views.total(rpc, signer, { book }, { status: Status.Approved }); // bigint, nothing sent
737
+
738
+ // Every Book of the program, or those with given bytes at an offset (after the 8-byte discriminator)
739
+ const books = await ledgerbook.accounts.Book.fetchAll(rpc); // [{ address, data }]
740
+ const several = await ledgerbook.accounts.Book.fetchMultiple(rpc, [book, otherBook]); // (Book | null)[]
741
+
742
+ // Live updates, until the AbortSignal aborts
743
+ for await (const book of ledgerbook.accounts.Book.watch(rpcSubscriptions, address, { abortSignal })) render(book);
744
+ for await (const { signature, event } of ledgerbook.watchEvents(rpcSubscriptions, { abortSignal, rpc })) show(event); // with rpc: emitCpi events too
745
+
746
+ // Remaining accounts go after the instruction's own (Anchor's `.remainingAccounts([...])`)
747
+ await ledgerbook.approveMany({ approver: signer, book }, { indices: [0n, 1n] }, [{ address: extra, role: AccountRole.WRITABLE }]);
748
+
749
+ // has_one accounts that do not sign, read from the account that names them (Anchor resolves `relations` the same way)
750
+ const accounts = await ledgerbook.resolve.someInstruction(rpc, { book }, { signer }); // signers, and what book's fields name
751
+
752
+ // Events of a fetched transaction (getTransaction, json): log events and emitCpi events from inner instructions
753
+ ledgerbook.eventsOf(await rpc.getTransaction(signature, { encoding: "json", maxSupportedTransactionVersion: 0 }).send());
754
+ ```
755
+
756
+ Signer accounts take a `TransactionSigner`, which kit uses to sign; an `Address` works too when you sign separately.
757
+ Kit's own transaction functions work with the instructions as well; `sendInstructions` is that pipeline in one call.
758
+
759
+ ## What the client contains
760
+
761
+ | | |
762
+ | --- | --- |
763
+ | `<program>.<instruction>(accounts, args)` | Builds the `Instruction`. Accounts with a fixed address and PDAs whose seeds are constants, arguments (an Option one with its default too: Anchor's `id.unwrap_or(0)`) or other accounts' keys are optional and filled in; pass one to override. An optional account passed as `null` is left out (sent as the program id, the convention TypeSOL and Anchor share); left undefined, it is filled in like any other. |
764
+ | `<program>.<instruction>(accounts, args, remaining?)` | The same, with remaining accounts appended in order (kit `AccountMeta`s). |
765
+ | `<program>.accounts.<Name>` | `decode(bytes)`, `encode(value)`, `fetch(rpc, address)`, `fetchMaybe(rpc, address)`, `fetchMultiple(rpc, addresses)`, `fetchAll(rpc, filters?)` (getProgramAccounts by discriminator, plus `{ offset, bytes }` filters), `watch(rpcSubscriptions, address, { abortSignal })`, `discriminator`. `decode` checks the discriminator. |
766
+ | `<program>.pdas.<account>(seeds)` | The PDA (address and bump) for each account an instruction derives, also one seeded from its own fields (from the field values). |
767
+ | `<program>.returns.<instruction>(bytes)` | Decodes return data. |
768
+ | `<program>.resolve.<instruction>(rpc, accounts, args?, { signer? })` | Fills in what needs the chain or the wallet: signer accounts left out (`options.signer`, the default signer, like Anchor's provider wallet), `has_one` accounts that do not sign (read from the account that names them), and PDAs seeded from another account's fields, scalars, strings or bytes (`seeds = [b"vault", book.owner]`: the account is read, then the PDA derived). Given accounts are kept. |
769
+ | `<program>.views.<instruction>(rpc, feePayer, accounts, args)` | Simulates an instruction that returns a value and decodes it (throws with the logs if it fails). |
770
+ | `<program>.sendInstructions(connection, feePayer, instructions)`, `simulate(rpc, feePayer, instructions)` | One transaction sent and confirmed (kit's sendAndConfirm), or simulated without signatures (error, logs, units, this program's return data). |
771
+ | `<program>.errors`, `errorCode(e)`, `isError(e, name)` | The program's errors (6000+), and for TypeSOL programs also every Anchor framework error (`AnchorError` and the constraints raise them) and TypeSOL's runtime errors. |
772
+ | `<program>.parseEvents(logs)`, `parseCpiEvents(data)`, `eventsOf(tx)`, `watchEvents(rpcSubscriptions, { abortSignal })` | Events from `Program data:` log lines, from `emitCpi` inner instructions (bytes or base58), from a fetched transaction (both), or live from log subscriptions. |
773
+ | Types and codecs | Every defined type as a TypeScript type (`Book`, the decoded value) and an input type (`BookArgs`, which also accepts `number` for 64- and 128-bit integers), with a kit codec (`getBookCodec()`). |
774
+
775
+ Types follow the program's TypeScript: `u64`/`i64`/`u128`/`i128` are `bigint` (inputs accept `number` too), smaller
776
+ integers and floats are `number`, `Pubkey` is kit's `Address`, `string` and `FixedString<N>` are `string`, `Option<T>` is
777
+ `T | null`, unit enums are const objects (`Status.Pending`, also usable as a type), and data enums are unions on `kind`,
778
+ as in the program. Names are camelCase. For Anchor IDLs, data enums use `__kind`, as Codama-generated clients do. The
779
+ file uses no TypeScript-only syntax (no `enum`), so it also runs under Node's type stripping.
780
+
781
+ ## Safety
782
+
783
+ An IDL can come from anywhere, so `typesol client` refuses one whose names are not identifiers, whose discriminators or
784
+ seed bytes are not bytes, or whose error codes are not integers, before anything reaches the output. Older (pre-0.30)
785
+ Anchor IDLs are refused with a hint to convert them (`anchor idl convert`).
786
+
787
+ ## Limits
788
+
789
+ - **Errors are matched by code, not by program**: a program this one calls can raise the same error code. Events are
790
+ this program's own: `parseEvents` follows the `Program <id> invoke` / `success` / `failed` lines and reads a
791
+ `Program data:` line only while this program is the innermost one running, and `eventsOf` reads only the `emitCpi`
792
+ inner instructions that call this program (it needs `tx.transaction`'s account keys for that). `parseCpiEvents(data)`
793
+ 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.
797
+ - **Anchor IDLs**: zero-copy (`bytemuck`) accounts decode and encode at their `#[repr(C)]` offsets as the program sees
798
+ them on SBF (padding included; `packed` and `align` honored; 128-bit integers align to 8). Generic types become one
799
+ type per use with concrete arguments (`Pair<u64, 2>` is `PairU64N2`). Left out, with a note: zero-copy types with
800
+ Rust's own layout (`repr(Rust)`) or holding a non-zero-copy type, and the generic definitions themselves.
801
+ - **In tests**: `svmConnection(svm)` from `typesol/testing` answers the client's RPC calls from LiteSVM, and
802
+ `testProgram(...)` has it as `t.connection` ([test-your-program.md](test-your-program.md)).
803
+ - `watchEvents` reads log events of transactions that succeeded (a failed one is skipped); with `rpc` it also fetches each transaction in which the program invoked itself and
804
+ reads its `emitCpi` events (log subscriptions do not carry inner instructions).
805
+
806
+ <!-- docs/migrate-from-anchor.md -->
807
+
808
+ # Migrate from Anchor
809
+
810
+ TypeSOL programs speak Anchor's wire format: the same instruction and account discriminators, Borsh arguments, an
811
+ Anchor-format IDL, the same error numbering and event logs. A ported program can keep its clients. This page maps
812
+ Anchor's constructs to TypeSOL's and shows the porting workflow. For one complete program ported this way, with the
813
+ original side by side, the checks run against it and its cost, see [Case study: porting Anchor's escrow](case-study-escrow.md).
814
+
815
+ ## Start from the IDL
816
+
817
+ ```sh
818
+ anchor build # in the Anchor project: target/idl/my_program.json
819
+ npx @typesol/cli init my-program && cd my-program
820
+ 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
822
+ ```
823
+
824
+ `typesol port` writes the account structs, enums, errors and one function per instruction with its accounts and
825
+ arguments, each body failing with `NotPorted` until you write it. It keeps instruction discriminators, account names
826
+ and error codes. Its notes (on stderr) list what an existing Anchor client would see differently; see
827
+ [Account data](#account-data) below. Then, for each instruction:
828
+
829
+ 1. Give each account its real type: `Account<T>` / `Mut<T>` for your structs, `Init<T>` for one the instruction creates,
830
+ token types for token accounts (the table below).
831
+ 2. Move the constraints from `#[account(...)]` into the parameter types or the body.
832
+ 3. Port the body. Integers are `bigint`s with `n` literals, and every `+ - * / %` is checked.
833
+ 4. Test with `typesol/testing` ([test your program](test-your-program.md)), then compare the IDLs.
834
+
835
+ ## Accounts and constraints
836
+
837
+ | Anchor | TypeSOL |
838
+ | --- | --- |
839
+ | `#[derive(Accounts)] struct Ctx` + `ctx.accounts.x` | the instruction's parameters, in the same order |
840
+ | a composite field, `pub pool: PoolAccounts<'info>` + `ctx.accounts.pool.vault` | an account group: `export interface PoolAccounts { vault: Mut<TokenAccount>; … }`, the parameter `pool: PoolAccounts`, and `pool.vault` |
841
+ | `Signer<'info>` / `#[account(mut)] Signer` | `Signer` / `Mut<Signer>` |
842
+ | `Account<'info, T>` / `#[account(mut)]` | `Account<T>` / `Mut<T>` |
843
+ | `#[account(init, payer = p, space = …, seeds = […], bump)]` | `Init<T>`, then `const bump = acct.create(p, ["seed", other.key])` (space is computed; `acct.create(p, […], 8n + 64n)` keeps an explicit `space`) |
844
+ | `#[account(init, payer = p, space = …)]` (a keypair account) | `Init<T>`, then `acct.create(p, null)` (the account signs the transaction, as in Anchor) |
845
+ | `init_if_needed` | `InitIfNeeded<T>`, then `const created = acct.createIfNeeded(p, seeds)` |
846
+ | `seeds = [b"vault", owner.key().as_ref()], bump = vault.bump` | `Seeds<Mut<Vault>, ["vault", "@owner"], "bump">` |
847
+ | `seeds = [b"offer", offer.maker.as_ref(), offer.id.to_le_bytes().as_ref()]` | `Seeds<…, ["offer", "@offer.maker", "@offer.id"], "bump">` |
848
+ | `has_one = owner` | `HasOne<Mut<T>, "owner">` |
849
+ | `has_one = owner @ ErrorCode::NotOwner` (also `address`, `owner`, `signer`, `mut` with `@ …`) | `HasOne<Mut<T>, "owner", ErrorCode.NotOwner>`; `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` |
850
+ | `close = destination` | `CloseTo<Mut<T>, "destination">`, or `close(acct, destination)` in the body |
851
+ | `address = ADMIN` | `Address<AccountInfo, "Admin1111…">` |
852
+ | `owner = program`, `executable` | `Owner<A, "…">`, `Executable<A>` |
853
+ | `constraint = expr @ MyError::X` (or without an error: 2003) | `constraint(acct, expr, MyError.X)` (or `constraint(acct, expr)`) at the start of the body: it runs with `acct`'s checks, where Anchor runs it |
854
+ | `realloc = n, realloc::payer = p` | `realloc(acct, n, p)` |
855
+ | `Option<Account<'info, T>>` | `Mut<T> \| null` (the client passes the program id to leave it out) |
856
+ | `UncheckedAccount` / `AccountInfo` | `AccountInfo` / `Mut<AccountInfo>`: check what you rely on yourself |
857
+ | `SystemAccount<'info>` | `SystemAccount` / `Mut<SystemAccount>` |
858
+ | `Migration<'info, From, To>` | `Migrate<From, To>`, then `acct.migrate(payer, value)`; the old struct keeps its on-chain discriminator with `/** @discriminator account:<OldName> */` |
859
+ | `#[account(discriminator = …)]` | `/** @discriminator <preimage or 0x8 bytes> */` on the struct |
860
+ | `AccountLoader<T>` with `#[account(zero)]` | `Zeroed<T>` (TypeSOL reads every account in place: no copy to avoid) |
861
+ | `Account<T>` with `#[account(zero)]` (Borsh) | `Zeroed<T>` of a `/** @layout borsh */` struct |
862
+ | `#[account(signer)]` on a non-`Signer` account | `Signed<A>`, e.g. `Signed<Zeroed<Multisig>>` |
863
+ | `seeds = [multisig.key().as_ref()], bump = multisig.nonce` | `Seeds<A, ["@multisig"], "@multisig.nonce">` |
864
+ | `Program<'info, System>` | `SystemProgram` |
865
+ | `Program<'info, Token>` / `Token2022` / `Interface<'info, TokenInterface>` | `TokenProgram` / `Token2022Program` / `TokenInterface` |
866
+ | `Account<'info, TokenAccount>` / `Account<'info, Mint>` (`InterfaceAccount`) | `TokenAccount` / `Mint` (`Mut<…>` when written) |
867
+ | `token::mint = m, token::authority = a` | `TokenOf<TokenAccount, "m", "a">` (2014 / 2015), or `HasOne<TokenAccount, "mint" \| "owner">` when the parameters have those names; `mint::authority = a, mint::freeze_authority = f` on an existing mint: `MintOf<Mint, "a", "f">` (2016 / 2017) |
868
+ | `mint::token_program = tp` / `token::token_program = tp` | `MintOf<Mint, never, never, "tp">` / `TokenOf<TokenAccount, never, never, "tp">` (2022 / 2021) |
869
+ | `extensions::metadata_pointer::authority = a, …` (with `mint::…`) | `mint.create(p, …, { metadataPointer: { authority: a.key, metadataAddress: mint.key }, … })`: transferHook, closeAuthority, permanentDelegate, nonTransferable, groupPointer, groupMemberPointer and more |
870
+ | `#[account(init, payer = p, seeds = […], bump, mint::decimals = 6, mint::authority = a, mint::freeze_authority = f)]` | `Init<Mint>`, then `const bump = mint.create(p, […], 6n, a.key, f.key)` (`null` seeds: a keypair mint; `InitIfNeeded<Mint>` + `createIfNeeded`) |
871
+ | `#[account(init, payer = p, seeds = […], bump, token::mint = m, token::authority = a)]` | `Init<TokenAccount>`, then `vault.create(p, […], m, a.key)` (`InitIfNeeded<TokenAccount>` + `createIfNeeded`) |
872
+ | `associated_token::mint = m, associated_token::authority = a` | `Ata<TokenAccount, "a", "m">`; `Ata<Init<TokenAccount>, "a", "m">` creates it |
873
+ | `ctx.remaining_accounts` | `remainingAccounts()` |
874
+ | `#[account(mut, dup)]` | `Dup<Mut<T>>` (in-place accounts only) |
875
+ | `sysvar::instructions` (`load_current_index_checked`, `load_instruction_at_checked`), `get_stack_height()` | `InstructionsSysvar`: `currentIndex()`, `get(i)`, `.length`; `stackHeight()` |
876
+ | `ctx.bumps.vault` | the value `create` returns, or `acct.pdaBump` |
877
+
878
+ ## Account data
879
+
880
+ | Anchor | TypeSOL |
881
+ | --- | --- |
882
+ | `#[account] pub struct T { … }` | `export interface T { … }` |
883
+ | `u8` … `u128`, `i8` … `i128`, `bool`, `Pubkey` | `u8` … `u128`, `i8` … `i128`, `boolean`, `Pubkey` |
884
+ | `[T; N]` | `FixedArray<T, N>` |
885
+ | `String` with `#[max_len(n)]` | `FixedString<N>`: a u32 length and N bytes, always N bytes long |
886
+ | `Vec<T>` with `#[max_len(n)]` | `Vec<T>` (any number, declared anywhere, stored after the fixed-size fields; it grows with `push(v, payer)`), or `FixedVec<T, n>`: a u32 length and room for n, always 4 + n × size bytes; in a `@layout borsh` struct, `Vec<T>` is Anchor's own, bounded only by the account |
887
+ | `Option<T>` | `Option<T>`: fixed size (1 + size of T) |
888
+ | `#[derive(AnchorSerialize…)] enum` | `export enum` (unit variants) or a data enum `type A = { kind: "X"; … } \| …` |
889
+
890
+ TypeSOL keeps account data at a fixed layout by default, so three Anchor layouts differ: a Borsh `String` is
891
+ variable-length (TypeSOL uses `FixedString<N>`), a Borsh `Option` takes 1 byte when empty (TypeSOL always reserves the
892
+ value), and an Anchor `Vec` stays where it is declared (TypeSOL stores growable Vecs after the fixed-size fields; a
893
+ `FixedVec<T, N>` keeps its place but always takes its full capacity, where Anchor packs the elements and moves the
894
+ fields after them).
895
+
896
+ To keep an Anchor program's existing accounts, mark the struct `/** @layout borsh */`: it is then stored exactly as
897
+ Anchor stores it (`FixedString<N>` / `FixedVec<T, N>` / `Option<T>` become Borsh String / Vec / Option, N being the
898
+ `#[max_len]`), its IDL type is Anchor's, and the upgraded program reads and writes the accounts in place. `typesol port`
899
+ adds it for you. It costs some compute (the account is unpacked and packed in every instruction that uses it) but stays
900
+ several times cheaper than Anchor. Without it, accounts that use these types need a migration (or a new program) rather
901
+ than an in-place upgrade. Everything else, including instruction arguments (`String`, `Option`, `Vec` are Borsh there),
902
+ matches byte for byte. A `@layout borsh` struct passed as a whole argument, returned or emitted is Borsh too, so an
903
+ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Option` fields keeps its client bytes.
904
+
905
+ ## Code
906
+
907
+ | Anchor | TypeSOL |
908
+ | --- | --- |
909
+ | `pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()>` | `export function deposit(owner: Mut<Signer>, vault: Mut<Vault>, …, amount: u64): void` |
910
+ | `-> Result<u64>` / a struct | `: u64` / a struct: sent as return data, listed in the IDL |
911
+ | `#[error_code] enum MyError { #[msg("…")] X }` | `export enum MyError { X = "…" }` (codes from 6000, in order; `X = ""` for a variant without `#[msg]`; `/** @code 6200 */` before a member for Anchor's `Y = 200`) |
912
+ | `f64` fields (events) | `f64`, made from the bits the program computed (`f64FromBits`) |
913
+ | `Option<[T; N]>`, structs of Options inside Options (`BankConfigOpt`) | `Option<FixedArray<T, N>>`; a struct argument holding Options is Borsh as Anchor sends it; an event holding one is `/** @layout borsh */` (`typesol port` writes it so) |
914
+ | `#[account(zero_copy)]`, `#[repr(C)]` types with `_pad` fields and `WrappedI80F48` | a fixed-layout struct with `/** @serialization bytemuck */` and `/** @repr c */`, `/** @idlName _pad0 */` on the padding, `/** @bytes */ value: i128` for the wrapped number ([language.md](language.md)) |
915
+ | `require!(c, MyError::X)`, `err!(MyError::X)` | `require(c, MyError.X)`, `require(false, MyError.X)` |
916
+ | `require_keys_eq!(a, b)`, `err!(ErrorCode::AccountDidNotDeserialize)` (Anchor's own codes) | `require(a === b, AnchorError.RequireKeysEqViolated)` (or your own error), `require(false, AnchorError.AccountDidNotDeserialize)` |
917
+ | `init_if_needed` + `extensions::…` on a mint | `mint.createIfNeeded(…, { metadataPointer: {…}, … })`: an existing mint is checked as Anchor checks it (2024–2039) |
918
+ | `a.checked_add(b).ok_or(…)?` | `a + b` (every operation is checked; overflow aborts with 5100) |
919
+ | `emit!(Ev { … })` / `emit_cpi!` | `emit<Ev>({ … })` / `emitCpi<Ev>({ … }, eventAuthority, self)` |
920
+ | `msg!("…")` | `log("…")` |
921
+ | `Clock::get()?.unix_timestamp`, `.slot` | `now()`, `currentSlot()` |
922
+ | `Rent::get()?.minimum_balance(n)` | `rentExempt(n)`, `minimumBalance(acct)` |
923
+ | `system_program::transfer(CpiContext::new(…), lamports)` | `systemProgram.transfer(from, to, lamports)` |
924
+ | `token::transfer_checked(CpiContext::new_with_signer(…, seeds), amount, decimals)` | `tokenProgram.transferChecked(from, mint, to, authority, amount, ["seed", key, bump])` |
925
+ | `token::mint_to_checked` / `burn_checked` / `approve_checked` | `tokenProgram.mintToChecked(mint, to, authority, amount)` / `burnChecked(from, mint, authority, amount)` / `approveChecked(source, mint, delegate, owner, amount)` |
926
+ | `system_program::transfer(CpiContext::new_with_signer(…, &[vault_seeds]), lamports)` | `systemProgram.transfer(vault, to, lamports, ["vault", owner.key, bump])` |
927
+ | `invoke_signed(&ix, infos, &[seeds_a, seeds_b])` | `invoke(program, accounts, data, [seedsA, seedsB])` |
928
+ | `let (_, data) = get_return_data().unwrap(); Quote::try_from_slice(&data)?` | `const quote = returnData<Quote>(program)` (a `@layout borsh` struct when it holds Options, strings or Vecs) |
929
+ | `[test.validator.clone]` in Anchor.toml | `"clone": [...]` in typesol.json and `typesol clone` (loaded by `testProgram`) |
930
+ | `anchor_spl::metadata::update_metadata_accounts_v2` | `metadataProgram.updateMetadataAccountsV2(…)` |
931
+ | `anchor_spl::metadata::burn_nft` / mpl `BurnV1` | `metadataProgram.burnV1(…)` |
932
+ | `Sysvar<StakeHistory>` / `StakeHistory::get(epoch)` | `StakeHistorySysvar`: `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)`, `has(epoch)` |
933
+ | `EpochSchedule::get()?`, `LastRestartSlot::get()?` | `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()`; `lastRestartSlot()` |
934
+ | `anchor_spl::stake::{authorize, deactivate_stake, withdraw}`, `delegate_stake` | `stakeProgram.authorize / deactivate / withdraw / delegate(…)` |
935
+ | `RandomnessAccountData::parse(…)?.get_value(&clock)?` (switchboard-on-demand) | `randomness: SwitchboardRandomness`, `randomness.value()` / `valueU64()`, `randomness.seedSlot` |
936
+ | `pub fn fallback(program_id, accounts, data)` | `/** @fallback */ export function fallback(): void` with `instructionData()` and `remainingAccounts()` |
937
+ | `#[access_control(check(&ctx))]` | call the check first in the body (`check(vault, owner)`), or `constraint(acct, …)` for one that belongs with an account's checks |
938
+ | `spl_memo::build_memo` + `invoke` | `memoProgram.memo(text, [signers])` |
939
+ | `UncheckedAccount` at the SlotHashes address | `SlotHashesSysvar`: `latestSlot`, `latestHash` |
940
+ | `spl_token_group_interface` CPIs (`initialize_group`, `initialize_member`, …) | `token.initializeTokenGroup(…)`, `initializeGroupMember(…)`, `updateGroupMaxSize(…)`, `updateGroupAuthority(…)` |
941
+ | `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
942
+ | `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
943
+ | `multisig.owners = owners` (a `Vec` argument into account data) | the same |
944
+ | `declare_program!(other)` / CPI to another Anchor program | `typesol cpi other.json` generates typed helpers |
945
+ | `for x in v.iter()` | `for (const x of v)` |
946
+ | `v.iter().any(\|x\| …)`, `.all`, `.position`, `.find`, `.fold(init, …)`, `.contains(&x)` | `v.some((x) => …)`, `every`, `findIndex`, `find`, `reduce((acc, x) => …, init)`, `includes(x)` |
947
+ | 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
+ | `x.unwrap_or(d)` | `x ?? d` |
949
+ | `fn max<T: PartialOrd>(a: T, b: T) -> T` | `function max<T extends bigint>(a: T, b: T): T` (one copy per type used) |
950
+
951
+ ## Tooling
952
+
953
+ | Anchor | TypeSOL |
954
+ | --- | --- |
955
+ | `anchor init` | `typesol init` (`--template vault` / `escrow`) |
956
+ | `anchor build` | `typesol build` (writes the IDL and a TypeScript client next to the binary) |
957
+ | `anchor test` (mocha, bankrun) | `npm test` with `typesol/testing` in LiteSVM |
958
+ | `anchor deploy` | `typesol deploy` ([deploy to mainnet](mainnet.md)) |
959
+ | `anchor idl init` / `upgrade` | `typesol idl publish` |
960
+ | `anchor verify` | `typesol verify` (reads the deployed program and IDL from the cluster) |
961
+ | `@coral-xyz/anchor` `Program` client | the generated `<name>.client.ts` on `@solana/kit`, or Anchor's client with the IDL |
962
+
963
+ <!-- docs/troubleshooting.md -->
964
+
965
+ # Troubleshooting
966
+
967
+ **"Solana SBF SDK not found"** — install the Agave CLI (https://docs.anza.xyz/cli/install) and run
968
+ `cargo-build-sbf --version` once. TypeSOL looks in `~/.local/share/solana/install/active_release/bin/platform-tools-sdk/sbf`
969
+ and next to `cargo-build-sbf` on PATH; set `TYPESOL_SBF_SDK` to a `platform-tools-sdk/sbf` directory otherwise.
970
+
971
+ **"platform-tools missing" / "no SBPF v2 libraries"** — `cargo-build-sbf --force-tools-install`.
972
+
973
+ **Windows** — not tested; use WSL2 with the Linux Agave CLI.
974
+
975
+ **Node errors such as `ERR_UNKNOWN_FILE_EXTENSION` or `ERR_REQUIRE_ESM`** — use Node.js 22.12 or newer.
976
+
977
+ **"`solana` was not found on PATH"** (deploy) — install the Agave CLI, or use `typesol deploy --dry-run` and run the
978
+ printed commands yourself.
979
+
980
+ **"… is missing, but typesol.json records …"** — the program keypair under `target/deploy/` was deleted or replaced.
981
+ Restore it from your backup. Without it you cannot upgrade the deployed program; removing `"address"` from
982
+ `typesol.json` gives the program a new address.
983
+
984
+ **A build error you don't recognize** — the compiler adds a `hint:` line under TypeScript's message where TypeScript's
985
+ own advice points the wrong way for a program. The usual ones: integers are `bigint` (`1n`, `u64` parameters, not
986
+ `number`); `require`, `log`, `min`, `max` and `fixedArray` are imported from `"typesol"`; arrays are read with `.get(i)`
987
+ and written with `.set(i, v)`; an account you change is a `Mut<T>` parameter; there is no `async`, `try`, `throw` or
988
+ `class`. The full list of what the subset covers is in [language.md](language.md).
989
+
990
+ **A transaction fails with a custom error** — see [errors.md](errors.md). Failures raised by the
991
+ compiler's checks log their TypeScript location, e.g. `TypeSOL: arithmetic overflow (vault.ts:42)`.
992
+
993
+ **Heap errors (5110) building strings** — strings are allocated on a 32 KiB heap and never freed. Build less text,
994
+ or declare `const HEAP_SIZE_KIB = 64n` and add a ComputeBudget `requestHeapFrame` instruction to the transaction.
995
+
996
+ **`typesol idl publish` fails on a local validator with "invalid instruction data"** — the System Program of
997
+ `solana-test-validator` (Agave 3.1 included) rejects a System instruction that the current Program Metadata program
998
+ uses. Publishing works on mainnet-beta. The error shows the failing transaction's last log lines.
999
+
1000
+ **"instruction X (with the helpers inlined into it) needs N bytes of stack; SBPF v0 gives each function 4096"** — under
1001
+ SBPF v0 (the default) every function gets a fixed 4 KiB stack frame, and going past it corrupts memory, so the build
1002
+ 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
+ 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.
1006
+
1007
+ <!-- docs/mainnet.md -->
1008
+
1009
+ # Deploy to mainnet
1010
+
1011
+ From an empty directory to a program on Solana mainnet-beta: create, test, deploy, publish the IDL, then check that
1012
+ 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.
1014
+
1015
+ You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Requirements).
1016
+
1017
+ ## 1. Create and test
1018
+
1019
+ ```sh
1020
+ npx @typesol/cli init my-app
1021
+ cd my-app
1022
+ npm install
1023
+ npm test
1024
+ ```
1025
+
1026
+ `npm test` runs `tests/my_app.test.ts` in LiteSVM: it compiles the program and calls it, with no validator or SOL.
1027
+ Write your program in `programs/my_app.ts` and keep the tests passing before you spend anything.
1028
+
1029
+ ## 2. Build
1030
+
1031
+ ```sh
1032
+ npx typesol build
1033
+ ```
1034
+
1035
+ This writes `target/my_app/`: the program (`my_app.so`), its Anchor IDL (`my_app.json`), a TypeScript client
1036
+ (`my_app.client.ts`) and the generated C. The first build also creates `target/deploy/my_app-keypair.json`, the
1037
+ program's address, and records the address in `typesol.json`.
1038
+
1039
+ **Back up `target/deploy/my_app-keypair.json` now.** It is not committed (`.gitignore`), and without it you cannot
1040
+ redeploy to that address.
1041
+
1042
+ ## 3. A wallet with SOL
1043
+
1044
+ ```sh
1045
+ solana-keygen new -o ~/.config/solana/deployer.json
1046
+ solana config set --url mainnet-beta --keypair ~/.config/solana/deployer.json
1047
+ solana address
1048
+ ```
1049
+
1050
+ Send SOL to that address. Most of what a deploy costs is rent for the program's bytes, which you get back if you
1051
+ ever close the program:
1052
+
1053
+ ```sh
1054
+ solana rent $(wc -c < target/my_app/my_app.so)
1055
+ ```
1056
+
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.
1059
+
1060
+ The public mainnet RPC is rate-limited; for deploys, set `--url` (or `solana config set --url`) to your RPC
1061
+ provider's endpoint.
1062
+
1063
+ ## 4. Deploy
1064
+
1065
+ ```sh
1066
+ npx typesol deploy --dry-run # builds and prints the solana command it will run
1067
+ npx typesol deploy
1068
+ ```
1069
+
1070
+ It runs `solana program deploy` at the address in `target/deploy/my_app-keypair.json`, with your wallet as payer and
1071
+ upgrade authority, and prints the program id. Deploying again upgrades the program in place.
1072
+
1073
+ If a deploy stops part-way, the buffer stays behind with its SOL. The error prints the buffer's address; recover it
1074
+ with `solana program close <buffer address>`, or list yours with `solana program show --buffers`.
1075
+
1076
+ ## 5. Publish the IDL
1077
+
1078
+ ```sh
1079
+ npx typesol idl publish
1080
+ ```
1081
+
1082
+ It writes the IDL to the Program Metadata program, signed by the upgrade authority, where Anchor clients and
1083
+ explorers look for it. It costs a few thousandths of a SOL of rent.
1084
+
1085
+ ## 6. Verify
1086
+
1087
+ ```sh
1088
+ npx typesol verify my_app
1089
+ ```
1090
+
1091
+ `verify` rebuilds the program from `programs/my_app.ts`, reads the deployed one at the address in `typesol.json` from
1092
+ 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
1094
+ published in step 5. Anyone can run it against your program with `--address <program id> --url mainnet-beta`.
1095
+
1096
+ ## 7. Call it
1097
+
1098
+ `target/my_app/my_app.client.ts` builds the program's instructions on `@solana/kit`; see [client.md](client.md).
1099
+
1100
+ ## Later
1101
+
1102
+ - **Freeze it.** `solana program set-upgrade-authority <program id> --final` makes the program immutable. It cannot
1103
+ be undone.
1104
+ - **Close it.** `solana program close <program id> --bypass-warning` returns the rent to the authority. The program
1105
+ id can never be used again.
1106
+
1107
+ A worked example: the official escrow, deployed to mainnet in TypeSOL, Pinocchio, native Rust and Anchor, with every
1108
+ transaction linked, is in the README's [On mainnet](../README.md#on-mainnet) section.
1109
+
1110
+ <!-- docs/security-model.md -->
1111
+
1112
+ # Security model
1113
+
1114
+ What a program compiled by TypeSOL can rely on, who is trusted, and what is left to the program's author. This is the
1115
+ specification the tests check and an audit measures the compiler against; [audit.md](audit.md) is the package for
1116
+ auditors, [SECURITY.md](../SECURITY.md) how to report a problem.
1117
+
1118
+ ## Trust
1119
+
1120
+ | Party | Trusted for |
1121
+ | --- | --- |
1122
+ | The program's author | the program's logic: what it allows, to whom, for how much |
1123
+ | 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 |
1125
+ | The Solana runtime | account ownership and signer flags as passed, the loader's account serialization, CPI privilege rules, sysvars |
1126
+
1127
+ Everything a transaction carries is attacker-controlled: the instruction data, which accounts are passed in which
1128
+ slots (any account, repeated or not), the flags the runtime then enforces, the data of accounts the program does not
1129
+ own, remaining accounts, and what another program returns or writes.
1130
+
1131
+ ## Guarantees
1132
+
1133
+ Each holds for every instruction of every program the compiler accepts. A break of any of them is a security bug
1134
+ (SECURITY.md).
1135
+
1136
+ ### Before the body runs
1137
+
1138
+ 1. **Account count.** Fewer accounts than parameters fail (3005); more than the program takes (32, or its `MAX_ACCOUNTS`) fail before parsing (5113).
1139
+ 2. **Account types.** Each parameter is checked for what its type says: `Signer` signed (3010); `Mut<…>` writable
1140
+ (2000); a program account (`Account<T>`, `Mut<T>`) owned by this program (3007), initialized (3012), with `T`'s
1141
+ discriminator (3002) and at least its size (3003); `TokenAccount` / `Mint` owned by SPL Token or Token-2022 and an
1142
+ initialized account of that kind (3007 / 3003); program parameters at their fixed address and executable
1143
+ (3008 / 3009); `SystemAccount` owned by the System Program (3011); `Zeroed<T>` owned, all-zero discriminator and
1144
+ rent-exempt.
1145
+ 3. **No aliasing.** Two writable parameters are never the same account (2040), whatever slots the transaction uses,
1146
+ unless the program marks one `Dup<…>`, and then only for accounts read and written in place (see below).
1147
+ 4. **Arguments.** Every argument is length-checked before it is read; strings are valid UTF-8; booleans, enums and
1148
+ options have valid tags (102).
1149
+ 5. **Constraints.** `Seeds` (2006, with the stored or the canonical bump), `Ata` (2015 / 2009 / 2014), `HasOne`
1150
+ (2001), `Owner` (2004), `Executable` (2007), `Address` (2012), `TokenOf` / `MintOf` (2014–2017, 2021, 2022) hold
1151
+ before the body, per account in Anchor's order ([errors.md](errors.md#which-error-a-transaction-gets)). A
1152
+ constraint naming an optional account is refused at compile time, so leaving the account out cannot skip it.
1153
+
1154
+ ### While it runs
1155
+
1156
+ 6. **Arithmetic.** Every `+ - * / % **`, compound assignment, `++` / `--`, unary minus, shift and cast is checked:
1157
+ overflow and lost bits fail (5100), division by zero fails (5101), a cast out of range fails (4102). There is no
1158
+ unchecked integer operation in the language.
1159
+ 7. **Bounds.** Every index into an array, Vec, FixedVec or remaining-account list is checked (5104); a
1160
+ growable Vec's stored length is checked against the account's size before it is used (3003).
1161
+ 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
1163
+ pre-funded still gets created. `createIfNeeded` on an existing account re-derives the canonical PDA and checks
1164
+ owner, discriminator and size (token accounts: mint and owner; mints: decimals, authorities and the extensions it
1165
+ names). A `Migrate<From, To>` account is checked as an existing `From`; `migrate(…)` is a top-level statement every
1166
+ path reaches, builds the new value before rewriting the bytes, and nothing reads the old data after it (compile
1167
+ errors).
1168
+ 9. **Writes through references.** A place is never written after the code that computes its value may have moved it:
1169
+ 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.
1171
+ 10. **Remaining accounts.** Writing one (`.lamports`, `loadAccountMut`) checks it is writable (3006) and not another
1172
+ account of the instruction (2040); `loadAccountMut` loads a given account once per instruction (2040);
1173
+ `loadAccount<T>` checks owner, discriminator and size, and validates the data as instruction arguments are.
1174
+ 11. **Growth.** An account grows by at most 10 KiB per instruction (3016), the payer is a `Mut<Signer>`, new bytes are
1175
+ zero and the new rent is paid; shrinking keeps the lamports in the account.
1176
+ 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
1178
+ signs for it; remaining accounts keep the flags they were passed with, or are checked for the role requested.
1179
+ `invokeInstruction` is the exception by design: its program, account flags and data come from values (stored in
1180
+ account data or passed in), so the compiler cannot check them; the runtime does, refusing any account the
1181
+ transaction did not pass that way and any signer the program's seeds do not cover. Only programs that store
1182
+ instructions to run (a multisig, a DAO) need it; review who can write those values.
1183
+ Return data is read only from the program named, at the expected size (5106).
1184
+ 13. **Events.** `emitCpi` is accepted only from this program's event-authority PDA, signed (2002).
1185
+
1186
+ ### When it ends
1187
+
1188
+ 14. **Closing.** A `CloseTo<…>` or `close(…)` account has its lamports moved to the destination, its data zeroed and
1189
+ its owner reset to the System Program on every successful return, so it cannot be revived as the same account.
1190
+ 15. **No silent success.** Every failed check returns its error code and the transaction fails: no code path continues
1191
+ or returns success after a failed check or CPI.
1192
+
1193
+ ## Left to the author
1194
+
1195
+ - **Logic.** Who may call what, limits, prices, fees. TypeSOL checks what the types and constraints say, nothing more.
1196
+ - **`AccountInfo` / `UncheckedProgram`.** Unchecked by design, as in Anchor: check what you rely on.
1197
+ - **`requirePda(account, seeds, bump)`.** Any valid bump passes (Anchor's `bump = expr`). Use a stored bump, never one
1198
+ from the arguments.
1199
+ - **`Dup<…>`.** A parameter marked `Dup` may be the same account as another writable one. Reads see every write
1200
+ (both are the same bytes), so a value read before a write through the other slot is stale: read, then write.
1201
+ - **`NATIVE_ACCOUNT_WRITES`.** A program that declares it gives up the up-front writability check and the
1202
+ one-view-per-account refusal for `loadRawMut`, `storeBorsh` and BigVec writes, as a native program has neither: the
1203
+ runtime still refuses a changed read-only account, but two loads of one account alias each other. Make the
1204
+ original's address and type checks before loading.
1205
+ - **Instruction introspection.** The Instructions sysvar holds what the transaction's author put there. Require things
1206
+ of the transaction with it (that a repay instruction follows), never treat it as proof of who did what.
1207
+ - **Oracles.** `pythPrice` checks verification, feed and age (pass the exponent you scale by); the raw `update.*`
1208
+ fields are unchecked. `switchboardValue` needs the expected feed; set `minSamples`.
1209
+ - **`merkleVerify`.** Leaves and inner nodes hash alike: build leaves as `keccak256(keccak256(data))` in the program.
1210
+ - **Existing accounts in `createIfNeeded`.** An existing token account's delegate and close authority, and a mint's
1211
+ extensions the call does not name, are not checked (as in Anchor).
1212
+ - **Seeds of variable length.** Two adjacent string seeds can collide (`"ab" + "c"` and `"a" + "bc"`), as in Anchor.
1213
+
1214
+ ## Where TypeSOL is stricter than Anchor
1215
+
1216
+ - Any two writable parameters naming one account are refused unless one is `Dup<…>` (Anchor compares only program
1217
+ and token accounts, and `dup` lifts that).
1218
+ - Arithmetic overflow returns an error code (5100) in every build; Anchor aborts the program, and only when
1219
+ overflow checks are enabled.
1220
+
1221
+ ## Status
1222
+
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
1225
+ [audit.md](audit.md).
1226
+
1227
+ <!-- docs/ai.md -->
1228
+
1229
+ # Writing TypeSOL with an AI agent
1230
+
1231
+ TypeSOL is TypeScript, which AI coding agents write well, but a subset of it: a model's ordinary habits (`1` for an
1232
+ integer, `console.log`, `throw`, `xs[i]`) are refused. Four things close that gap.
1233
+
1234
+ ## The rules in the project
1235
+
1236
+ `typesol init` writes the rules an agent needs into the project:
1237
+
1238
+ | File | Read by |
1239
+ | --- | --- |
1240
+ | `AGENTS.md` | Codex, Cursor, Zed, Aider and other agents that read AGENTS.md |
1241
+ | `CLAUDE.md` (`@AGENTS.md`) | Claude Code |
1242
+ | `.cursor/rules/typesol.mdc` | Cursor (always applied to `programs/` and `tests/`) |
1243
+
1244
+ They say what ordinary TypeScript habits break (bigint integers, imports from `"typesol"`, no `throw` / `async` /
1245
+ `class`, `Mut<T>` for an account that changes, `.get(i)` / `.set(i, v)` on lists) and how to check and test. Keep your
1246
+ own project notes below them in AGENTS.md.
1247
+
1248
+ ## llms.txt
1249
+
1250
+ [typesol.com/llms.txt](https://typesol.com/llms.txt) is the index of the docs for models
1251
+ ([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
1252
+ and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
1253
+ 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`).
1255
+
1256
+ ## Errors an agent can fix by itself
1257
+
1258
+ `typesol check --json` prints `{ "ok": false, "diagnostics": [...] }`; each diagnostic has `file`, `line`, `column`,
1259
+ `length`, `message` and, for the usual mistakes, `hint`: what to write instead ("integers (u64, u32, i64 …) are bigint
1260
+ in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on check → edit → check without building.
1261
+
1262
+ ## The MCP server
1263
+
1264
+ `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:
1267
+
1268
+ ```json
1269
+ { "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
1270
+ ```
1271
+
1272
+ | Tool | What it does |
1273
+ | --- | --- |
1274
+ | `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
1275
+ | `idl` | the Anchor-compatible IDL the program compiles to |
1276
+ | `docs` | searches the docs and returns the best-matching sections |
1277
+ | `rules` | the rules above |
1278
+
1279
+ Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
1280
+ files, which an agent should do in the open.
1281
+
1282
+ <!-- docs/stability.md -->
1283
+
1284
+ # Stability and the road to 1.0
1285
+
1286
+ TypeSOL is pre-1.0. Until 1.0, a minor release (0.x → 0.y) may change the language, the account and IDL layout of
1287
+ generated programs and error codes, and says so in the CHANGELOG ([versioning
1288
+ policy](https://github.com/typesol-lang/.github/blob/main/VERSIONING.md)). This page says what 1.0 will promise, which
1289
+ parts are already meant to stay as they are, and what has to be settled first.
1290
+
1291
+ ## What 1.0 will promise
1292
+
1293
+ From 1.0 on, within a major version:
1294
+
1295
+ - **Sources keep compiling.** A program that compiles with 1.x compiles with every later 1.y, to a program with the same
1296
+ 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.
1299
+ - **The checks stay.** No check a program gets from its parameter types (owner, discriminator, signer, writability,
1300
+ aliasing, checked arithmetic, constraints) is removed or weakened.
1301
+ - **The tools keep their interfaces**: `typesol build`, `test` (via `typesol/testing`), `check --json`, `deploy`,
1302
+ `verify`, `idl`, the typed client, and `typesol.json`.
1303
+
1304
+ ## Stable already
1305
+
1306
+ Meant to stay as they are; a change before 1.0 would be a breaking change listed as one:
1307
+
1308
+ - Types: the integers (`u8` … `u128`, `i8` … `i128`), `boolean`, `Pubkey`, `Hash`, structs, `FixedArray`, `FixedVec`,
1309
+ `Vec`, `FixedString`, `Option`, unit and data enums, `u256` in computation.
1310
+ - Account parameters and their checks: `Signer`, `Account<T>`, `Mut<T>`, `Init<T>`, `InitIfNeeded<T>`, `Zeroed<T>`,
1311
+ optional accounts, token accounts and mints, programs, sysvars, account groups; the constraints (`HasOne`, `Seeds`,
1312
+ `CloseTo`, `Ata`, `Address`, `Owner`, `Executable`).
1313
+ - Errors and events: error enums and their codes, `require`, `AnchorError`, `emit`, `emitCpi`.
1314
+ - CPIs: System, SPL Token, Token-2022, Associated Token, Memo, generic `invoke` with PDA signing.
1315
+ - Layouts: account data (Anchor's discriminator and fixed or `@layout borsh` layout), the IDL, the client.
1316
+
1317
+ ## Experimental
1318
+
1319
+ Useful today, but may still change before 1.0 (each change listed in the CHANGELOG):
1320
+
1321
+ - The native-program surface (0.40.0): `loadRaw` / `loadRawMut`, the instruction data readers, error code 0,
1322
+ `ProgramError`, `panic`, `PANIC_ON_OVERFLOW`, `ERROR_LOG_PREFIX` / `PROGRAM_ERROR_LOG_PREFIX`, `logBase64`,
1323
+ `createProgramAddress`.
1324
+ - `loadBorsh` / `storeBorsh` (0.42.0): a native program's Borsh accounts read into a local struct and written back.
1325
+ - `BigVec<T>` (0.42.0): SPL's `big_vec`, a list over the rest of a native account.
1326
+ - `panic(null, location)` (no log line) and `abort()` (Rust's abort, "SBF program panicked") (0.42.0).
1327
+ - 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).
1329
+ - `epochRewards()` and `EpochRewards` (0.42.0): the EpochRewards sysvar through its syscall.
1330
+ - `NATIVE_ACCOUNT_WRITES` (0.42.0): opt-in native write semantics for `loadRawMut`, `storeBorsh` and BigVec writes
1331
+ (writability and aliasing left to the runtime). It drops checks a program would otherwise get, so it stays outside
1332
+ "the checks stay" promise above: it only applies to programs that declare it.
1333
+ - Metaplex CPIs (Token Metadata, Core, Bubblegum), oracles (Pyth, Switchboard), the Stake program.
1334
+ - `programAt<P>` / `sysvarAt<S>` and remaining accounts in the typed CPIs (System, Token, ATA, Memo, Stake); a ternary
1335
+ between remaining accounts and `AccountInfo` parameters (0.42.0).
1336
+ - Functions chosen at run time and lists of functions, closures returned from functions.
1337
+ - `typesol/testing`'s epochs and staking: `warpToEpoch`, `nextEpoch`, `StakeCluster`, `stakeActivation`, the vote and
1338
+ stake account builders and `readStakeAccount`.
1339
+ - Tools: `typesol port`, `clone`, `profile`, `cpi`, the editor plugin, the MCP server and the agent files `init`
1340
+ writes, the SBPF v1 and v2 targets.
1341
+
1342
+ ## Before 1.0
1343
+
1344
+ - **An external audit** of the compiler and runtime ([audit package](audit.md)), its findings fixed and published.
1345
+ - **Settle the open edges**, each either supported or refused with a clear error:
1346
+ - 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
+ - `require` with an error code computed at run time that is 0: fails as an overflow (5100) today, where a native
1349
+ program returns CUSTOM_ZERO;
1350
+ - which experimental parts above become stable, and which stay outside the 1.0 promise.
1351
+ - **A release candidate** (1.0.0-rc) used for the showcase ports and the templates, with no breaking change between it
1352
+ and 1.0.0.