@typesol/cli 0.42.0 → 0.43.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 (44) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/README.md +10 -7
  3. package/dist/compiler/analyze.js +443 -12
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +25 -0
  9. package/dist/compiler/emit/base.js +58 -7
  10. package/dist/compiler/emit/calls.d.ts +67 -0
  11. package/dist/compiler/emit/calls.js +521 -46
  12. package/dist/compiler/emit/cpi-core.d.ts +20 -3
  13. package/dist/compiler/emit/cpi-core.js +226 -5
  14. package/dist/compiler/emit/cpi.js +8 -2
  15. package/dist/compiler/emit/expressions.js +38 -7
  16. package/dist/compiler/emit/program.js +30 -1
  17. package/dist/compiler/emit/rbtree.d.ts +7 -0
  18. package/dist/compiler/emit/rbtree.js +142 -0
  19. package/dist/compiler/emit/shared.d.ts +8 -0
  20. package/dist/compiler/emit/shared.js +9 -1
  21. package/dist/compiler/emit/statements.d.ts +27 -1
  22. package/dist/compiler/emit/statements.js +288 -19
  23. package/dist/compiler/emit/storage.d.ts +23 -2
  24. package/dist/compiler/emit/storage.js +100 -56
  25. package/dist/compiler/emit/token.js +2 -2
  26. package/dist/compiler/emit/views.d.ts +60 -0
  27. package/dist/compiler/emit/views.js +523 -0
  28. package/dist/compiler/idl.js +2 -1
  29. package/dist/compiler/model.d.ts +65 -4
  30. package/dist/compiler/model.js +14 -0
  31. package/dist/compiler/toolchain.d.ts +15 -0
  32. package/dist/compiler/toolchain.js +146 -11
  33. package/docs/architecture.md +9 -2
  34. package/docs/case-study-phoenix.md +226 -0
  35. package/docs/language.md +139 -8
  36. package/docs/migrate-from-anchor.md +1 -0
  37. package/docs/runtime.md +1 -1
  38. package/docs/stability.md +21 -2
  39. package/docs/troubleshooting.md +5 -2
  40. package/lib/typesol.d.ts +221 -4
  41. package/llms-full.txt +169 -14
  42. package/llms.txt +1 -1
  43. package/package.json +2 -2
  44. package/runtime/typesol_rt.h +407 -0
package/docs/language.md CHANGED
@@ -16,11 +16,12 @@ The full reference. For a tour, start with the [README](../README.md).
16
16
  | Logging | `log("text")`, `log(value)`, `log(pubkey)` |
17
17
  | Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
18
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; given another list (`const y: FixedVec<Pubkey, 4> = xs`) it is a copy, as a struct local is. One list holds at most 2 KiB (the 4 KiB stack frame is shared with the rest of the function): a bigger one is a compile error naming its size |
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
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
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
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
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 |
24
25
  | Pubkey constants | `const ADMIN = pubkey("4Nd1…")` (checked at compile time) or inline `pubkey("…")`; usable as seeds |
25
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 |
26
27
  | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
@@ -34,6 +35,8 @@ The full reference. For a tour, start with the [README](../README.md).
34
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 |
35
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) |
36
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)) |
37
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) |
38
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 |
39
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) |
@@ -41,17 +44,19 @@ The full reference. For a tour, start with the [README](../README.md).
41
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 |
42
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 |
43
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`) |
44
- | Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL) |
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 |
45
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 |
46
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) |
47
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 |
48
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 |
49
- | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash` (a PDA seed too: its 32 bytes, as Marginfi seeds an order with the hash of its bank keys); `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump; `programId()` → this program's address; `a.compare(b)` orders Pubkeys and Hashes as Rust orders their 32 bytes (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
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) |
50
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) (mainnet program unless `SwitchboardFeed<"devnet">`) |
51
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 |
52
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 |
53
- | Loops | `for (let i = 0n; i < n; i++)`, `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
54
- | Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
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; `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 |
55
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) |
56
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) |
57
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) |
@@ -271,7 +276,13 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
271
276
  hand-encoded `invoke` data.
272
277
  - Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
273
278
  byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
274
- original's own checks (an exact size, its error codes) before the load. Structs are packed, as `#[repr(C, packed)]`.
279
+ original's own checks (an exact size, its error codes) before the load. A read-only view can be read where it is
280
+ made, `loadRaw<Header>(market).inner.b` or `loadRawAt<Prefix>(market, 576n).tick` (its checks made there); a
281
+ writable one claims its account once per instruction, so it is bound to a const first. The owner check of these views (and of
282
+ `loadRawAt`, `rawArrayAt`, `rbTreeAt` below) is made every time, but the last account found this program's passes
283
+ again with one pointer compare instead of 32 bytes until a CPI or an owner write (`assignOwner`, `closeRaw`,
284
+ `close`): helpers that each view the market again, and views in loops, pay about 3 compute units for it instead of
285
+ about 14. Structs are packed, as `#[repr(C, packed)]`.
275
286
  - Borsh accounts without a discriminator (SPL Stake Pool's `StakePool`, read with `try_from_slice_unchecked` and
276
287
  written with `serialize`): `const pool = loadBorsh<StakePool>(acct)` decodes the data from byte 0 into a local
