@typesol/cli 0.37.0 → 0.39.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 (52) hide show
  1. package/CHANGELOG.md +352 -1
  2. package/README.md +31 -14
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +7 -6
  5. package/dist/compiler/analyze.js +350 -38
  6. package/dist/compiler/emit/alias.js +3 -2
  7. package/dist/compiler/emit/base.d.ts +5 -0
  8. package/dist/compiler/emit/base.js +2 -0
  9. package/dist/compiler/emit/borsh.js +63 -2
  10. package/dist/compiler/emit/calls.d.ts +9 -1
  11. package/dist/compiler/emit/calls.js +147 -18
  12. package/dist/compiler/emit/cpi-core.js +21 -6
  13. package/dist/compiler/emit/cpi.js +81 -27
  14. package/dist/compiler/emit/create.d.ts +7 -0
  15. package/dist/compiler/emit/create.js +27 -0
  16. package/dist/compiler/emit/expressions.js +7 -4
  17. package/dist/compiler/emit/function.d.ts +7 -0
  18. package/dist/compiler/emit/function.js +168 -30
  19. package/dist/compiler/emit/program.js +15 -2
  20. package/dist/compiler/emit/shared.d.ts +5 -5
  21. package/dist/compiler/emit/shared.js +5 -0
  22. package/dist/compiler/emit/statements.d.ts +8 -0
  23. package/dist/compiler/emit/statements.js +93 -6
  24. package/dist/compiler/emit/storage.d.ts +10 -1
  25. package/dist/compiler/emit/storage.js +50 -11
  26. package/dist/compiler/idl.d.ts +2 -2
  27. package/dist/compiler/idl.js +48 -13
  28. package/dist/compiler/model.d.ts +47 -10
  29. package/dist/compiler/model.js +14 -4
  30. package/dist/testing.js +8 -0
  31. package/dist/tools/clientgen.js +10 -1
  32. package/dist/tools/portgen.d.ts +6 -0
  33. package/dist/tools/portgen.js +68 -17
  34. package/docs/architecture.md +5 -4
  35. package/docs/audit.md +31 -19
  36. package/docs/case-study-escrow.md +5 -5
  37. package/docs/case-study-jito-mev.md +171 -0
  38. package/docs/case-study-marginfi.md +797 -0
  39. package/docs/case-study-multisig.md +3 -3
  40. package/docs/case-study-raydium-clmm.md +151 -101
  41. package/docs/case-study-raydium-cp-swap.md +3 -3
  42. package/docs/cli.md +5 -5
  43. package/docs/client.md +1 -1
  44. package/docs/errors.md +15 -4
  45. package/docs/language.md +39 -26
  46. package/docs/migrate-from-anchor.md +4 -1
  47. package/docs/runtime.md +1 -1
  48. package/docs/security-model.md +2 -1
  49. package/docs/testing.md +33 -1
  50. package/lib/typesol.d.ts +48 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
package/docs/language.md CHANGED
@@ -11,48 +11,52 @@ The full reference. For a tour, start with the [README](../README.md).
11
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). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
12
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
13
  | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
14
- | Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+; `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). See [errors.md](errors.md) |
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
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
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
- | Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack |
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 |
19
19
  | 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 |
20
20
  | 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 |
21
21
  | 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 |
22
22
  | 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` |
23
23
  | Pubkey constants | `const ADMIN = pubkey("4Nd1…")` (checked at compile time) or inline `pubkey("…")`; usable as seeds |
24
- | 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) and `Vec<T>` (Borsh: from a Vec argument or a list in account data) |
24
+ | 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 |
25
25
  | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
26
26
  | 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 |
27
27
  | Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
28
28
  | 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 |
29
+ | 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 |
30
+ | 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 |
31
+ | 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 |
32
+ | 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 |
29
33
  | 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); `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) |
30
- | 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`) |
34
+ | 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) |
31
35
  | 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 |
32
- | 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>`); 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) |
36
+ | 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) |
33
37
  | Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
34
38
  | 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 |
35
- | 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) |
39
+ | 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 |
36
40
  | Ternaries | `const fee = vip ? 0n : 30n` — only the chosen branch runs |
37
41
  | Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL) |
38
42
  | 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 |
39
- | Option of structs | `home: Option<Point>` in account data — `=== null`, `p.home.x` after narrowing, `p.home = null` / `{ x, y }` |
43
+ | 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) |
40
44
  | Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58) — 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 |
41
45
  | `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
42
- | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash`; `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 as Rust does (-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) |
46
+ | 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) |
43
47
  | 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">`) |
