@typesol/cli 0.44.1 → 0.46.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 (80) hide show
  1. package/CHANGELOG.md +343 -0
  2. package/NOTICE +14 -1
  3. package/README.md +115 -26
  4. package/SECURITY.md +10 -8
  5. package/dist/bin.d.ts +2 -0
  6. package/dist/bin.js +9 -0
  7. package/dist/cli.js +226 -62
  8. package/dist/compiler/analyze.js +57 -6
  9. package/dist/compiler/diagnostics.d.ts +4 -3
  10. package/dist/compiler/diagnostics.js +10 -6
  11. package/dist/compiler/emit/base.d.ts +1 -1
  12. package/dist/compiler/emit/calls.js +18 -5
  13. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  14. package/dist/compiler/emit/cpi-core.js +8 -4
  15. package/dist/compiler/emit/expressions.d.ts +14 -0
  16. package/dist/compiler/emit/expressions.js +52 -4
  17. package/dist/compiler/emit/shared.d.ts +8 -1
  18. package/dist/compiler/emit/shared.js +8 -1
  19. package/dist/compiler/emit/statements.d.ts +8 -3
  20. package/dist/compiler/emit/statements.js +68 -3
  21. package/dist/compiler/emit/storage.js +5 -1
  22. package/dist/compiler/hints.d.ts +7 -0
  23. package/dist/compiler/hints.js +58 -9
  24. package/dist/compiler/index.d.ts +56 -1
  25. package/dist/compiler/index.js +27 -3
  26. package/dist/compiler/model.js +3 -2
  27. package/dist/compiler/toolchain.d.ts +73 -2
  28. package/dist/compiler/toolchain.js +222 -17
  29. package/dist/node-version.d.ts +4 -0
  30. package/dist/node-version.js +12 -0
  31. package/dist/tools/docker.d.ts +183 -0
  32. package/dist/tools/docker.js +442 -0
  33. package/dist/tools/doctor.d.ts +44 -0
  34. package/dist/tools/doctor.js +108 -14
  35. package/dist/workspace.d.ts +11 -3
  36. package/dist/workspace.js +46 -9
  37. package/docker/Dockerfile +163 -0
  38. package/docker/deps/0.43.0.lock.json +1206 -0
  39. package/docker/deps/0.44.0.lock.json +1206 -0
  40. package/docker/deps/0.44.1.lock.json +1206 -0
  41. package/docker/deps/0.45.0.lock.json +1206 -0
  42. package/docker/deps/0.46.0.lock.json +1206 -0
  43. package/docs/ai.md +2 -1
  44. package/docs/architecture.md +18 -6
  45. package/docs/audit.md +15 -7
  46. package/docs/case-study-phoenix.md +1 -1
  47. package/docs/case-study-raydium-amm.md +1 -1
  48. package/docs/case-study-spl-stake-pool.md +1 -1
  49. package/docs/cli.md +71 -6
  50. package/docs/errors.md +22 -8
  51. package/docs/glossary.md +210 -0
  52. package/docs/language-accounts.md +499 -0
  53. package/docs/language-basics.md +389 -0
  54. package/docs/language-builtins.md +411 -0
  55. package/docs/language-chain.md +198 -0
  56. package/docs/language-cpi.md +470 -0
  57. package/docs/language-errors-events.md +184 -0
  58. package/docs/language-native.md +493 -0
  59. package/docs/language-pdas.md +198 -0
  60. package/docs/language-statements.md +620 -0
  61. package/docs/language-types.md +601 -0
  62. package/docs/language.md +190 -467
  63. package/docs/mainnet.md +103 -8
  64. package/docs/migrate-from-anchor.md +7 -6
  65. package/docs/security-model.md +4 -4
  66. package/docs/stability.md +64 -3
  67. package/docs/test-your-program.md +52 -15
  68. package/docs/testing.md +49 -2
  69. package/docs/troubleshooting.md +210 -42
  70. package/lib/typesol.d.ts +67 -22
  71. package/llms-full.txt +5084 -591
  72. package/llms.txt +12 -1
  73. package/package.json +4 -2
  74. package/releases/0.43.0.json +669 -0
  75. package/releases/0.44.0.json +672 -0
  76. package/releases/0.44.1.json +672 -0
  77. package/releases/0.45.0.json +732 -0
  78. package/runtime/LICENSE-compiler-builtins.txt +275 -0
  79. package/runtime/typesol_builtins.c +484 -0
  80. package/ts-plugin/index.js +16 -5
package/docs/language.md CHANGED
@@ -1,476 +1,199 @@
1
1
  # The TypeSOL language
2
2
 