277
288
  struct (a copy: fields updated, Options narrowed and set to null or a value, data enums switched, copied, passed to
@@ -291,6 +302,54 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
291
302
  `for (const v of list.validators.slice(skip, skip + len))` (`deserialize_mut_slice(skip, len)`). The load fails with
292
303
  AccountDataTooSmall when the stored length does not fit, where the Rust would only panic on reaching such an element:
293
304
  check the length first (`readData<u32>(acct, offset)`) where the original returns an error of its own before that.
305
+ - Parts at offsets the account's header gives: `loadRawAt<T>(acct, offset)` / `loadRawMutAt<T>(…)` for a struct,
306
+ `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt<T>(…)` for a run-time number of elements, each bounds-checked
307
+ once when it is made (ProgramError::AccountDataTooSmall; `loadRaw`'s fixed size check stays 3003, the error of a
308
+ view whose size is known when the program is compiled), as Phoenix slices `&data[576..]` after checking the
309
+ account's size itself. `rbTreeAt(…).length` and `.capacity` read a tree made for the one read; anything else on a
310
+ 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.
311
+ - lib-sokoban's trees (Phoenix's order books and trader seats): `rbTreeMutAt<K, V>(acct, offset, capacity, compare?)`,
312
+ every write the crate's own, so the account matches the original after every instruction:
313
+
314
+ ```ts
315
+ /** Phoenix's FIFOOrderId Ord: a bid's sequence number is stored inverted (top bit set); bids descend, asks ascend. */
316
+ function orderCmp(a: FIFOOrderId, b: FIFOOrderId): i8 {
317
+ if (a.order_sequence_number >> 63n === 1n) {
318
+ // a bid (the left key's side decides): `other.cmp(self)`
319
+ if (a.price_in_ticks !== b.price_in_ticks) return b.price_in_ticks < a.price_in_ticks ? -1n : 1n;
320
+ return b.order_sequence_number < a.order_sequence_number ? -1n : b.order_sequence_number > a.order_sequence_number ? 1n : 0n;
321
+ }
322
+ if (a.price_in_ticks !== b.price_in_ticks) return a.price_in_ticks < b.price_in_ticks ? -1n : 1n;
323
+ return a.order_sequence_number < b.order_sequence_number ? -1n : a.order_sequence_number > b.order_sequence_number ? 1n : 0n;
324
+ }
325
+ const bids = rbTreeMutAt<FIFOOrderId, FIFORestingOrder>(market, 880n, n, orderCmp);
326
+ const best = bids.min(); // the best bid, or null
327
+ if (best !== null && best.value.num_base_lots > 0n) best.value.num_base_lots -= fill;
328
+ const index = traders.addrOf(trader); // a seat's node index, 0 when absent
329
+ // a cancel: find the order, check it, then remove that node (no second search)
330
+ const at = bids.addrOf(orderId);
331
+ if (at !== 0n && bids.nodeAt(at).value.trader_index === traderIndex) bids.removeAt(at);
332
+ ```
333
+
334
+ The C runs sokoban's get_addr / _insert / _remove / rotations / allocator statement for statement, with the node
335
+ stride a constant (512 entries: get 166 CU, insert 493, remove 294, min 94; 4096: 215 / 595 / 355 / 112, against
336
+ 300 / 604 / 497 / 191 and 384 / 742 / 618 / 225 for lib-sokoban built with cargo-build-sbf). sokoban's panics are
337
+ Rust panics in the original; the tree reproduces each as solana-program up to 1.17 reports one (Phoenix's build):
338
+ the log line `panicked at '<message>', <file>:<line>:<column>`, then the runtime's abort ("SBF program panicked",
339
+ ProgramFailedToComplete), with sokoban's messages and source lines as Phoenix's binary holds them (`src/…`):
340
+ `initialize()` on an allocator that is not all zero, "Cannot reinitialize NodeAllocator" (src/node_allocator.rs:249:13);
341
+ an empty tree's insert with no room (capacity 0, or a damaged allocator), "Buffer is full, size N" (:269:17); and on
342
+ damaged registers only, "Nodes are not connected" (src/red_black_tree.rs:429:13), "assertion failed:
343
+ self.is_root(parent)" (:503:17), "assertion failed: self.is_leaf(max_left)" (:598:17), a size going below zero
344
+ ("attempt to subtract with overflow", src/node_allocator.rs:291:9). A node index outside 1..capacity, from `nodeAt`
345
+ or a damaged register, panics as Rust's `nodes[i - 1]` would ("index out of bounds: the len is N but the index is
346
+ I", src/node_allocator.rs:255:10; index 0, "attempt to subtract with overflow", :255:21: locations read from the
347
+ source, not from a binary), so a damaged tree never reads outside the account. A port makes the original's checks
348
+ in the original's order before the tree call, and these lines follow on their own. Iteration keeps its stack on the
349
+ program's stack (64 nodes, more than any red-black tree a u32 index can address holds on one path); a deeper,
350
+ damaged tree panics where the Rust's heap stack would grow. A walk costs about 34 compute units per node, a sum in
351
+ 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
352
+ a helper parameter (make it again in the helper from the account).
294
353
  - Writes as the original makes them: `export const NATIVE_ACCOUNT_WRITES = true` (anywhere in the program; opt-in, for
295
354
  native ports). A native program writes account data in place and the runtime judges afterwards: a read-only account