44
48
  | 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 |
45
49
  | 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 |
46
50
  | 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 |
47
- | Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds` 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`); 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) |
51
+ | 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`); 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) |
48
52
  | 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)`) |
49
53
  | 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) |
50
54
  | List callbacks | on a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument: `forEach`, `some`, `every`, `find` (an Option of the element; scalar elements), `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 |
51
55
  | 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) |
52
56
  | 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()`) |
53
57
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
54
- | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (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()`; `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
55
- | 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) |
58
+ | 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()`; `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
59
+ | 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) |
56
60
  | 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) |
57
61
  | 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) |
58
62
  | Heap | 32 KiB by default; `const HEAP_SIZE_KIB = 64n` (32–256) lets the program use more, when clients add ComputeBudget `requestHeapFrame` |
@@ -65,21 +69,21 @@ The full reference. For a tour, start with the [README](../README.md).
65
69
  | Parameter type | Checked before your code runs |
66
70
  | --- | --- |
67
71
  | `Signer` / `Mut<Signer>` | signed (and writable) |
68
- | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable) |
69
- | `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) |
72
+ | `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 |
73
+ | `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 |
70
74
  | `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 |
71
75
  | `/** @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 |
72
76
  | 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 |
73
- | `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), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
74
- | `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`); `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 |
77
+ | `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) |
78
+ | `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 |
75
79
  | `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>` |
76
80
  | `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) |
77
- | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
81
+ | `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) |
78
82
  | `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 |
79
83
  | `Address<A, "4Nd1…">` | exact address (2012; `address` in the IDL) |
80
- | `Owner<A, "Tokenkeg…">`, `Executable<A>` | owner program (2004), executable (2007) |
84
+ | `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 |
81
85
  | `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) |
82
- | `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; `x !== null` before use, or `x!` / `x!.field` to assert it was passed (5115 otherwise); `optional` in the IDL |
86
+ | `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 |
83
87
  | `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` |
84
88
  | `EventAuthority`, `SelfProgram` | Anchor's `["__event_authority"]` PDA, and this program's own address, for `emitCpi` |
85
89
  | `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 { … }` |
@@ -87,7 +91,7 @@ The full reference. For a tour, start with the [README](../README.md).
87
91
  | `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 |
88
92
  | `Init<Mint>`, `InitIfNeeded<Mint>` | Anchor `init` / `init_if_needed` with `mint::decimals` / `mint::authority` / `mint::freeze_authority`: `const bump = mint.create(payer, ["mint", payer.key], 6n, authority, freezeAuthority \| null)` creates the mint at that PDA of this program, or with `null` seeds as a new keypair account that signs (3010 if it did not), under the instruction's token program (its only token program parameter, or one passed as the last argument of `create` / `createIfNeeded`; plus `SystemProgram`). Token-2022 extensions (Anchor's `extensions::…`) go after the freeze authority: `mint.create(payer, null, 6n, authority, null, { metadataPointer: { authority, metadataAddress: mint.key }, transferHook: { authority, programId }, closeAuthority, permanentDelegate, nonTransferable: true, defaultAccountState: true, interestBearing: { rateAuthority, rate }, transferFee: { configAuthority, withdrawAuthority, basisPoints, maximumFee }, groupPointer, groupMemberPointer })` sizes the mint for them and initializes each before InitializeMint2. With `createIfNeeded` an existing mint must carry groupPointer / groupMemberPointer / metadataPointer / closeAuthority / permanentDelegate / transferHook with those keys (Anchor's 2024–2039); extensions not listed are not looked at, so an existing mint may carry others (a permanent delegate, say). `createIfNeeded(…)` returns whether it created it; an existing one must be that PDA and have those decimals and authorities (2018 / 2016 / 2017) |
89
93
  | `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) |
90
- | `TokenAccount` / `Mut<TokenAccount>` | owned by SPL Token or Token-2022 (extensions allowed, multisig accounts refused), initialized; `mint`, `owner`, `amount`, `delegate`, `delegatedAmount`, `isFrozen`, `isNative`, `closeAuthority`, `tokenProgram` |
94
+ | `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` |
91
95
  | `Mint` / `Mut<Mint>` | owned by SPL Token or Token-2022, initialized; `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
92
96
  | `SystemProgram`, `TokenProgram`, `Token2022Program` | exact program address |
93
97
  | `TokenInterface` | either token program |
@@ -95,7 +99,7 @@ The full reference. For a tour, start with the [README](../README.md).
95
99
  | `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