3
- The full reference. For a tour, start with the [README](../README.md).
3
+ TypeSOL is a subset of TypeScript that compiles to Solana programs. A program is a `.ts` file: its exported functions
4
+ are instructions, its exported interfaces are account data, and its parameter types say which accounts are checked and
5
+ how. The TypeScript compiler type-checks it against `lib/typesol.d.ts`; TypeSOL then refuses what is outside the
6
+ language, lowers the rest to C and builds an SBF program with clang, and writes an Anchor-compatible IDL and a typed
7
+ client. Nothing runs on chain but the compiled code.
8
+
9
+ What differs from TypeScript, in short:
10
+
11
+ - Integers are bigints of a declared width (`u8` … `u128`, `i8` … `i128`, `1n` literals), and every arithmetic
12
+ operation is checked. There is no `number` and no floating point.
13
+ - Everything comes from `"typesol"`: no Node.js, no npm packages, no `console`, no `Math`.
14
+ - No `class`, `async`, `throw` or `try`: a failed `require` (or check, or overflow) ends the instruction and fails the
15
+ whole transaction, whose changes the runtime discards.
16
+ - Every type's layout is known when the program compiles. Locals and struct fields have a fixed size: strings in
17
+ accounts are `FixedString<N>`, lists are `FixedArray` or `FixedVec`. What varies in length is a `string` or `Vec`
18
+ argument (read in place from the instruction data), a `Vec` field (the account grows) and a string built at run time
19
+ (on the heap). There are no dynamic objects.
20
+
21
+ For a tour, start with the [README](../README.md); to port an Anchor program, [migrate from
22
+ Anchor](migrate-from-anchor.md). New to Solana? [Language basics](language-basics.md#solana-in-a-dozen-lines) starts
23
+ with the terms the guide uses.
24
+
25
+ ## The guide
26
+
27
+ Read in order, or jump to what you need. Every example on these pages is a complete program that compiles, unless it
28
+ is marked as a fragment.
29
+
30
+ An example shows the construct its section is about. Unless the text says who may call an instruction, the example
31
+ does not check its caller, as a real program must: see [constraints](language-accounts.md#constraints) and
32
+ [signing as a PDA](language-pdas.md#signing-as-a-pda).
33
+
34
+ | Page | What it covers |
35
+ | --- | --- |
36
+ | [Language basics](language-basics.md) | Solana in a dozen lines, then what a program is: the file, imports, instructions, account data, helpers, constants, multiple files, what the compiler derives, stack and heap, limits and costs (rent, compute, transaction and account sizes) |
37
+ | [Types](language-types.md) | integers and checked arithmetic, casts, `u256`, booleans, `Pubkey`, strings, enums, data enums, structs, `Option`, lists, `f64`, heap values, with their bytes and limits |
38
+ | [Statements and functions](language-statements.md) | which TypeScript is TypeSOL: declarations, copies and references, control flow, destructuring, helpers, `Inout<T>`, closures, generics, and what is refused |
39
+ | [Accounts](language-accounts.md) | account parameters and the checks they emit, creating, closing and resizing accounts, constraints, optional accounts, account groups, remaining accounts, account layouts |
40
+ | [PDAs](language-pdas.md) | seeds, bumps, `Seeds<…>`, `requirePda`, deriving addresses, signing as a PDA, PDAs in the IDL |
41
+ | [Errors, logs, events and return values](language-errors-events.md) | `require`, error enums and codes, `log`, `emit`, `emitCpi`, return values |
42
+ | [Calling other programs](language-cpi.md) | the System, Token, Token-2022, Associated Token, Memo, Metaplex and Stake programs, typed calls from an IDL, `invoke`, `invokeInstruction`, transfer hooks |
43
+ | [Sysvars, hashes, signatures and oracles](language-chain.md) | the clock and other sysvars, hashing, signature checks, instruction introspection, Pyth, Switchboard, randomness |
44
+ | [Porting a native program](language-native.md) | advanced: the `@fallback` entry, raw account views, Borsh accounts, `BigVec`, the red-black tree, byte builders, Rust's panics and log lines |
45
+ | [Built-ins](language-builtins.md) | every name `"typesol"` exports, one line each, generated from `lib/typesol.d.ts` |
46
+ | [Glossary](glossary.md) | the Solana and TypeSOL terms the guide uses: account, owner, rent, PDA, CPI, IDL, compute units, … |
47
+
48
+ Then: [test your program](test-your-program.md) in LiteSVM, call it from [the generated client](client.md),
49
+ [deploy it](mainnet.md), and when something fails, [troubleshooting](troubleshooting.md).
50
+
51
+ The error codes are in [errors.md](errors.md); what a compiled program checks for you and what is left to you, in the
52
+ [security model](security-model.md).
53
+
54
+ ## Not supported yet
55
+
56
+ - A struct holding a FixedVec that is both an argument and account data (its bytes differ there, and the IDL describes
57
+ a type one way): declare one for each.
58
+ - Growing an account by more than 10 KiB in one instruction (Solana's limit): realloc again in the next instruction.
59
+ - `?.` and `!` on anything but optional accounts, Options and a `find` on struct elements.
60
+ - Functions stored in a struct, chosen from a list by index, or returned from an instruction.
61
+ - A fused `map` to strings: store it, annotated.
62
+ - Floating point (by design).
63
+
64
+ They are rejected at compile time rather than half-supported.
65
+
66
+ ## Index of the former sections
67
+
68
+ Where each part of the language is described, under the headings this page used to have.
4
69
 
5
- ## Types and statements
70
+ ### Types and statements
6
71
 
7
- | Concept | TypeSOL |
72
+ | Topic | Where |
8
73
  | --- | --- |
9
- | 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) |
10
- | Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
11
- | Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits; the amount, also in `<<=` / `>>=`, may be any integer type). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit), `min` / `max`, `switch` and as a list index (5104 past u64); a shift amount or an exponent is a u128 or smaller (compile error); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
12
- | 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)` |
13
- | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
14
- | 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) |
15
- | 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) |
16
- | Logging | `log("text")`, `log(value)`, `log(pubkey)` |
17
- | Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
18
- | 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(…)`) |
19
- | Local lists | `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey: k, isSigner: false, isWritable: false }])`, `const buf: FixedVec<u8, 600> = fixedVec([])`, `const pair: FixedArray<Meta, 2> = fixedArray(meta)` — a FixedVec or FixedArray of integers, booleans, Pubkeys, enums, `FixedString<N>` or fixed-size structs on the stack, with `get`, `set`, `push`, `pushAll`, `pop`, `clear`, `.length`, `for … of` and the list methods (a `FixedVec<u8, N>` is also a byte buffer: `pushLE`, `pushKey`, `pushBorsh`, `setLE`, `truncate`, see [Porting a native program](#porting-a-native-program)); given another list (`const y: FixedVec<Pubkey, 4> = xs`) it is a copy, as a struct local is. Setting one up costs about the same at any size (`fixedVec([])` of 1280 bytes about 10 CU: the free slots are zeroed by the memset syscall, the elements written in place, also as a struct literal's field). One list holds at most 2 KiB of elements (a FixedVec's u32 length aside: `FixedVec<u32, 512>` fits; the 4 KiB stack frame is shared with the rest of the function, and a frame that overflows is reported with its biggest locals): a bigger one is a compile error naming its size. `/** @heap */` on an instruction's list or struct local (`/** @heap */ const ids: FixedVec<u8, 1024> = fixedVec([])`) keeps it on the heap instead (one allocation per declaration, reused when a loop declares it again; up to the heap's size, 32 KiB or `HEAP_SIZE_KIB`; about 18 CU); not in helpers, which may run many times while the heap is never freed |
20
- | 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 |
21
- | 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 |
22
- | 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 |
23
- | 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` |
24
- | File-local structs | `interface Pair { a: u64; b: u64 }` without `export`: the file's own struct, for its helpers (parameters, results, `Inout<Pair>`), locals and other such structs; left out of the IDL. What the IDL describes (account data, instruction arguments and results, events, an exported struct's field, a data enum's variant) cannot hold one: each such use is an error saying to export it |
25
- | Pubkey constants | `const ADMIN = pubkey("4Nd1…")` (checked at compile time) or inline `pubkey("…")`; usable as seeds |
26
- | 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 |
27
- | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
28
- | 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 |
29
- | Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it, also when it was made through another parameter that may be the same account: a `Dup<…>` pair, a read-only and a writable account of one type, a struct loaded with `loadAccount` / `loadAccountMut`). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
30
- | 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 |
31
- | 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) |
32
- | 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 |
33
- | 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 |
34
- | 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 |
35
- | 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 |
36
- | 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) |
37
- | 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 |
38
- | Views at run-time offsets | A native account whose parts start where its header says (Phoenix's market at byte 576, trees sized by `market_size_params`, Serum's slabs): `loadRawAt<T>(acct, offset)` / `loadRawMutAt<T>(acct, offset)` are `loadRaw` / `loadRawMut` at a byte offset known only at run time, and `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt<T>(…)` are `capacity` elements of a fixed-size type (integers, booleans, Pubkeys, enums, `FixedString<N>`, structs) packed in place from there, the count a run-time u64: `get` / `set` (5104 past the count), `.length` (the capacity), `for … of` and the list methods, structs by reference. The bounds are checked once, when the view is made (`offset + size`, with overflow, within the data: ProgramError::AccountDataTooSmall), and element access is pointer arithmetic. Owner (3007), writability and the one-mutable-view claim (2040) are `loadRaw` / `loadRawMut`'s, so several mutable views of one account need `NATIVE_ACCOUNT_WRITES`, as a native port declares. Bind them with const; not helper parameters. A view (and anything read through it) is not used after `closeRaw` or `resizeAccount` of an account it may view, or after a helper that may close or resize one it is given: its bounds were checked against the old length, so it is a compile error saying to take the view again |
39
- | lib-sokoban's RedBlackTree | `const bids = rbTreeMutAt<FIFOOrderId, FIFORestingOrder>(market, offset, capacity, compareOrders)` (or `rbTreeAt` to read): lib-sokoban 0.3's `RedBlackTree<K, V, N>` over account bytes, byte for byte (root, allocator, 1-based nodes of registers + key + value; freed nodes keep their key and value; LIFO free list ending at the bump index), checked against the crate after every operation of recorded traces (test/verification/rbtree-trace.test.ts). `length`, `capacity`, `initialize()`, `get(k)` (the value in place, or null), `insert(k, v)` (the node index, or null when a new key finds it full; an equal key takes the value), `remove(k)` (the value, read in the freed node, or null), `removeAt(i)` (the node at index `i` from `addrOf` or a node's `.index`, removed with `remove`'s writes without searching again: 144 CU less per cancel in test/language/phx-costs.test.ts; null for 0 or a node in no tree), `min()` / `max()` (a node: `.key`, `.value`, `.index`, or null), `addrOf(k)` (0 when absent), `nodeAt(i)` (Phoenix keeps a trader's node index), `for (const e of tree)` / `tree.reversed()` with `break` / `continue`. The comparator, a function of the program `(a: K, b: K) => i8` (any signed integer result; an unsigned one is refused, as it could never say "less"), is called as `compare(searchedKey, nodeKey)` (Phoenix's FIFOOrderId orders by the left key's side); without one, keys are ordered as Rust derives Ord (fields in order, integers by value, Pubkeys bytewise). A reference into the tree (`get`, `min`, a node, however it is bound: `c ? t.min() : t.max()`, `t.get(k)!`; a node is bound with const) cannot be used after an `insert` (it may reuse a freed node), and a `for … of` body cannot insert, remove or initialize on the tree it walks, nor on any tree view of an account that may be the walked one's (another view of the same tree; under `NATIVE_ACCOUNT_WRITES` any account may be), nor call a helper that takes accounts and makes an `rbTreeMutAt` view (compile errors, as Rust's borrows). Panics as sokoban's (see [Porting a native program](#porting-a-native-program)) |
40
- | 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) |
41
- | 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 |
42
- | 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) |
43
- | Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
44
- | 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 |
45
- | 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 |
46
- | 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`) |
47
- | Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL); an integer constant may be computed from literals and constants declared before it, here or in an imported file (`const EVENT_ROOM = 1280n - 34n`, `const ASKS_AT: u64 = BIDS_AT + 2n * BOOK`: `+ - * / % ** & \| ^ << >>`, unary `-` and `~`), folded when the program is compiled; a typed one is computed in its type, every step checked (`const X: u64 = 1n - 2n + 5n` is an error; `const M: u8 = ~1n` is 254, `~` within the width), and division by zero, a negative exponent or a shift past the width are compile errors |
48
- | Type aliases | `type Price = u64`, `type Key = Pubkey`, `type Buf = FixedVec<u8, 32>`, `type MaybePoint = Point \| null`, an alias of another alias — another name for one type, replaced by it wherever it is used (layouts, arguments, the IDL: all the type's own); exported or not, imported like any name (the aliased type keeps the names of the file declaring it). Not generic. A union of named types (`type Event = Fill \| Place`) is neither an alias nor a data enum: write the variants as object types, below |
49
- | 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 |
50
- | 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) |
51
- | 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 |
52
- | `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
53
- | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash` (a PDA seed too: its 32 bytes, as Marginfi seeds an order with the hash of its bank keys); `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump, or both from one search with `const [address, bump] = findProgramAddressWithBump(seeds, program)` (Rust's `let (address, bump) = …`; each separate search costs about 450 CU per bump tried); `programId()` → this program's address; `a.compare(b)` orders Pubkeys and Hashes as Rust orders their 32 bytes (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
54
- | Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted; staleness counts slots from the feed's `result.slot`; the 18-decimal result is scaled to `decimals` rounding toward zero) (mainnet program unless `SwitchboardFeed<"devnet">`). Neither reader checks the price's sign or zero, the confidence (Pyth's `conf`, Switchboard's spread of samples), or a publish time or result slot in the future (it counts as fresh): check what your program relies on |
55
- | 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 |
56
- | 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 |
57
- | Loops | `for (let i = 0n; i < n; i++)` (or two counters, `for (let i = 0n, j = n; i < j; i++, j--)`: several declarations, and comma-separated updates run in order after each pass, `continue` included), `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
58
- | Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place. Pubkey, Option, string and u256 parameters are passed by pointer too (the SBF target passes a C struct as a pointer to the caller's object and does not copy it); a helper that can write (it takes accounts, remaining accounts or `Inout<T>` places) gets a copy taken at the call, unless the argument is a local, a temporary, an instruction argument, a constant, an account's key, the program id or a parameter of the calling helper, which nothing it is given reaches; a helper that writes nothing reads the caller's value in place. Text a string argument views in account data or in an `Inout<T>` place is copied for such a helper too; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
59
- | `Inout<T>` parameters | `function addEvent(rec: Inout<Recorder>, e: Event): void { rec.count += 1n; … }` is Rust's `rec: &mut Recorder`: the helper gets the caller's place itself (a pointer, no copy: about the compute units of the same code written inline) and the caller sees its writes after the call, as JS shares an object passed to a function. `T` is a fixed-size struct, a `FixedArray<T, N>` or a `FixedVec<T, N>` (its `push`, `pop` and `clear` included). The argument is a writable place: a local struct or list, a `loadBorsh` local, a field path of a local, of a `loadRawMut` view or of a `Mut<T>` account, a list element (`book.levels.get(i)`, a narrowed Option's value), another `Inout` parameter (passed on), or a literal (a fresh value nobody else sees); a read-only one (a field of an `Account<T>`, a `loadRaw` view, an instruction argument, a read-only parameter) is a compile error naming what to change. At each call, so that the helper's parameter is the only way to the place while it runs: no other argument may share storage with an Inout one (one place inside the other; two elements of one list, whatever their indexes, a BigVec slice's elements included; an account and a place inside it; a read-only struct argument inside it: pass a copy); an element of a `Vec` or `BigVec` is refused when the call may resize or filter that list (the helper takes writable or remaining accounts), since its elements would move; and a reference into the place (`const e = p.items.get(0n)`) that is read after the call is refused, since the helper may replace what it points at (copy the fields first, or read them through the place). Places that differ in the source but may be one account at run time (two `Dup<…>` accounts, a writable and a read-only account, two native views under `NATIVE_ACCOUNT_WRITES`: `loadRawMut`, `loadRawMutAt`, `rawArrayMutAt` elements, `rbTreeMutAt` nodes, a helper's own account parameters) are compared before the call: 2040 when they overlap. The comparison covers an Inout argument against every other argument passed in place (another Inout one, a read-only struct, array or list, an account), so a read-only argument cannot change under the helper while it writes; one copied for the call (a helper that takes accounts gets a copy of account data) shares nothing and is not compared. One pair is left to run time: a place in a `loadRawMut` view passed with the `RemainingAccount` it was loaded from (without `NATIVE_ACCOUNT_WRITES` a second `loadRawMut` of it in the helper fails, 2040; with the flag the helper can load and write the same bytes, the flag's trade-off). Integers, Pubkeys, strings and Options are values, which JS copies into a function too: return the new value (`x = f(x)`) or keep it in a struct and take `Inout<ThatStruct>`. `Vec<T>`, `BigVec<T>`, accounts and data enums are refused with what to write instead, and so is `Inout<T>` anywhere but a helper's parameter. Closures (and helpers expanded because they were given one) take `Inout<T>` the same way; their struct parameters were references already |
60
- | 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) |
61
- | 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) |
62
- | 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) |
63
- | 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) |
64
- | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list callback writing it) |
65
- | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
66
- | 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) |
67
- | 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) |
68
- | 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) |
69
- | 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) |
70
- | Heap | 32 KiB by default; `const HEAP_SIZE_KIB = 64n` (32–256) lets the program use more, when clients add ComputeBudget `requestHeapFrame` |
71
- | Docs | JSDoc on instructions, `@param`, structs, fields and data enums becomes `docs` in the IDL |
72
- | 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) |
73
- | 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)` |
74
-
75
- ## Account parameters and the checks they emit
76
-
77
- | Parameter type | Checked before your code runs |
74
+ | instructions: exported functions, parameters, results | [Basics: Instructions](language-basics.md#instructions) |
75
+ | account data: exported interfaces, nesting | [Basics: Account data](language-basics.md#account-data) |
76
+ | integers, literals, checked operators, `++` `+=` … | [Types: Integers](language-types.md#integers) |
77
+ | `mulDiv`, `mulDivCeil`, `isqrt`, `min`, `max` | [Types: Integer helpers](language-types.md#integer-helpers) |
78
+ | casts (`u8(x)` …) | [Types: Casts](language-types.md#casts) |
79
+ | `u256` | [Types: u256](language-types.md#u256) |
80
+ | `boolean` | [Types: Booleans](language-types.md#booleans) |
81
+ | `Pubkey`, `Hash`, `pubkey("…")` constants | [Types: Pubkey and Hash](language-types.md#pubkey-and-hash) |
82
+ | `string`, `FixedString<N>` | [Types: Strings](language-types.md#strings) |
83
+ | strings built at run time, templates | [Types: Strings built at run time](language-types.md#strings-built-at-run-time) |
84
+ | unit enums | [Types: Enums](language-types.md#enums) |
85
+ | data enums | [Types: Data enums](language-types.md#data-enums) |
86
+ | structs, struct literals, struct values | [Types: Structs](language-types.md#structs) |
87
+ | file-local structs | [Types: File-local structs](language-types.md#file-local-structs) |
88
+ | struct, list and Option arguments | [Types: Struct arguments](language-types.md#struct-arguments) |
89
+ | `Option`, `??`, `?.`, `!`, options of structs and arrays | [Types: Option](language-types.md#option) |
90
+ | `FixedArray`, `fixedArray` locals | [Types: FixedArray](language-types.md#fixedarray) |
91
+ | `FixedVec`, local lists, `pushAll` | [Types: FixedVec](language-types.md#fixedvec) |
92
+ | `Vec` in account data and as arguments | [Types: Vec](language-types.md#vec) |
93
+ | list callbacks (`map`, `filter`, `find`, …) | [Types: List methods](language-types.md#list-methods) |
94
+ | `f64` | [Types: f64](language-types.md#f64) |
95
+ | the heap, `@heap`, `HEAP_SIZE_KIB` | [Types: Heap values](language-types.md#heap-values), [Basics: Memory](language-basics.md#memory-stack-and-heap) |
96
+ | `const` and `let`, copies and references | [Statements: Declarations](language-statements.md#declarations), [Copies and references](language-statements.md#copies-and-references) |
97
+ | destructuring | [Statements: Destructuring](language-statements.md#destructuring) |
98
+ | ternaries, evaluation order | [Statements: Expressions](language-statements.md#expressions) |
99
+ | loops | [Statements: Loops](language-statements.md#loops) |
100
+ | `switch` | [Statements: switch](language-statements.md#switch) |
101
+ | helpers, how arguments are passed, `@noinline` | [Statements: Helpers](language-statements.md#helpers) |
102
+ | `Inout<T>` parameters | [Statements: Inout parameters](language-statements.md#inout-parameters) |
103
+ | arrow functions and closures, functions as values | [Statements: Arrow functions and closures](language-statements.md#arrow-functions-and-closures) |
104
+ | functions as arguments | [Statements: Functions as arguments](language-statements.md#functions-as-arguments) |
105
+ | generic helpers | [Statements: Generic helpers](language-statements.md#generic-helpers) |
106
+ | top-level constants | [Basics: Constants](language-basics.md#constants) |
107
+ | type aliases | [Basics: Type aliases](language-basics.md#type-aliases) |
108
+ | multiple files | [Basics: Multiple files](language-basics.md#multiple-files) |
109
+ | JSDoc in the IDL | [Basics: What the compiler derives](language-basics.md#what-the-compiler-derives) |
110
+ | errors, `require`, error codes | [Errors: require](language-errors-events.md#require), [Error enums](language-errors-events.md#error-enums) |
111
+ | `log` | [Errors: log](language-errors-events.md#log) |
112
+ | `emit`, events | [Errors: Events](language-errors-events.md#events) |
113
+ | `emitCpi` | [Errors: Events through CPI](language-errors-events.md#events-through-cpi) |
114
+ | `@layout borsh` (Anchor's account bytes) | [Accounts: @layout borsh](language-accounts.md#anchors-account-bytes-layout-borsh) |
115
+ | `@repr`, `@serialization bytemuck` | [Accounts: Zero-copy types](language-accounts.md#zero-copy-types-as-anchors-idl-describes-them) |
116
+ | `@bytes`, `@idlName`, `key_` | [Accounts: Field names and bytes for the IDL](language-accounts.md#field-names-and-bytes-for-the-idl) |
117
+ | accounts created by hand, `initAccount` | [Accounts: Accounts created by hand](language-accounts.md#accounts-created-by-hand) |
118
+ | remaining accounts, `loadAccount` | [Accounts: Remaining accounts](language-accounts.md#remaining-accounts) |
119
+ | other programs' accounts, `readData`, `writeData` | [Accounts: Other programs' accounts](language-accounts.md#other-programs-accounts) |
120
+ | `realloc`, `resizeAccount` | [Accounts: Closing and resizing](language-accounts.md#closing-and-resizing) |
121
+ | sysvars | [Chain: Sysvars](language-chain.md#sysvars) |
122
+ | hashing, signatures, `findProgramAddress` | [Chain: Hashing](language-chain.md#hashing), [Signatures](language-chain.md#signatures), [PDAs: Deriving addresses](language-pdas.md#deriving-addresses-in-the-body) |
123
+ | oracles | [Chain: Oracles](language-chain.md#oracles) |
124
+ | randomness | [Chain: Randomness](language-chain.md#randomness) |
125
+ | Token-2022 extension reads | [CPI: Token-2022 extension reads](language-cpi.md#token-2022-extension-reads) |
126
+ | Metaplex Core | [CPI: Metaplex Core](language-cpi.md#metaplex-core) |
127
+ | compressed NFTs | [CPI: Compressed NFTs](language-cpi.md#compressed-nfts-bubblegum) |
128
+ | native Borsh accounts (`loadBorsh`) | [Native: Borsh accounts](language-native.md#borsh-accounts) |
129
+ | `BigVec` | [Native: BigVec](language-native.md#lists-over-the-rest-of-an-account-bigvec) |
130
+ | views at run-time offsets | [Native: Views at run-time offsets](language-native.md#views-at-run-time-offsets) |
131
+ | lib-sokoban's red-black tree | [Native: Red-black tree](language-native.md#lib-sokobans-red-black-tree) |
132
+
133
+ ### Account parameters and the checks they emit
134
+
135
+ | Topic | Where |
78
136
  | --- | --- |
79
- | `Signer` / `Mut<Signer>` | signed (and writable) |
80
- | `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 |
81
- | `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 |
82
- | `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 |
83
- | `/** @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 |
84
- | 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 |
85
- | `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) |
86
- | `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 |
87
- | `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>` |
88
- | `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) |
89
- | `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) |
90
- | `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 |
91
- | `Address<A, "4Nd1…">` | exact address (2012; `address` in the IDL) |
92
- | `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 |
93
- | `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) |
94
- | `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 |
95
- | `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` |
96
- | `EventAuthority`, `SelfProgram` | Anchor's `["__event_authority"]` PDA, and this program's own address, for `emitCpi` |
97
- | `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 { … }` |
98
- | `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 |
99
- | `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 |
100
- | `Init<Mint>`, `InitIfNeeded<Mint>` | Anchor `init` / `init_if_needed` with `mint::decimals` / `mint::authority` / `mint::freeze_authority`: `const bump = mint.create(payer, ["mint", payer.key], 6n, authority, freezeAuthority \| null)` creates the mint at that PDA of this program, or with `null` seeds as a new keypair account that signs (3010 if it did not), under the instruction's token program (its only token program parameter, or one passed as the last argument of `create` / `createIfNeeded`; plus `SystemProgram`). Token-2022 extensions (Anchor's `extensions::…`) go after the freeze authority: `mint.create(payer, null, 6n, authority, null, { metadataPointer: { authority, metadataAddress: mint.key }, transferHook: { authority, programId }, closeAuthority, permanentDelegate, nonTransferable: true, defaultAccountState: true, interestBearing: { rateAuthority, rate }, transferFee: { configAuthority, withdrawAuthority, basisPoints, maximumFee }, groupPointer, groupMemberPointer })` sizes the mint for them (as Token-2022 does: extensions adding up to a Multisig's 355 bytes give a 357-byte mint) and initializes each before InitializeMint2; a `null` authority is sent as Token-2022's empty COption. With `createIfNeeded` an existing mint must carry groupPointer / groupMemberPointer / metadataPointer / closeAuthority / permanentDelegate / transferHook with those keys (Anchor's 2024–2039); extensions not listed are not looked at, so an existing mint may carry others (a permanent delegate, say). `createIfNeeded(…)` returns whether it created it; an existing one must be that PDA and have those decimals and authorities (2018 / 2016 / 2017) |
101
- | `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) |
102
- | `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` |
103
- | `Mint` / `Mut<Mint>` | owned by SPL Token or Token-2022, initialized; `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
104
- | `SystemProgram`, `TokenProgram`, `Token2022Program` | exact program address |
105
- | `TokenInterface` | either token program |
106
- | `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
107
- | `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
108
- | `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)` |
109
- | `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) |
110
- | `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) |
111
- | `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 |
112
- | `Program<"Address…">` | exact program address + executable |
113
- | `UncheckedProgram` | executable only — check `.key` yourself |
114
- | `AccountInfo` / `Mut<AccountInfo>` | nothing (writable for `Mut`); `owner`, `executable` |
115
- | `SystemAccount` / `Mut<SystemAccount>` | owned by the System Program, e.g. a wallet (Anchor `SystemAccount`, 3011) |
116
-
117
- 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).
118
-
119
- Two writable parameters can never be the same account: aliasing is refused with error 2040 (also when a remaining
120
- account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
121
- (Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed
122
- or `@layout borsh`; a close destination may be one, the rent reaching it through either): a write through either is
123
- seen through the other, so read what you need before writing. A reference into one of them (`const e = a.entries.get(i)`)
124
- cannot be used after a push, pop or clear through the other moved that data, as with one name (compile error); copy
125
- the fields first. A remaining account
126
- can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
127
- with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
128
- `AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
129
- of a position, as Raydium CLMM's tick arrays).
130
-
131
- ## Built-ins
132
-
133
- - `systemProgram.transfer(from, to, lamports, signerSeeds?)` (`from` is a `Mut<Signer>`, or a system-owned PDA of this
134
- program, a SOL vault, with its seeds), `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
135
- (the new account signs: a keypair `Mut<Signer>` or this program's PDA), `systemProgram.createPda(payer, account, space,
136
- owner, seeds)` (Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: a `Mut<AccountInfo>`
137
- that must be this program's PDA for `seeds` (2006), created owned by `owner`, or topped up, allocated and assigned when
138
- someone funded the address first; returns the bump, records the PDA in the IDL, and among the creates a body starts
139
- with runs before the constraints), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
140
- - Token programs (`TokenProgram`, `Token2022Program`, `TokenInterface`) — pass `signerSeeds` (with the bump) when the authority is a PDA:
141
- `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),
142
- `approve(source, delegate, owner, amount)`, `revoke`, the checked forms `mintToChecked(mint, to, authority, amount)`,
143
- `burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
144
- come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
145
- `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
146
- `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
147
- - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts (the destination
148
- is another writable account; the account is not used after it in the function, except its `key`: compile errors, or
149
- 2040 at run time in a helper given one account twice)
150
- - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
151
- stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
152
- among up to 256 addresses for the same seeds
153
-
154
- ## Implementing another program's interface (transfer hooks)
155
-
156
- `/** @discriminator spl-transfer-hook-interface:execute */` above an instruction replaces its Anchor discriminator with
157
- sha256(preimage)[..8] (or `@discriminator 0x…` for raw bytes), so a TypeSOL program can be a Token-2022 transfer hook:
158
- `execute(source, mint, destination, owner, extraMetas, ...extraAccounts, amount)` plus
159
- `initExtraAccountMetas(payer, account, mint, systemProgram, extraAccounts?)` for the validation account (an
160
- ExtraAccountMetaList). Extra accounts are listed as `{ address, isSigner?, isWritable? }` (a fixed address) or
161
- `{ seeds: [...], program?, isSigner?, isWritable? }` (a PDA of this program, or with `program: i` of the program at account
162
- index i), with seeds from string literals, `seedAccountKey(i)`, `seedAccountData(i, offset, length)` and
163
- `seedInstructionData(offset, length)`; Token-2022 resolves and checks them on every transfer. The first extra account has
164
- index 5. `updateExtraAccountMetas(...)` rewrites and resizes an existing list. See `test/fixtures/hook.ts` and the
165
- transfer-hook ports.
166
-
167
- ## Calling other programs
168
-
169
- ```ts
170
- export function relayIncrement(authority: Signer, counter: Mut<AccountInfo>, counterProgram: Program<"JD2v…99Y2">, by: u64): void {
171
- invoke(counterProgram, [readonlySigner(authority), writable(counter)], [sighash("increment"), by]);
172
- }
173
-
174
- // Sign for a PDA of this program: raw System transfer (u32 tag 2, u64 lamports) out of a treasury PDA.
175
- export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: Mut<SystemAccount>, systemProgram: SystemProgram, amount: u64, bump: u8): void {
176
- invoke(systemProgram, [writableSigner(treasury), writable(recipient)], [u32(2n), amount], ["treasury", admin.key, bump]);
177
- }
178
- ```
179
-
180
- - program: a `Program<"address">` (key and executable checked on entry), an `UncheckedProgram`, an
181
- `Address<AccountInfo, "address">` (Anchor's `#[account(address = ID)]` on an `UncheckedAccount`: only the key is
182
- checked, 2012), the system or a token program, or a remaining account.
183
- - accounts: `readonly(x)`, `writable(x)`, `readonlySigner(x)`, `writableSigner(x)`. The compiler refuses `writable` on a
184
- non-`Mut` parameter and a signer flag on an account that neither signed nor is covered by `signerSeeds`. An optional
185
- account passed as it is (`readonly(x)` / `writable(x)` with `x: A | null`, no `!`) is left out of the list when it
186
- was not passed, as Rust's `if let Some(x) = &self.x { accounts.push(…) }` does.
187
- - data (Borsh): integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
188
- Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
189
- `sighash("name")` (Anchor discriminator), `hex("0a0b")`. Up to 1024 bytes.
190
- - `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
191
- lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
192
- - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
193
- wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
194
- signer([…, bump])`. A named list, and one given to a helper, holds its seeds as they were when it was written (JS
195
- evaluates the array then): a field or local changed afterwards does not change what it signs for. A list written in
196
- a call (`transfer(…, signer([…]))`, `create(payer, [...], space)`) holds them as they were when the list was read,
197
- even when a later argument changes a seed.
198
- - `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
199
- - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
200
- A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
201
- unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
202
- declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106.
203
-
204
- A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
205
- `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`):
206
-
207
- ```ts
208
- invokeInstruction(transaction.programId, transaction.accounts, transaction.data, remainingAccounts(), [multisig.key, multisig.nonce]);
209
- ```
210
-
211
- - the accounts are a list of structs with `pubkey`, `isSigner` and `isWritable` (a Vec or FixedVec in account data, a
212
- Vec argument, a stored `map` result, or a local list built on the stack); the data a list of u8 (the same, the
213
- instruction data or a slice of it).
214
- - every account in the fourth argument (`remainingAccounts()` or a slice; in a helper, its `RemainingAccounts`
215
- parameter or a slice of it) is handed to the runtime, which finds each meta's account there by key: one that is
216
- missing fails the call, as under Rust (MissingAccount, "Instruction references an unknown account").
217
- - so a native port builds the instruction as Rust's instruction builders do, in a helper too, with metas naming
218
- accounts by key:
219
-
220
- ```ts
221
- function transfer(rest: RemainingAccounts, data: InstructionBytes, to: Pubkey): void {
222
- const metas: FixedVec<Meta, 2> = fixedVec([{ pubkey: rest.get(0n).key, isSigner: true, isWritable: true }]);
223
- metas.push({ pubkey: to, isSigner: false, isWritable: true });
224
- const ix: FixedVec<u8, 12> = fixedVec([2n, 0n, 0n, 0n]); // system_instruction::transfer
225
- ix.pushAll(data.slice(1n, 9n)); // the lamports, as sent
226
- invokeInstruction(rest.get(2n).key, metas, ix, rest);
227
- }
228
- ```
229
- - the runtime checks the privileges: a meta may be a signer or writable only as the transaction passed that account,
230
- or as a PDA of this program the seeds (fifth argument) sign for. See `showcase/mainnet/multisig/multisig.ts`.
231
-
232
- Typed calls from an IDL: `typesol cpi other.json --out other_cpi.ts` writes one helper per instruction
233
- (`vaultDeposit(program, owner, vault, systemProgram, amount, seeds)`), with the account flags, discriminator and
234
- argument encoding taken from the IDL (Anchor 0.30+ / 1.x, or TypeSOL's own). Call it with `signer([...seeds, bump])`
235
- when a PDA of your program signs, or `signer([])`. Instructions whose arguments have no Borsh-identical TypeSOL type
236
- (strings or Options inside structs, data-carrying enums) are listed and left out.
237
-
238
- ## PDAs in the IDL
239
-
240
- When an instruction calls `x.create(payer, seeds)` or `requirePda(x, seeds, bump)` and every seed is a string literal,
241
- an integer literal, an argument, `acct.key` or a scalar field of an account, the IDL entry for `x` gets Anchor `pda.seeds`
242
- (`const` / `arg` / `account`), so Anchor and Codama clients derive the address themselves.
243
-
244
- ## Programs and sysvars passed as remaining accounts
245
-
246
- A native program takes its programs and sysvars by position too. `programAt<P>(account)` checks a remaining account
247
- (or an `AccountInfo` parameter) is that program, once, by its key, and gives it P's typed methods:
248
-
249
- ```ts
250
- const rest = remainingAccounts();
251
- const stake = programAt<StakeProgram>(rest.get(12n)); // ProgramError.IncorrectProgramId if it is another account
252
- stake.split(rest.get(3n), rest.get(4n), rest.get(1n), lamports, [pool.key, "withdraw", bump]);
253
- const minimum = stake.getMinimumDelegation();
254
- programAt<TokenInterface>(rest.get(10n)).mintTo(rest.get(7n), rest.get(8n), rest.get(1n), amount, seeds);
255
- ```
256
-
257
- - P is `StakeProgram`, `SystemProgram`, `TokenProgram`, `Token2022Program`, `TokenInterface` (either token program),
258
- `AssociatedTokenProgram` or `MemoProgram`. Bind it with `const`, or call a method on it directly; pass it to a helper
259
- that takes that program type.
260
- - `sysvarAt<StakeHistorySysvar>(account)` does the same for the StakeHistory sysvar (ProgramError.InvalidArgument for
261
- another account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)` … as on a parameter (read its fields
262
- through a `const` bound to it; methods also work on the call itself).
263
- - Every typed CPI (System, SPL Token and Token-2022, ATA, Memo, Stake) takes, for each account, a declared parameter,
264
- a remaining account (`rest.get(i)`, a local bound to one, a `RemainingAccount` helper parameter), a struct loaded
265
- from one, or an `AccountInfo` parameter where a `TokenAccount` or `Mint` goes. Declared parameters keep their
266
- compile-time checks (writable slots need `Mut<…>`, an authority without signerSeeds a `Signer`). A remaining account
267
- is not checked by the compiler, and unlike `invoke` the typed calls add no runtime check of their own: the runtime
268
- refuses a CPI that makes an account writable or a signer when the transaction did not (and no seeds sign for it),
269
- and the called program checks the rest (a token account's mint and owner, a stake account's authorities).
270
- - The cost is the key check (four 8-byte compares) and the call itself: within a few compute units of the same call
271
- written with `invoke`, which checks only the executable flag (test/integrations/native-cpi.test.ts measures it).
272
-
273
- ## Porting a native program
274
-
275
- A program written without Anchor (Raydium AMM v4, SPL programs) reads a tag byte and its arguments itself and takes its
276
- accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-amm` and `test/fixtures/native.ts`):
277
-
278
- - One `/** @fallback */` entry: `const data = instructionData()` gives the bytes, with `data.readU8/U16/U32/U64/U128/
279
- readPubkey(offset)` (little-endian, bounds-checked: 5104), and the list methods, `for … of`, `data.slice(a, b)`
280
- (a view, 5104 out of range) and `out.pushAll(data.slice(a, b))` (a memcpy into a local FixedVec); a helper takes it as
281
- an `InstructionBytes` parameter. `remainingAccounts()` gives the accounts by position.
282
- - Calls to System, Token and Stake: `programAt<P>(acct)` and the typed methods, with remaining accounts (above), not
283
- hand-encoded `invoke` data.
284
- - Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
285
- byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
286
- original's own checks (an exact size, its error codes) before the load. A read-only view can be read where it is
287
- made, `loadRaw<Header>(market).inner.b` or `loadRawAt<Prefix>(market, 576n).tick` (its checks made there); a
288
- writable one claims its account once per instruction, so it is bound to a const first. The owner check of these views (and of
289
- `loadRawAt`, `rawArrayAt`, `rbTreeAt` below) is made every time, but the last account found this program's passes
290
- again with one pointer compare instead of 32 bytes until a CPI or an owner write (`assignOwner`, `closeRaw`,
291
- `close`): helpers that each view the market again, and views in loops, pay about 3 compute units for it instead of
292
- about 14. Structs are packed, as `#[repr(C, packed)]`.
293
- - Borsh accounts without a discriminator (SPL Stake Pool's `StakePool`, read with `try_from_slice_unchecked` and
294
- written with `serialize`): `const pool = loadBorsh<StakePool>(acct)` decodes the data from byte 0 into a local
295
- struct (a copy: fields updated, Options narrowed and set to null or a value, data enums switched, copied, passed to
296
- helpers), and `storeBorsh(acct, pool)` encodes it back from byte 0. As Rust: no owner check and no discriminator
297
- (check the owner first, as the original does); bytes after the value are ignored when reading and left as they were
298
- when writing (an Option that became None leaves its old bytes behind it); data too short, an Option tag or boolean
299
- 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
300
- account too small for the encoding fail with `ProgramError.BorshIoError`. `acct` is a remaining account, a
301
- `RemainingAccount` helper parameter or an `AccountInfo` parameter (`Mut<AccountInfo>` for `storeBorsh`; a remaining
302
- account must be writable, 3006). `T` may hold integers, booleans, Pubkeys, enums, FixedArrays, `FixedString<N>`,
303
- `FixedVec<T, N>`, Options, data enums with fixed-size payloads and nested structs of those, with or without
304
- `@layout borsh`; not `Vec<T>` or `string` (they would need the heap or a view). Each struct gets its own
305
- straight-line decoder and encoder (no heap): about 280 CU to read a 611-byte `StakePool` and 610 CU to read and
306
- write it back. The local lives on the stack (4 KiB per function).
307
- - Lists over the rest of an account (SPL's `big_vec`): a struct ending in `BigVec<T>`, `const list =
308
- loadRawMut<ValidatorList>(acct)`, then `list.validators.push(…)`, `.retain((v) => …)`, `.findIndex((v) => …)`,
309
- `for (const v of list.validators.slice(skip, skip + len))` (`deserialize_mut_slice(skip, len)`). The load fails with
310
- AccountDataTooSmall when the stored length does not fit, where the Rust would only panic on reaching such an element:
311
- check the length first (`readData<u32>(acct, offset)`) where the original returns an error of its own before that.
312
- - Parts at offsets the account's header gives: `loadRawAt<T>(acct, offset)` / `loadRawMutAt<T>(…)` for a struct,
313
- `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt<T>(…)` for a run-time number of elements, each bounds-checked
314
- once when it is made (ProgramError::AccountDataTooSmall; `loadRaw`'s fixed size check stays 3003, the error of a
315
- view whose size is known when the program is compiled), as Phoenix slices `&data[576..]` after checking the
316
- account's size itself. `rbTreeAt(…).length` and `.capacity` read a tree made for the one read; anything else on a
317
- tree or a raw array is done on a const bound to it. The checks a Rust original makes first (a size, its own error code) go before the view.
318
- - lib-sokoban's trees (Phoenix's order books and trader seats): `rbTreeMutAt<K, V>(acct, offset, capacity, compare?)`,
319
- every write the crate's own, so the account matches the original after every instruction:
320
-
321
- ```ts
322
- /** Phoenix's FIFOOrderId Ord: a bid's sequence number is stored inverted (top bit set); bids descend, asks ascend. */
323
- function orderCmp(a: FIFOOrderId, b: FIFOOrderId): i8 {
324
- if (a.order_sequence_number >> 63n === 1n) {
325
- // a bid (the left key's side decides): `other.cmp(self)`
326
- if (a.price_in_ticks !== b.price_in_ticks) return b.price_in_ticks < a.price_in_ticks ? -1n : 1n;
327
- return b.order_sequence_number < a.order_sequence_number ? -1n : b.order_sequence_number > a.order_sequence_number ? 1n : 0n;
328
- }
329
- if (a.price_in_ticks !== b.price_in_ticks) return a.price_in_ticks < b.price_in_ticks ? -1n : 1n;
330
- return a.order_sequence_number < b.order_sequence_number ? -1n : a.order_sequence_number > b.order_sequence_number ? 1n : 0n;
331
- }
332
- const bids = rbTreeMutAt<FIFOOrderId, FIFORestingOrder>(market, 880n, n, orderCmp);
333
- const best = bids.min(); // the best bid, or null
334
- if (best !== null && best.value.num_base_lots > 0n) best.value.num_base_lots -= fill;
335
- const index = traders.addrOf(trader); // a seat's node index, 0 when absent
336
- // a cancel: find the order, check it, then remove that node (no second search)
337
- const at = bids.addrOf(orderId);
338
- if (at !== 0n && bids.nodeAt(at).value.trader_index === traderIndex) bids.removeAt(at);
339
- ```
340
-
341
- The C runs sokoban's get_addr / _insert / _remove / rotations / allocator statement for statement, with the node
342
- stride a constant (512 entries: get 166 CU, insert 493, remove 294, min 94; 4096: 215 / 595 / 355 / 112, against
343
- 300 / 604 / 497 / 191 and 384 / 742 / 618 / 225 for lib-sokoban built with cargo-build-sbf). sokoban's panics are
344
- Rust panics in the original; the tree reproduces each as solana-program up to 1.17 reports one (Phoenix's build):
345
- the log line `panicked at '<message>', <file>:<line>:<column>`, then the runtime's abort ("SBF program panicked",
346
- ProgramFailedToComplete), with sokoban's messages and source lines as Phoenix's binary holds them (`src/…`):
347
- `initialize()` on an allocator that is not all zero, "Cannot reinitialize NodeAllocator" (src/node_allocator.rs:249:13);
348
- an empty tree's insert with no room (capacity 0, or a damaged allocator), "Buffer is full, size N" (:269:17); and on
349
- damaged registers only, "Nodes are not connected" (src/red_black_tree.rs:429:13), "assertion failed:
350
- self.is_root(parent)" (:503:17), "assertion failed: self.is_leaf(max_left)" (:598:17), a size going below zero
351
- ("attempt to subtract with overflow", src/node_allocator.rs:291:9). A node index outside 1..capacity, from `nodeAt`
352
- or a damaged register, panics as Rust's `nodes[i - 1]` would ("index out of bounds: the len is N but the index is
353
- I", src/node_allocator.rs:255:10; index 0, "attempt to subtract with overflow", :255:21: locations read from the
354
- source, not from a binary), so a damaged tree never reads outside the account. A port makes the original's checks
355
- in the original's order before the tree call, and these lines follow on their own. Iteration keeps its stack on the
356
- program's stack (64 nodes, more than any red-black tree a u32 index can address holds on one path); a deeper,
357
- damaged tree panics where the Rust's heap stack would grow. A walk costs about 34 compute units per node, a sum in
358
- its body included (each node's index checked once, when the walk reaches it). A tree is a const of the function that makes it, not
359
- a helper parameter (make it again in the helper from the account).
360
- - Writes as the original makes them: `export const NATIVE_ACCOUNT_WRITES = true` (anywhere in the program; opt-in, for
361
- native ports). A native program writes account data in place and the runtime judges afterwards: a read-only account
362
- whose data actually changed fails the instruction (`ReadonlyDataModified`, or an access violation at the write under
363
- account-data direct mapping), one that was only read (or written with the bytes it held) is fine, and an account
364
- passed twice is two `AccountInfo`s over one buffer. By default
365
- `loadRawMut` and `storeBorsh` check writability up front (3006), `loadRawMut` claims the account once and
366
- `storeBorsh` refuses an account passed more than once (2040, as a write to a remaining account's lamports), so a
367
- port fails where the original succeeds (a read-only validator list that is only read; the list passed again as a
368
- stake account, which the original skips by its address checks). With the flag, `loadRawMut`, `storeBorsh` and the
369
- BigVec writes through a `loadRawMut` view skip both, and both take a plain `AccountInfo` parameter (no `Mut<…>`
370
- needed). Owner and size checks stay. **The trade-off:** a write to a read-only account is reported by the runtime at
371
- the end, not at the write, and two loads of one account are two views of the same bytes (a write through one is
372
- read through the other), where Rust's `RefCell` would fail a second `borrow_mut()` while the first is held (a panic,
373
- or `AccountBorrowFailed` through `try_borrow_mut_data`). The original's own address and type checks normally refuse
374
- such a pair before it is loaded (SPL Stake Pool's PDA checks); make them in the same order, before the load. Only
375
- data writes are affected: with or without the flag every view reads the account's bytes in place, so a `loadRaw`
376
- of an account also loaded with `loadRawMut` (or written with `storeBorsh`) reads what was written, BigVec pushes
377
- included; the flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position or
378
- another, is 2040 without it). `.lamports` on remaining accounts, `loadAccountMut`, CPI account metas and the checks of
379
- `Mut<…>` parameters stay as they are, and programs without the flag compile exactly as before.
380
- - Accounts closed, reassigned and resized by hand, on remaining accounts and `AccountInfo` parameters:
381
- `closeRaw(account, receiver)` is what Phoenix's Tombstone writes, in its order: `receiver.lamports +=
382
- account.lamports` (checked), `account.lamports = 0`, `assign(&system_program::id())`, `realloc(0, false)`. Unlike
383
- `close` the data is not zeroed first (a realloc to 0 drops it, and the runtime then accepts the new owner), so it
384
- costs a few compute units whatever the account's size, and the account ends as the original's does (gone, its
385
- lamports in the receiver; test/language/native-close.test.ts compares it with Phoenix's own Tombstone).
386
- `assignOwner(account, owner)` is `AccountInfo::assign` (the runtime accepts it for a writable account of this program
387
- whose data is empty or zeroed), and `resizeAccount(account, size)` also takes a remaining account (`realloc(size,
388
- true)`: new bytes zeroed, at most 10 KiB past the size it had when the instruction started, 3016; that size is the one
389
- the entrypoint records in the account's record, as solana_program 1.14's does, only in programs that resize a
390
- remaining account). A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node
391
- or a struct read through one) is a compile error to use after it: its bounds were checked against the old length, so
392
- take the view again. Without `NATIVE_ACCOUNT_WRITES` the accounts are checked as other writes the compiler cannot see
393
- are: writable (3006; a parameter must be `Mut<AccountInfo>`), passed once (2040), the closed or reassigned account
394
- this program's (3007), and not closed into itself (2040). With it nothing is checked and the runtime judges, as for
395
- the original (`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`),
396
- and plain `AccountInfo` parameters are enough.
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
- - Panics as an older solana-program writes them: `export const PANIC_STYLE = "solana-1.14"` (a program built with
407
- solana-program 1.14 to 1.17, whose rustc formats a panic before 1.73 did: Phoenix v1) makes `panic(message,
408
- location)` log `panicked at '<message>', <location>` and then abort, so the runtime's last line is "SBF program
409
- panicked" with no location, as that panic handler leaves it (`panic(null, …)` is refused there: the handler always
410
- logs; without a location the TypeScript line and column are used). `PANIC_ON_OVERFLOW`'s panics abort too.
411
- - Overflow panics with Rust's message and location: `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
412
- checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
413
- "attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder
414
- with a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow" and "attempt to shift
415
- left / right with overflow" for a shift amount past the width), logged as `panic` logs (`PANIC_STYLE` above, else
416
- the message and sol_panic_ at the location), instead of failing with 5100 / 5101; with or without
417
- `PANIC_ON_OVERFLOW`, which applies outside it. Rust reports the location of the expression the operator belongs
418
- to, so the wrapper goes around that expression: only the operators written inside it take the location (not those
419
- of the helpers it calls), an inner `panicsAt` gives its operators their own (`panicsAt(A, x + panicsAt(B, y * z))`),
420
- and as a statement it takes an assignment, `panicsAt(LOC, total += fee);`. A Rust newtype's operator panics at its
421
- `impl` (Phoenix's `QuoteLots + QuoteLots` at the macro line in quantities.rs, wherever the addition is written): give
422
- the port a helper, `function addQuoteLots(a: u64, b: u64): u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`. The
423
- bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks them
424
- differently, or with other messages).
425
- test/language/rust-panics.test.ts checks the lines against the Phoenix binary's own panics.
426
- - Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
427
- "Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`); `null`
428
- logs no failure line at all, as a native program returns an error its own checks already explained (Phoenix): the
429
- program's errors and codes its helpers return (`ERROR_LOG_PREFIX = null`), built-in ProgramErrors and `programAt`'s
430
- check (`PROGRAM_ERROR_LOG_PREFIX = null`), each about 110 CU cheaper than a logged one (constraint errors and the
431
- compiler's own checks still log);
432
- `logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
433
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address);
434
- `logComputeUnits()` is `sol_log_compute_units()`: the runtime writes "Program consumption: N units remaining" at
435
- that point, as for the original (Phoenix's cancel and withdraw paths log it).
436
- - Byte strings built by hand (instruction data for a self-CPI, a log record, return data) in a `FixedVec<u8, N>`, a
437
- local list or one in account data: `buf.pushLE(x)` appends an integer's little-endian bytes at its width (u8 … u128,
438
- i8 … i128; a literal needs one: `buf.pushLE<u16>(1n)` or `buf.pushLE(u16(1n))`), `buf.pushKey(key)` a Pubkey's 32
439
- bytes, `buf.pushBorsh(value)` a value's Borsh encoding with the codecs `invoke`, events and `storeBorsh` use (a
440
- struct, or an object literal given its type, `buf.pushBorsh<Header>({ … })`; a data enum, its tag then the variant's
441
- fields; a FixedArray; a list, its u32 count then the elements; integers, booleans, Pubkeys, strings and Options; a
442
- data-enum literal of a fixed-size variant costs what the same bytes cost with `pushLE`: its fields evaluated in
443
- order, then one room check and a store of each),
444
- `buf.setLE(offset, x)` (or `setLE<u16>(offset, x)`) overwrites bytes within the length, as Rust's
445
- `data[a..b].copy_from_slice(…)`, and `buf.truncate(n)` keeps the first `n`. Past the room (or, for `setLE` and
446
- `truncate`, past the length) fails with 5104 and the length does not move. Phoenix's event recorder, which the test
447
- checks byte for byte against the Phoenix binary's batches:
448
-
449
- ```ts
450
- const data: FixedVec<u8, 1280> = fixedVec([15n]); // PhoenixInstruction::Log
451
- data.pushBorsh<PhoenixMarketEvent>({ kind: "Header", instruction, sequenceNumber, timestamp: now(), slot: currentSlot(), market, signer, totalEvents: 0n });
452
- // … for each event, the batch sent first if it would not fit: data.pushBorsh<PhoenixMarketEvent>({ kind: "Fill", index, … });
453
- data.setLE(91n, u16(batchSize)); // total_events of this batch
454
- invokeInstruction(programId(), metas, data, rest, ["log", bump]);
455
- data.truncate(93n); // back to the header
456
- ```
457
- - Return data as the original sets it: `setReturnData(bytes)` is `set_return_data(&bytes)`, the bytes as they are, from
458
- the `@fallback` entry, a helper or a void instruction (Phoenix's Borsh `Vec<FIFOOrderId>` of the orders that rested,
459
- built in a local `FixedVec<u8, N>`). `bytes` is a list of u8: a local FixedVec, a Vec or FixedVec in account data, or
460
- the instruction data or a slice of it. The last call wins and an empty list clears it; a CPI made afterwards replaces
461
- it with the callee's (call it after the last CPI, as Rust must). More than 1024 bytes fails as the Rust call does: the
462
- runtime refuses it ("Return data too large (1025 > 1024)"). An instruction that returns a value cannot call it (a
463
- compile error: its return value is its return data); a helper it calls may, and the instruction's return value, set
464
- last, replaces what the helper set.
137
+ | every account type and what it checks | [Accounts: Account parameters](language-accounts.md#account-parameters-and-the-checks-they-emit) |
138
+ | `Init`, `InitIfNeeded`, `create`, `space` | [Accounts: Creating accounts](language-accounts.md#creating-accounts) |
139
+ | `Zeroed<T>`, `Signed<Zeroed<T>>` | [Accounts: Zeroed accounts](language-accounts.md#zeroed-accounts) |
140
+ | `Migrate<From, To>` | [Accounts: Migrating an account](language-accounts.md#migrating-an-account) |
141
+ | constraints: `HasOne`, `Seeds`, `CloseTo`, `Address`, `Owner`, `Executable`, `Signed`, your own errors, `constraint(…)` | [Accounts: Constraints](language-accounts.md#constraints) |
142
+ | `Seeds<…>`, `"@name"`, bumps, `pdaBump` | [PDAs: Seeds constraints](language-pdas.md#seeds-constraints) |
143
+ | token accounts and mints, `TokenOf`, `MintOf`, `Ata` | [CPI: Token accounts and mints as parameters](language-cpi.md#token-accounts-and-mints-as-parameters) |
144
+ | `Init<Mint>`, `Init<TokenAccount>`, ATAs, mint extensions | [CPI: Creating mints and token accounts](language-cpi.md#creating-mints-and-token-accounts) |
145
+ | optional accounts | [Accounts: Optional accounts](language-accounts.md#optional-accounts) |
146
+ | account groups | [Accounts: Account groups](language-accounts.md#account-groups) |
147
+ | `ProgramData` | [Accounts: ProgramData](language-accounts.md#programdata) |
148
+ | the `@fallback` entry | [Native: The fallback entry](language-native.md#the-fallback-entry) |
149
+ | `InstructionsSysvar` introspection | [Chain: Instruction introspection](language-chain.md#instruction-introspection) |
150
+ | program and sysvar parameters | [Accounts: Account parameters](language-accounts.md#account-parameters-and-the-checks-they-emit) |
151
+ | `MAX_ACCOUNTS` | [Accounts: How many accounts](language-accounts.md#how-many-accounts) |
152
+ | two parameters, one account (2040), `Dup<…>` | [Accounts: Two parameters, one account](language-accounts.md#two-parameters-one-account) |
153
+
154
+ ### Built-ins
155
+
156
+ | Topic | Where |
157
+ | --- | --- |
158
+ | `systemProgram.transfer`, `createAccount`, `createPda` | [CPI: The System Program](language-cpi.md#the-system-program) |
159
+ | token program methods | [CPI: Tokens](language-cpi.md#tokens) |
160
+ | `account.lamports`, `close` | [Accounts: Closing and resizing](language-accounts.md#closing-and-resizing) |
161
+ | `requirePda` | [PDAs: Checking a PDA in the body](language-pdas.md#checking-a-pda-in-the-body) |
162
+ | every exported name | [Built-ins](language-builtins.md) |
465
163
 
466
- ## Not supported yet
164
+ ### Implementing another program's interface (transfer hooks)
467
165
 
468
- A struct holding a FixedVec that is both an argument and account data (its bytes differ there, and the IDL describes a
469
- type one way: declare one for each), growing an account by more than 10 KiB in one instruction (Solana's limit: realloc
470
- again in the next instruction), `?.` and `!` on anything but optional accounts, Options and a `find` on struct elements,
471
- functions stored in a struct, chosen from a list by index or returned from an instruction, a fused `map` to strings
472
- (store it, annotated), floating point (by design).
473
- They are rejected at compile time rather than half-supported.
166
+ See [Calling other programs: transfer hooks](language-cpi.md#implementing-another-programs-interface-transfer-hooks).
167
+
168
+ ### Calling other programs
169
+
170
+ | Topic | Where |
171
+ | --- | --- |
172
+ | `invoke`: program, accounts, data | [CPI: invoke](language-cpi.md#invoke) |
173
+ | signer seeds, `signer([…])` | [PDAs: Signing as a PDA](language-pdas.md#signing-as-a-pda) |
174
+ | `returnData` | [CPI: Return data](language-cpi.md#return-data) |
175
+ | `invokeInstruction` | [CPI: invokeInstruction](language-cpi.md#invokeinstruction) |
176
+ | `typesol cpi`: typed calls from an IDL | [CPI: Typed calls from an IDL](language-cpi.md#typed-calls-from-an-idl) |
177
+ | Associated Token, Memo, Token Metadata, Stake | [CPI: Associated Token, Memo, Metadata and Stake](language-cpi.md#associated-token-memo-metadata-and-stake) |
178
+
179
+ ### PDAs in the IDL
180
+
181
+ See [PDAs: PDAs in the IDL](language-pdas.md#pdas-in-the-idl).
182
+
183
+ ### Programs and sysvars passed as remaining accounts
184
+
185
+ See [Calling other programs: programs and sysvars passed as remaining
186
+ accounts](language-cpi.md#programs-and-sysvars-passed-as-remaining-accounts).
187
+
188
+ ### Porting a native program
189
+
190
+ See [Porting a native program](language-native.md): the [fallback entry](language-native.md#the-fallback-entry),
191
+ [accounts without a discriminator](language-native.md#accounts-without-a-discriminator),
192
+ [writes as the original makes them](language-native.md#writes-as-the-original-makes-them) (`NATIVE_ACCOUNT_WRITES`),
193
+ [closing and resizing by hand](language-native.md#accounts-closed-reassigned-and-resized-by-hand),
194
+ [errors and panics](language-native.md#errors-and-panics-as-the-original-reports-them),
195
+ [log lines](language-native.md#log-lines-as-the-original-writes-them),
196
+ [byte strings](language-native.md#byte-strings-built-by-hand) and
197
+ [return data](language-native.md#return-data-as-the-original-sets-it).
474
198
 
475
- `Init.create` handles a PDA address someone pre-funded: it tops up rent, then allocates and assigns instead of
476
- `create_account` (which would fail).
199
+ **Next:** [Language basics](language-basics.md).