296
355
  whose data actually changed fails the instruction (`ReadonlyDataModified`, or an access violation at the write under
@@ -311,6 +370,23 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
311
370
  included; the flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position or
312
371
  another, is 2040 without it). `.lamports` on remaining accounts, `loadAccountMut`, CPI account metas and the checks of
313
372
  `Mut<…>` parameters stay as they are, and programs without the flag compile exactly as before.
373
+ - Accounts closed, reassigned and resized by hand, on remaining accounts and `AccountInfo` parameters:
374
+ `closeRaw(account, receiver)` is what Phoenix's Tombstone writes, in its order: `receiver.lamports +=
375
+ account.lamports` (checked), `account.lamports = 0`, `assign(&system_program::id())`, `realloc(0, false)`. Unlike
376
+ `close` the data is not zeroed first (a realloc to 0 drops it, and the runtime then accepts the new owner), so it
377
+ costs a few compute units whatever the account's size, and the account ends as the original's does (gone, its
378
+ lamports in the receiver; test/language/native-close.test.ts compares it with Phoenix's own Tombstone).
379
+ `assignOwner(account, owner)` is `AccountInfo::assign` (the runtime accepts it for a writable account of this program
380
+ whose data is empty or zeroed), and `resizeAccount(account, size)` also takes a remaining account (`realloc(size,
381
+ true)`: new bytes zeroed, at most 10 KiB past the size it had when the instruction started, 3016; that size is the one
382
+ the entrypoint records in the account's record, as solana_program 1.14's does, only in programs that resize a
383
+ remaining account). A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node
384
+ or a struct read through one) is a compile error to use after it: its bounds were checked against the old length, so
385
+ take the view again. Without `NATIVE_ACCOUNT_WRITES` the accounts are checked as other writes the compiler cannot see
386
+ are: writable (3006; a parameter must be `Mut<AccountInfo>`), passed once (2040), the closed or reassigned account
387
+ this program's (3007), and not closed into itself (2040). With it nothing is checked and the runtime judges, as for
388
+ the original (`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`),
389
+ and plain `AccountInfo` parameters are enough.
314
390
  - Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
315
391
  `ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
316
392
  built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
@@ -320,10 +396,65 @@ accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-
320
396
  runtime's `abort` syscall, which logs "SBF program panicked" with no location; `const PANIC_ON_OVERFLOW = true`
321
397
  makes arithmetic overflow and division by zero panic as `checked_*().unwrap()` does instead of failing with 5100 /
322
398
  5101.