96
100
  | `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)` |
97
101
  | `StakeProgram` | `initialize(stake, rentSysvar, staker, withdrawer)` (no lockup), `authorize(stake, clockSysvar, authority, newAuthority, "staker" \| "withdrawer")`, `delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker)`, `deactivate(stake, clockSysvar, staker)`, `withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports)`; the sysvar and config accounts are parameters, as in anchor-spl's stake module; authorities sign (PDAs with signerSeeds) |
98
- | `InstructionsSysvar`, `PythPriceUpdate`, `SwitchboardFeed` | exact address / owner program + discriminator |
102
+ | `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) |
99
103
  | `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 |
100
104
  | `Program<"Address…">` | exact program address + executable |
101
105
  | `UncheckedProgram` | executable only — check `.key` yourself |
@@ -106,9 +110,9 @@ Every account exposes `key`, `lamports`, `dataLen`, `isSigner`, `isWritable`. At
106
110
 
107
111
  Two writable parameters can never be the same account: aliasing is refused with error 2040 (also when a remaining
108
112
  account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
109
- (Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed,
110
- a close destination or `@layout borsh`): a write through either is seen through the other, so read what you need
111
- before writing. A remaining account
113
+ (Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed
114
+ or `@layout borsh`; a close destination may be one, the rent reaching it through either): a write through either is
115
+ seen through the other, so read what you need before writing. A remaining account
112
116
  can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
113
117
  with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
114
118
  `AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
@@ -118,7 +122,11 @@ of a position, as Raydium CLMM's tick arrays).
118
122
 
119
123
  - `systemProgram.transfer(from, to, lamports, signerSeeds?)` (`from` is a `Mut<Signer>`, or a system-owned PDA of this
120
124
  program, a SOL vault, with its seeds), `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
121
- (the new account signs: a keypair `Mut<Signer>` or this program's PDA), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
125
+ (the new account signs: a keypair `Mut<Signer>` or this program's PDA), `systemProgram.createPda(payer, account, space,
126
+ owner, seeds)` (Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: a `Mut<AccountInfo>`
127
+ that must be this program's PDA for `seeds` (2006), created owned by `owner`, or topped up, allocated and assigned when
128
+ someone funded the address first; returns the bump, records the PDA in the IDL, and among the creates a body starts
129
+ with runs before the constraints), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
122
130
  - Token programs (`TokenProgram`, `Token2022Program`, `TokenInterface`) — pass `signerSeeds` (with the bump) when the authority is a PDA:
123
131
  `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),
124
132
  `approve(source, delegate, owner, amount)`, `revoke`, the checked forms `mintToChecked(mint, to, authority, amount)`,
@@ -157,8 +165,13 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
157
165
  }
158
166
  ```
159
167
 
168
+ - program: a `Program<"address">` (key and executable checked on entry), an `UncheckedProgram`, an
169
+ `Address<AccountInfo, "address">` (Anchor's `#[account(address = ID)]` on an `UncheckedAccount`: only the key is
170
+ checked, 2012), the system or a token program, or a remaining account.
160
171
  - accounts: `readonly(x)`, `writable(x)`, `readonlySigner(x)`, `writableSigner(x)`. The compiler refuses `writable` on a
161
- non-`Mut` parameter and a signer flag on an account that neither signed nor is covered by `signerSeeds`.
172
+ non-`Mut` parameter and a signer flag on an account that neither signed nor is covered by `signerSeeds`. An optional
173
+ account passed as it is (`readonly(x)` / `writable(x)` with `x: A | null`, no `!`) is left out of the list when it
174
+ was not passed, as Rust's `if let Some(x) = &self.x { accounts.push(…) }` does.
162
175
  - data (Borsh): integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
163
176
  Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
164
177
  `sighash("name")` (Anchor discriminator), `hex("0a0b")`. Up to 1024 bytes.