399
+ - Panics as an older solana-program writes them: `export const PANIC_STYLE = "solana-1.14"` (a program built with
400
+ solana-program 1.14 to 1.17, whose rustc formats a panic before 1.73 did: Phoenix v1) makes `panic(message,
401
+ location)` log `panicked at '<message>', <location>` and then abort, so the runtime's last line is "SBF program
402
+ panicked" with no location, as that panic handler leaves it (`panic(null, …)` is refused there: the handler always
403
+ logs; without a location the TypeScript line and column are used). `PANIC_ON_OVERFLOW`'s panics abort too.
404
+ - Overflow panics with Rust's message and location: `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
405
+ checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
406
+ "attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder
407
+ with a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow" and "attempt to shift
408
+ left / right with overflow" for a shift amount past the width), logged as `panic` logs (`PANIC_STYLE` above, else
409
+ the message and sol_panic_ at the location), instead of failing with 5100 / 5101; with or without
410
+ `PANIC_ON_OVERFLOW`, which applies outside it. Rust reports the location of the expression the operator belongs
411
+ to, so the wrapper goes around that expression: only the operators written inside it take the location (not those
412
+ of the helpers it calls), an inner `panicsAt` gives its operators their own (`panicsAt(A, x + panicsAt(B, y * z))`),
413
+ and as a statement it takes an assignment, `panicsAt(LOC, total += fee);`. A Rust newtype's operator panics at its
414
+ `impl` (Phoenix's `QuoteLots + QuoteLots` at the macro line in quantities.rs, wherever the addition is written): give
415
+ the port a helper, `function addQuoteLots(a: u64, b: u64): u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`. The
416
+ bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks them
417
+ differently, or with other messages).
418
+ test/language/rust-panics.test.ts checks the lines against the Phoenix binary's own panics.
323
419
  - Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
324
- "Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`);
420
+ "Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`); `null`
421
+ logs no failure line at all, as a native program returns an error its own checks already explained (Phoenix): the
422
+ program's errors and codes its helpers return (`ERROR_LOG_PREFIX = null`), built-in ProgramErrors and `programAt`'s
423
+ check (`PROGRAM_ERROR_LOG_PREFIX = null`), each about 110 CU cheaper than a logged one (constraint errors and the
424
+ compiler's own checks still log);
325
425
  `logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
326
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
426
+ `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address);
427
+ `logComputeUnits()` is `sol_log_compute_units()`: the runtime writes "Program consumption: N units remaining" at
428
+ that point, as for the original (Phoenix's cancel and withdraw paths log it).
429
+ - Byte strings built by hand (instruction data for a self-CPI, a log record, return data) in a `FixedVec<u8, N>`, a
430
+ local list or one in account data: `buf.pushLE(x)` appends an integer's little-endian bytes at its width (u8 … u128,
431
+ i8 … i128; a literal needs one: `buf.pushLE<u16>(1n)` or `buf.pushLE(u16(1n))`), `buf.pushKey(key)` a Pubkey's 32
432
+ bytes, `buf.pushBorsh(value)` a value's Borsh encoding with the codecs `invoke`, events and `storeBorsh` use (a
433
+ struct, or an object literal given its type, `buf.pushBorsh<Header>({ … })`; a data enum, its tag then the variant's
434
+ fields; a FixedArray; a list, its u32 count then the elements; integers, booleans, Pubkeys, strings and Options; a
435
+ data-enum literal of a fixed-size variant costs what the same bytes cost with `pushLE`: its fields evaluated in
436
+ order, then one room check and a store of each),
437
+ `buf.setLE(offset, x)` (or `setLE<u16>(offset, x)`) overwrites bytes within the length, as Rust's
438
+ `data[a..b].copy_from_slice(…)`, and `buf.truncate(n)` keeps the first `n`. Past the room (or, for `setLE` and
439
+ `truncate`, past the length) fails with 5104 and the length does not move. Phoenix's event recorder, which the test
440
+ checks byte for byte against the Phoenix binary's batches:
441
+
442
+ ```ts
443
+ const data: FixedVec<u8, 1280> = fixedVec([15n]); // PhoenixInstruction::Log
444
+ data.pushBorsh<PhoenixMarketEvent>({ kind: "Header", instruction, sequenceNumber, timestamp: now(), slot: currentSlot(), market, signer, totalEvents: 0n });
445
+ // … for each event, the batch sent first if it would not fit: data.pushBorsh<PhoenixMarketEvent>({ kind: "Fill", index, … });
446
+ data.setLE(91n, u16(batchSize)); // total_events of this batch
447
+ invokeInstruction(programId(), metas, data, rest, ["log", bump]);
448
+ data.truncate(93n); // back to the header
449
+ ```
450
+ - Return data as the original sets it: `setReturnData(bytes)` is `set_return_data(&bytes)`, the bytes as they are, from
451
+ the `@fallback` entry, a helper or a void instruction (Phoenix's Borsh `Vec<FIFOOrderId>` of the orders that rested,
452
+ built in a local `FixedVec<u8, N>`). `bytes` is a list of u8: a local FixedVec, a Vec or FixedVec in account data, or
453
+ the instruction data or a slice of it. The last call wins and an empty list clears it; a CPI made afterwards replaces
454
+ 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
455
+ runtime refuses it ("Return data too large (1025 > 1024)"). An instruction that returns a value cannot call it (a
456
+ compile error: its return value is its return data); a helper it calls may, and the instruction's return value, set
457
+ last, replaces what the helper set.
327
458
 