@@ -185,7 +198,7 @@ invokeInstruction(transaction.programId, transaction.accounts, transaction.data,
185
198
  - every account in the fourth argument (`remainingAccounts()` or a slice) is handed to the runtime, which finds each
186
199
  meta's account there by key: one that is missing fails the call, as under Rust.
187
200
  - the runtime checks the privileges: a meta may be a signer or writable only as the transaction passed that account,
188
- or as a PDA of this program the seeds (fifth argument) sign for. See `examples/multisig.ts`.
201
+ or as a PDA of this program the seeds (fifth argument) sign for. See `showcase/mainnet/multisig/multisig.ts`.
189
202
 
190
203
  Typed calls from an IDL: `typesol cpi other.json --out other_cpi.ts` writes one helper per instruction
191
204
  (`vaultDeposit(program, owner, vault, systemProgram, amount, seeds)`), with the account flags, discriminator and
@@ -101,7 +101,10 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
101
101
  | --- | --- |
102
102
  | `pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()>` | `export function deposit(owner: Mut<Signer>, vault: Mut<Vault>, …, amount: u64): void` |
103
103
  | `-> Result<u64>` / a struct | `: u64` / a struct: sent as return data, listed in the IDL |
104
- | `#[error_code] enum MyError { #[msg("…")] X }` | `export enum MyError { X = "…" }` (codes from 6000, in order) |
104
+ | `#[error_code] enum MyError { #[msg("…")] X }` | `export enum MyError { X = "…" }` (codes from 6000, in order; `X = ""` for a variant without `#[msg]`; `/** @code 6200 */` before a member for Anchor's `Y = 200`) |
105
+ | `f64` fields (events) | `f64`, made from the bits the program computed (`f64FromBits`) |
106
+ | `Option<[T; N]>`, structs of Options inside Options (`BankConfigOpt`) | `Option<FixedArray<T, N>>`; a struct argument holding Options is Borsh as Anchor sends it; an event holding one is `/** @layout borsh */` (`typesol port` writes it so) |
107
+ | `#[account(zero_copy)]`, `#[repr(C)]` types with `_pad` fields and `WrappedI80F48` | a fixed-layout struct with `/** @serialization bytemuck */` and `/** @repr c */`, `/** @idlName _pad0 */` on the padding, `/** @bytes */ value: i128` for the wrapped number ([language.md](language.md)) |
105
108
  | `require!(c, MyError::X)`, `err!(MyError::X)` | `require(c, MyError.X)`, `require(false, MyError.X)` |
106
109
  | `require_keys_eq!(a, b)`, `err!(ErrorCode::AccountDidNotDeserialize)` (Anchor's own codes) | `require(a === b, AnchorError.RequireKeysEqViolated)` (or your own error), `require(false, AnchorError.AccountDidNotDeserialize)` |
107
110
  | `init_if_needed` + `extensions::…` on a mint | `mint.createIfNeeded(…, { metadataPointer: {…}, … })`: an existing mint is checked as Anchor checks it (2024–2039) |
package/docs/runtime.md CHANGED
@@ -51,7 +51,7 @@ In file order:
51
51
  ## Changing it
52
52
 
53
53
  - Every runtime change can move compute units or binary size. Measure it before and after with
54
- [typesol/benchmarks](https://github.com/typesol/benchmarks) pointed at your checkout, and put the difference in
54
+ [typesol-lang/benchmarks](https://github.com/typesol-lang/benchmarks) pointed at your checkout, and put the difference in
55
55
  the pull request (see CONTRIBUTING).
56
56
  - A change that alters behavior (a result, an error code, a log line, account bytes) is a language change and goes
57
57
  in the CHANGELOG as one. One that only changes cost says so: "same results".
@@ -106,4 +106,5 @@ Each holds for every instruction of every program the compiler accepts. A break
106
106
  ## Status
107
107
 
108
108
  The compiler and runtime have had internal security reviews; the findings of the latest are fixed in 0.25.0
109
- (CHANGELOG). There has been no external audit yet: see [audit.md](audit.md).
109
+ (CHANGELOG). The releases after it have not had such a review yet, and there has been no external audit: see
110
+ [audit.md](audit.md).
package/docs/testing.md CHANGED
@@ -6,10 +6,42 @@ run prints its seed; reproduce with `FUZZ_SEED=<n>`, widen with `FUZZ_RUNS` / `F
6
6
  | Check | Oracle | What must hold |
7
7
  | --- | --- | --- |
8
8
  | `test/verification/fuzz-arith.test.ts` | BigInt | `+ - * / % **`, `& \| ^ << >> ~`, unary minus, comparisons and casts at every width u8…u128 / i8…i128, plus `mulDiv`, `mulDivCeil`, `isqrt`, `min`, `max`, return the same value or abort with the same code (5100/5101/4102), for edge and random inputs |
9
+ | `test/verification/fuzz-u256.test.ts` | BigInt | every `u256` operator, `mulDiv` / `mulDivCeil` with their 512-bit product, comparisons and the checked narrowing casts, on random values: the same value or the same error (5100, 5101, 4102) |
10
+ | `showcase/test/fuzz-i80f48.test.ts` | vectors the `fixed` crate (1.28.0) wrote, from `showcase/test/fixtures/marginfi/i80f48-oracle` | Marginfi's I80F48 (`showcase/mainnet/marginfi/i80f48.ts`): a BigInt model must give every vector, then the port must give the model's answer on them and on random values (products toward −∞, quotients toward zero, f64 to nearest-even) |
9
11
  | `test/verification/fuzz-state.test.ts` | TypeScript state model | random honest + hostile actions on vault and escrow: every outcome as predicted, balances equal the model, SOL conserved up to fees, token supply exactly conserved; random filings/decisions/resets on ledgerbook: Vec contents, account size and rent exemption equal the model |
10
12
  | `test/verification/fuzz-layout.test.ts` | TypeScript model | random pushes, pops, sets, in-place additions, moves and clears on an account with two growable Vecs (honest, out of range and by a stranger): the decoded account equals the model after every step; random `loadAccountMut` index pairs over remaining-account lists that repeat accounts: every alias refused (2040), balances conserved |
13
+ | `showcase/test/fuzz-jito.test.ts` | Jito's tip payment, tip distribution and priority fee distribution as deployed on mainnet | random sequences of tips, receiver and builder changes, accounts opened over epochs, roots uploaded, Merkle claims (wrong amounts, proofs and signers among them), closes and config changes, with at most one injected fault per transaction: the same outcome, account bytes, events and log lines as the original after every step; keys, amounts and choices all come from the seed |
14
+ | `showcase/test/fuzz-marginfi.test.ts` | Marginfi v2 as deployed on mainnet | random sequences of bank creation (random weights, curves and fees, most valid, some broken one way), configuration (operational states, curves, liquidation fees, the circuit breaker's switch and settings, frozen banks), accruals over balances written into both at every scale and clock jumps up to a year, limits, pauses, wrong signers: the same outcome, account bytes and events as the original after every step; inputs the original panics on (a negative fee rate) must fail in the port too |
15
+ | the `fuzz:` case of `showcase/test/raydium-clmm.test.ts` | Raydium CLMM as deployed on mainnet | random swaps (both ways, exact in and out, price limits, thresholds), positions opened at random ranges, and liquidity added and taken out (over the position's own, under slippage limits): the same outcome, account bytes and events as the original after every step; choices and amounts come from the seed (`CLMM_FUZZ_STEPS` lengthens it), keys are fresh each run; each transaction may use 1.4M compute units, so a swap the original needs more than 200,000 for still runs to its end |
11
16
  | `test/verification/differential.test.ts` | Anchor twins in `test/anchor-twins` | identical transactions to TypeSOL and Anchor programs: same outcomes, same account contents, same wallet and token balances after every step |
12
- | `test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `test/ports/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([test/ports/README.md](https://github.com/typesol/typesol/blob/main/test/ports/README.md)) |
17
+ | `showcase/test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `showcase/program-examples/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([showcase/program-examples/README.md](https://github.com/typesol-lang/typesol/blob/main/showcase/program-examples/README.md)) |
13
18
 
14
19
  Compute-unit and binary-size comparisons with Anchor, native Rust and Pinocchio are in the README
15
20
  ([Numbers](../README.md#numbers)).
21
+
22
+ ## Reproducing a release
23
+
24
+ From the release after 0.38.0 on, each release's GitHub Release carries `manifest.json` (written by
25
+ `scripts/release-manifest.ts` from the published package and the tag's sources; the scripts need Node 22.18 or later):
26
+
27
+ - the compiler and toolchain versions (clang, platform-tools, Node, TypeScript, the runtime header's sha256);
28
+ - the sha256 of the SBF binary, IDL and C that every program under `examples/` and `showcase/program-examples/` builds to;
29
+ - the sha256 of the reference binaries the differential tests run against (`test/programs/`);
30
+ - a hash of the test corpus.
31
+
32
+ It also carries the previous release's sources built by the previous package and by this one, and their diff
33
+ (`binary-diff.txt`). That is the check behind a changelog line such as "programs that use none of these compile to the
34
+ same binaries". To redo it, or to compare other versions:
35
+
36
+ ```sh
37
+ git worktree add ../typesol-prev v0.37.0 # the sources to build
38
+ npm install --prefix /tmp/a @typesol/cli@0.37.0
39
+ npm install --prefix /tmp/b @typesol/cli@0.38.0
40
+ node scripts/release-manifest.ts --compiler /tmp/a/node_modules/@typesol/cli --sources ../typesol-prev --out a.json
41
+ node scripts/release-manifest.ts --compiler /tmp/b/node_modules/@typesol/cli --sources ../typesol-prev --out b.json
42
+ node scripts/release-manifest.ts --diff a.json b.json
43
+ ```
44
+
45
+ For 0.37.0 → 0.38.0 (run by hand before the manifest job existed): all 67 programs of the 0.37.0 sources build to
46
+ the same binary and IDL with both packages.
47
+
package/lib/typesol.d.ts CHANGED
@@ -177,8 +177,10 @@ export declare function remainingAccounts(): RemainingAccounts;
177
177
  * Read a struct of this program from a remaining account or an `AccountInfo` parameter (Anchor's
178
178
  * `AccountLoader::try_from` on an `UncheckedAccount`): owner, discriminator and size are checked.
179
179
  * `loadAccountMut` also requires it to be writable, not aliased by another writable account, and not already loaded
180
- * with `loadAccountMut` in this instruction (2040). The result is also the account (`.key`, `.lamports`), and passes
181
- * to a helper that takes `Account<T>` / `Mut<T>`.
180
+ * with `loadAccountMut` in this instruction (2040). A `const` view declared in a loop body ends with its iteration,
181
+ * so a later iteration may load the account again; `loadAccountMut<Dup<T>>` there also lets a remaining account be
182
+ * passed more than once (a route back through one pool), one view at a time. The result is also the account (`.key`,
183
+ * `.lamports`), and passes to a helper that takes `Account<T>` / `Mut<T>`.
182
184
  */
183
185
  export declare function loadAccount<T>(account: RemainingAccount | AccountInfo): Account<T>;
184
186
  export declare function loadAccountMut<T>(account: RemainingAccount | AccountInfo): Mut<T>;
@@ -187,6 +189,8 @@ export declare function loadAccountMut<T>(account: RemainingAccount | AccountInf
187
189
  export interface Hash {
188
190
  readonly __hash: unique symbol;
189
191
  equals(other: Hash): boolean;
192
+ /** The order of the 32 bytes (lexicographic): -1, 0 or 1, as Rust compares `[u8; 32]`. */
193
+ compare(other: Hash): i64;
190
194
  }
191
195
 
192
196
  /** sha256 over the parts concatenated: strings (UTF-8), Pubkeys/Hashes (32 bytes), integers (LE), booleans (1 byte). */
@@ -653,6 +657,12 @@ export declare const AuthorityType: {
653
657
  * the struct size. Accounts ending in a Vec size themselves through push/pop/clear.
654
658
  */
655
659
  export declare function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void;
660
+ /**
661
+ * Resize a `Mut<AccountInfo>` of this program to `newSize` bytes (Rust's `AccountInfo::resize`): the data length only,
662
+ * the new bytes zeroed. No rent moves: fund the account first (`rentExempt(newSize)`), the runtime refuses an account
663
+ * left short. At most 10 KiB past its size when the instruction started (3016).
664
+ */
665
+ export declare function resizeAccount(account: Mut<AccountInfo>, newSize: u64): void;
656
666
 
657
667
  /**
658
668
  * Token-2022 extensions of a mint (any account works; legacy SPL Token mints have none).
@@ -723,8 +733,8 @@ export type Account<T> = Readonly<T> & AccountMeta;
723
733
  */
724
734
  export type Mut<T, E = never> = T & AccountMeta;
725
735
 
726
- /** A PDA seed: a string, a Pubkey, an integer (at its width) or a unit enum value (one byte). */
727
- export type Seed = string | Pubkey | bigint | number;
736
+ /** A PDA seed: a string, a Pubkey, a Hash (its 32 bytes), an integer (at its width) or a unit enum value (one byte). */
737
+ export type Seed = string | Pubkey | Hash | bigint | number;
728
738
 
729
739
  /**
730
740
  * The seeds (with the bump) of one PDA signature, for helpers that sign CPIs: declare a `seeds: SignerSeeds`
@@ -829,7 +839,7 @@ export type MintOf<A, AuthorityParam extends string, FreezeAuthorityParam extend
829
839
  /**
830
840
  * Anchor's `dup`: this writable account may be the same account as another writable parameter (TypeSOL refuses that
831
841
  * otherwise, 2040). Both are read and written in place, so a write through one is seen through the other: read
832
- * what you need before writing. Not for accounts that are created, closed, a close destination or `@layout borsh`.
842
+ * what you need before writing. Not for accounts that are created, closed or `@layout borsh` (a close destination may be one: it receives the rent through either).
833
843
  */
834
844
  export type Dup<A> = A & { readonly __dup?: true };
835
845
  /**
@@ -1514,6 +1524,8 @@ export interface CompressedLeaf {
1514
1524
  /** The current slot and epoch (Clock sysvar). */
1515
1525
  export declare function currentSlot(): u64;
1516
1526
  export declare function currentEpoch(): u64;
1527
+ /** The Unix time the current epoch started at (Clock.epoch_start_timestamp). */
1528
+ export declare function epochStartTimestamp(): i64;
1517
1529
  /** The EpochSchedule sysvar: slots per epoch (after warmup), whether epochs warm up, and where normal epochs start. */
1518
1530
  export declare function slotsPerEpoch(): u64;
1519
1531
  export declare function epochWarmup(): boolean;
@@ -1630,6 +1642,13 @@ export interface SystemProgram extends AccountMeta {
1630
1642
  * `Mut<Signer>` keypair, or a PDA of this program when you pass its `signerSeeds` (with the bump).
1631
1643
  */
1632
1644
  createAccount(payer: Mut<Signer>, account: AccountMeta, lamports: u64, space: u64, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
1645
+ /**
1646
+ * Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: `account` must be the PDA of this
1647
+ * program for `seeds` (no bump; 2006 otherwise); it is created with `space` bytes owned by `owner`, or, when someone
1648
+ * already funded the address, topped up to rent, allocated and assigned. Returns the bump. Among the creates a body
1649
+ * starts with, it runs before the other accounts' constraints, as Anchor's `init` does.
1650
+ */
1651
+ createPda(payer: Mut<Signer>, account: Mut<AccountInfo>, space: u64, owner: Pubkey, seeds: Seed[]): u8;
1633
1652
  /** System Allocate: give `account` `space` bytes of data. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
1634
1653
  allocate(account: AccountMeta, space: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1635
1654
  /** System Assign: make `owner` the account's owner. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
@@ -1818,9 +1837,13 @@ export interface UncheckedProgram extends AccountMeta {
1818
1837
  export interface CpiAccount {
1819
1838
  readonly __cpi_account: void;
1820
1839
  }
1821
- export declare function readonly(account: AccountMeta | RemainingAccount): CpiAccount;
1840
+ /**
1841
+ * An optional account (`A | null`) passed as it is, without `!`: left out of the CPI's list when it was not passed
1842
+ * (Rust's `if let Some(a) = &self.a { accounts.push(a) }`, as for `with_remaining_accounts`).
1843
+ */
1844
+ export declare function readonly(account: AccountMeta | RemainingAccount | null): CpiAccount;
1822
1845
  export declare function readonly(accounts: RemainingAccounts | RemainingSlice): Iterable<CpiAccount>;
1823
- export declare function writable(account: AccountMeta | RemainingAccount): CpiAccount;
1846
+ export declare function writable(account: AccountMeta | RemainingAccount | null): CpiAccount;
1824
1847
  export declare function writable(accounts: RemainingAccounts | RemainingSlice): Iterable<CpiAccount>;
1825
1848
  export declare function readonlySigner(account: AccountMeta | RemainingAccount): CpiAccount;
1826
1849
  export declare function writableSigner(account: AccountMeta | RemainingAccount): CpiAccount;
@@ -1966,9 +1989,11 @@ export declare enum AnchorError {
1966
1989
  /**
1967
1990
  * Abort with the given error unless `condition` holds. The error is a member of an exported string enum, any
1968
1991
  * `AnchorError` member, or a string literal: each distinct literal becomes an error named `RequireFailed<N>` with code
1969
- * 6000 + N, numbered after the program's error enums and listed in the IDL.
1992
+ * 6000 + N, numbered after the program's error enums and listed in the IDL. A `u32` value instead fails with that code
1993
+ * as computed at run time (`require(r.err === 0n, r.err)`, a helper returning its error as a value, as Rust's `?` passes
1994
+ * one on); a zero code fails with 5100.
1970
1995
  */
1971
- export declare function require(condition: boolean, error: string | AnchorError): asserts condition;
1996
+ export declare function require(condition: boolean, error: string | AnchorError | u32): asserts condition;
1972
1997
  /**
1973
1998
  * Anchor's `constraint = condition @ error` on `account`. Written at the start of an instruction's body (before any
1974
1999
  * other statement), it runs with that account's checks, after its has_one and before its owner check, so a transaction
@@ -2036,6 +2061,15 @@ export declare function mulDiv(a: u64, b: u64, c: u64): u64;
2036
2061
  export declare function mulDivCeil(a: u64, b: u64, c: u64): u64;
2037
2062
  /** floor(sqrt(x)) for unsigned integers up to u128. */
2038
2063
  export declare function isqrt<T extends bigint>(x: T): T;
2064
+
2065
+ /**
2066
+ * A 64-bit float, held as its IEEE 754 bits (Borsh writes an f64 as those 8 bytes, little-endian); the IDL calls it
2067
+ * f64. There is no float arithmetic: make one from bits the program computed in integers (`f64FromBits`), as
2068
+ * Marginfi's events report I80F48 amounts, and read the bits back with `f64Bits`.
2069
+ */
2070
+ export type f64 = bigint & { readonly __f64: unique symbol };
2071
+ export declare function f64FromBits(bits: u64): f64;
2072
+ export declare function f64Bits(value: f64): u64;
2039
2073
  export declare function min<T extends bigint>(a: T, b: T): T;
2040
2074
  export declare function max<T extends bigint>(a: T, b: T): T;
2041
2075
 
@@ -2044,6 +2078,11 @@ export declare function max<T extends bigint>(a: T, b: T): T;
2044
2078
  * `readData<u64>(pool, 72n)`, `readData<Pubkey>(pool, 8n)`. Check the account's owner yourself first.
2045
2079
  */
2046
2080
  export declare function readData<T extends bigint | boolean | Pubkey | Hash>(account: AccountMeta | RemainingAccount, offset: u64): T;
2081
+ /**
2082
+ * Write a little-endian value at `offset` in a `Mut<AccountInfo>`'s data (bounds-checked, error 3003):
2083
+ * `writeData<u64>(archive, 72n, count)`. Only this program's accounts can change: check the owner first.
2084
+ */
2085
+ export declare function writeData<T extends bigint | boolean | Pubkey | Hash>(account: Mut<AccountInfo>, offset: u64, value: T): void;
2047
2086
 
2048
2087
  /**
2049
2088
  * View another program's Anchor account as a struct declared here (same field layout): the owner must be
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.37.0",
3
+ "version": "0.39.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -63,13 +63,15 @@
63
63
  "test": "vitest run",
64
64
  "typesol": "node dist/cli.js",
65
65
  "smoke": "node scripts/smoke.ts",
66
- "fuzz": "FUZZ_RUNS=2000 FUZZ_STEPS=600 FUZZ_VERBOSE=1 vitest run test/verification/fuzz-arith.test.ts test/verification/fuzz-state.test.ts test/verification/fuzz-layout.test.ts test/verification/differential.test.ts --silent=false",
66
+ "fuzz": "FUZZ_RUNS=2000 FUZZ_STEPS=600 FUZZ_VERBOSE=1 vitest run test/verification/fuzz-arith.test.ts test/verification/fuzz-state.test.ts test/verification/fuzz-layout.test.ts test/verification/differential.test.ts showcase/test/fuzz-jito.test.ts showcase/test/fuzz-marginfi.test.ts --silent=false",
67
67
  "build:twins": "cd test/anchor-twins && cargo-build-sbf",
68
68
  "prepack": "npm run build",
69
69
  "fetch:programs": "bash scripts/fetch-programs.sh",
70
- "format": "prettier --write \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\"",
71
- "lint": "prettier --check \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\" && pnpm typecheck",
72
- "prepublishOnly": "pnpm lint && pnpm test"
70
+ "format": "prettier --write \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"showcase/test/*.ts\" \"showcase/test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\"",
71
+ "lint": "prettier --check \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"showcase/test/*.ts\" \"showcase/test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\" && pnpm typecheck",
72
+ "prepublishOnly": "pnpm lint && pnpm test",
73
+ "test:core": "vitest run --exclude 'showcase/**'",
74
+ "test:showcase": "vitest run showcase"
73
75
  },
74
76
  "engines": {
75
77
  "node": ">=22.12"
@@ -115,10 +117,10 @@
115
117
  "packageManager": "pnpm@11.9.0",
116
118
  "repository": {
117
119
  "type": "git",
118
- "url": "git+https://github.com/typesol/typesol.git"
120
+ "url": "git+https://github.com/typesol-lang/typesol.git"
119
121
  },
120
122
  "bugs": {
121
- "url": "https://github.com/typesol/typesol/issues"
123
+ "url": "https://github.com/typesol-lang/typesol/issues"
122
124
  },
123
125
  "homepage": "https://typesol.com",
124
126
  "publishConfig": {