328
459
  ## Not supported yet
329
460
 
@@ -140,6 +140,7 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
140
140
  | a closure `\|x\| x + offset`, `let fee = \|x: u64\| x / 100;` | `const f = (x: u64): u64 => x + offset` (it may read and write the function's variables), `const fee = (x: u64): u64 => x / 100n;` |
141
141
  | `x.unwrap_or(d)` | `x ?? d` |
142
142
  | `fn max<T: PartialOrd>(a: T, b: T) -> T` | `function max<T extends bigint>(a: T, b: T): T` (one copy per type used) |
143
+ | `fn add_event(rec: &mut EventRecorder, e: &Event)` | `function addEvent(rec: Inout<EventRecorder>, e: Event): void` (structs, FixedArray and FixedVec; a `&mut u64` becomes a returned value or a struct field) |
143
144
 
144
145
  ## Tooling
145
146
 
package/docs/runtime.md CHANGED
@@ -34,7 +34,7 @@ In file order:
34
34
  | Well-known program ids | System, Token, Token-2022, ATA, Metaplex and the other programs the language names |
35
35
  | Strings | `TS_Str` views (pointer, length), UTF-8 validation, comparison, `FixedString<N>` storage |
36
36
  | Entry point input | `TsAccount` (the loader's serialized account, read in place), `TsParams`, `ts_deserialize` |
37
- | Account checks | owner, discriminator, signer, writable, executable, address, size, uniqueness (`ts_check_*`), growable Vec lengths |
37
+ | Account checks | owner, discriminator, signer, writable, executable, address, size, uniqueness (`ts_check_*`), growable Vec lengths; `ts_owned`, the native views' owner check with its one-account cache (`TS_OWNER_CACHE`, forgotten at every CPI and owner write by `TS_OWNER_FORGET`) |
38
38
  | Little-endian IO | `ts_read_le` and friends for argument decoding and Borsh |
39
39
  | Sysvars | clock, rent (`ts_rent`, `ts_minimum_balance_of`, `ts_minimum_balance`), program data |
40
40
  | PDA | `ts_pda_hash`, `ts_create_pda_address`, `ts_find_pda` (canonical bump), `ts_require_pda` |
package/docs/stability.md CHANGED
@@ -40,13 +40,33 @@ Useful today, but may still change before 1.0 (each change listed in the CHANGEL
40
40
  `createProgramAddress`.
41
41
  - `loadBorsh` / `storeBorsh` (0.42.0): a native program's Borsh accounts read into a local struct and written back.
42
42
  - `BigVec<T>` (0.42.0): SPL's `big_vec`, a list over the rest of a native account.
43
+ - Views at run-time offsets (0.43.0): `loadRawAt` / `loadRawMutAt`, `rawArrayAt` / `rawArrayMutAt`; a read-only
44
+ view read where it is made (`loadRaw<T>(a).field`, `rbTreeAt(…).length`), and the owner check's cache the views share.
45
+ - The built-in RedBlackTree (0.43.0): `rbTreeAt` / `rbTreeMutAt`, lib-sokoban 0.3's byte layout and algorithms,
46
+ its panics in solana-program 1.14–1.17's format, `removeAt(index)` (what it gives for a node in no tree may change).
43
47
  - `panic(null, location)` (no log line) and `abort()` (Rust's abort, "SBF program panicked") (0.42.0).
48
+ - Failures without a log line (0.43.0): `ERROR_LOG_PREFIX = null` / `PROGRAM_ERROR_LOG_PREFIX = null`.
49
+ - `findProgramAddressWithBump` (0.43.0), with `const [address, bump] = …` its only array destructuring.
50
+ - Plain type aliases (0.43.0): `type Price = u64`, replaced by the type they name.
51
+ - File-local structs (0.43.0): `interface Pair { … }` without `export`, for helpers and locals, out of the IDL.
52
+ - Constant expressions (0.43.0): top-level integer constants folded from literals and earlier constants, a typed
53
+ one computed in its type.
54
+ - Comma-separated `for` updates and initializers (0.43.0).
55
+ - Stack room (0.43.0): `/** @noinline */` helpers and `/** @heap */` locals.
44
56
  - Local `FixedVec` / `FixedArray` lists of structs, `FixedVec.pushAll`, the instruction data as a list (`slice`,
45
- `InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0).
57
+ `InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0); local FixedVecs given for read-only
58
+ `FixedVec<T, N>` / `Vec<T>` helper parameters (0.43.0).
46
59
  - `epochRewards()` and `EpochRewards` (0.42.0): the EpochRewards sysvar through its syscall.
47
60
  - `NATIVE_ACCOUNT_WRITES` (0.42.0): opt-in native write semantics for `loadRawMut`, `storeBorsh` and BigVec writes
48
61
  (writability and aliasing left to the runtime). It drops checks a program would otherwise get, so it stays outside
49
62
  "the checks stay" promise above: it only applies to programs that declare it.
63
+ - `Inout<T>` helper parameters (0.43.0): a helper that changes a struct, FixedArray or FixedVec of the caller's
64
+ that is not an account (a local, a `loadBorsh` local, a field of a `loadRawMut` view, a list element), with the
65
+ aliasing rules at each call. It settles the open edge of helpers taking a writable struct that is not an account,
66
+ which were refused; the rules (what counts as overlapping, which places may move) may still be refined.
67
+ - For native ports (0.43.0): `setReturnData` and `logComputeUnits` in a native entry; `closeRaw`, `assignOwner`
68
+ and `resizeAccount` on remaining accounts; the byte builders of `FixedVec<u8, N>` (`pushLE`, `pushKey`, `pushBorsh`,
69
+ `setLE`, `truncate`); `PANIC_STYLE = "solana-1.14"` and `panicsAt(location, expression)`.
50
70
  - Metaplex CPIs (Token Metadata, Core, Bubblegum), oracles (Pyth, Switchboard), the Stake program.
51
71
  - `programAt<P>` / `sysvarAt<S>` and remaining accounts in the typed CPIs (System, Token, ATA, Memo, Stake); a ternary
52
72
  between remaining accounts and `AccountInfo` parameters (0.42.0).
@@ -61,7 +81,6 @@ Useful today, but may still change before 1.0 (each change listed in the CHANGEL
61
81
  - **An external audit** of the compiler and runtime ([audit package](audit.md)), its findings fixed and published.
62
82
  - **Settle the open edges**, each either supported or refused with a clear error:
63
83
  - a struct holding a FixedVec as both an argument and account data (two layouts, one IDL type);
64
- - helpers that take a writable struct which is not an account (a `loadRaw` view, a local), now refused;
65
84
  - `require` with an error code computed at run time that is 0: fails as an overflow (5100) today, where a native
66
85
  program returns CUSTOM_ZERO;
67
86
  - which experimental parts above become stable, and which stay outside the 1.0 promise.
@@ -37,6 +37,9 @@ uses. Publishing works on mainnet-beta. The error shows the failing transaction'
37
37
  SBPF v0 (the default) every function gets a fixed 4 KiB stack frame, and going past it corrupts memory, so the build
38
38
  refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`) grow frames dynamically, so this limit does not apply there. Large structs and arrays copied into typed
39
39
  locals (`const q: Big = acct.big`) are the usual cause: bind them without a type (`const q = acct.big`, a reference
40
- into the account data) or move the work into helpers. Helpers are often inlined into their instruction, so their
41
- locals count toward its frame.
40
+ into the account data). The message lists the biggest locals (clang's frame layout: a local's name and the source
41
+ line near it; the locals of an inlined helper show as unnamed, with the helpers' locals that may be them). Helpers are
42
+ often inlined into their instruction, so their locals count toward its frame: mark one `/** @noinline */` to give it a
43
+ 4 KiB frame of its own (a few compute units per call), or declare a large local list or struct of an instruction
44
+ `/** @heap */` to keep it on the heap (about 18 CU for the allocation).
42
45