@typesol/cli 0.38.0 → 0.40.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.
- package/CHANGELOG.md +373 -2
- package/README.md +43 -26
- package/SECURITY.md +1 -1
- package/dist/cli.js +37 -3
- package/dist/compiler/analyze.d.ts +6 -11
- package/dist/compiler/analyze.js +331 -34
- package/dist/compiler/emit/alias.js +3 -2
- package/dist/compiler/emit/base.d.ts +7 -1
- package/dist/compiler/emit/base.js +2 -0
- package/dist/compiler/emit/borsh.js +63 -2
- package/dist/compiler/emit/calls.d.ts +14 -1
- package/dist/compiler/emit/calls.js +311 -21
- package/dist/compiler/emit/cpi-core.js +17 -5
- package/dist/compiler/emit/cpi.js +81 -27
- package/dist/compiler/emit/create.d.ts +7 -0
- package/dist/compiler/emit/create.js +27 -0
- package/dist/compiler/emit/expressions.d.ts +6 -0
- package/dist/compiler/emit/expressions.js +102 -6
- package/dist/compiler/emit/function.d.ts +7 -0
- package/dist/compiler/emit/function.js +164 -29
- package/dist/compiler/emit/program.js +27 -2
- package/dist/compiler/emit/shared.d.ts +15 -5
- package/dist/compiler/emit/shared.js +5 -0
- package/dist/compiler/emit/statements.d.ts +28 -1
- package/dist/compiler/emit/statements.js +270 -13
- package/dist/compiler/emit/storage.d.ts +10 -1
- package/dist/compiler/emit/storage.js +50 -11
- package/dist/compiler/hints.d.ts +5 -0
- package/dist/compiler/hints.js +88 -0
- package/dist/compiler/idl.d.ts +1 -1
- package/dist/compiler/idl.js +42 -11
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +6 -1
- package/dist/compiler/model.d.ts +47 -10
- package/dist/compiler/model.js +14 -4
- package/dist/testing.js +8 -0
- package/dist/tools/clientgen.js +10 -1
- package/dist/tools/portgen.d.ts +6 -0
- package/dist/tools/portgen.js +68 -17
- package/docs/architecture.md +5 -4
- package/docs/audit.md +31 -19
- package/docs/case-study-escrow.md +5 -5
- package/docs/case-study-jito-mev.md +9 -5
- package/docs/case-study-marginfi.md +797 -0
- package/docs/case-study-multisig.md +3 -3
- package/docs/case-study-raydium-amm.md +80 -0
- package/docs/case-study-raydium-clmm.md +44 -33
- package/docs/case-study-raydium-cp-swap.md +3 -3
- package/docs/cli.md +5 -5
- package/docs/client.md +1 -1
- package/docs/errors.md +13 -5
- package/docs/language.md +65 -32
- package/docs/migrate-from-anchor.md +4 -1
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +2 -1
- package/docs/testing.md +34 -1
- package/docs/troubleshooting.md +6 -0
- package/lib/typesol.d.ts +118 -10
- package/package.json +9 -7
- package/runtime/typesol_rt.h +158 -17
- package/ts-plugin/index.js +24 -1
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
|
|
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)
|
|
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
|
|
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
|
|
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) |
|
|
48
|
-
| 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)`) |
|
|
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) |
|
|
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)`). 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) |
|
|
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
|
-
| 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 |
|
|
54
|
+
| 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) |
|
|
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) |
|
|
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) |
|
|
74
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
|
-
|
|
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), `
|
|
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 `
|
|
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
|
|
@@ -199,13 +212,33 @@ When an instruction calls `x.create(payer, seeds)` or `requirePda(x, seeds, bump
|
|
|
199
212
|
an integer literal, an argument, `acct.key` or a scalar field of an account, the IDL entry for `x` gets Anchor `pda.seeds`
|
|
200
213
|
(`const` / `arg` / `account`), so Anchor and Codama clients derive the address themselves.
|
|
201
214
|
|
|
215
|
+
## Porting a native program
|
|
216
|
+
|
|
217
|
+
A program written without Anchor (Raydium AMM v4, SPL programs) reads a tag byte and its arguments itself and takes its
|
|
218
|
+
accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-amm` and `test/fixtures/native.ts`):
|
|
219
|
+
|
|
220
|
+
- One `/** @fallback */` entry: `const data = instructionData()` gives the bytes, with `data.readU8/U16/U32/U64/U128/
|
|
221
|
+
readPubkey(offset)` (little-endian, bounds-checked: 5104); `remainingAccounts()` gives the accounts by position.
|
|
222
|
+
- Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
|
|
223
|
+
byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
|
|
224
|
+
original's own checks (an exact size, its error codes) before the load. Structs are packed, as `#[repr(C, packed)]`.
|
|
225
|
+
- Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
|
|
226
|
+
`ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
|
|
227
|
+
built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
|
|
228
|
+
reporting that location); `const PANIC_ON_OVERFLOW = true` makes arithmetic overflow and division by zero panic as
|
|
229
|
+
`checked_*().unwrap()` does instead of failing with 5100 / 5101.
|
|
230
|
+
- Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
|
|
231
|
+
"Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`);
|
|
232
|
+
`logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
|
|
233
|
+
`createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
|
|
234
|
+
|
|
202
235
|
## Not supported yet
|
|
203
236
|
|
|
204
|
-
A struct holding a FixedVec that is both an argument and account data (
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
a
|
|
208
|
-
(by design).
|
|
237
|
+
A struct holding a FixedVec that is both an argument and account data (its bytes differ there, and the IDL describes a
|
|
238
|
+
type one way: declare one for each), growing an account by more than 10 KiB in one instruction (Solana's limit: realloc
|
|
239
|
+
again in the next instruction), `?.` and `!` on anything but optional accounts, Options and a `find` on struct elements,
|
|
240
|
+
functions stored in a struct, chosen from a list by index or returned from an instruction, a fused `map` to strings
|
|
241
|
+
(store it, annotated), floating point (by design).
|
|
209
242
|
They are rejected at compile time rather than half-supported.
|
|
210
243
|
|
|
211
244
|
`Init.create` handles a PDA address someone pre-funded: it tops up rent, then allocates and assigns instead of
|
|
@@ -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; `X = ""` for a variant without `#[msg]`) |
|
|
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".
|
package/docs/security-model.md
CHANGED
|
@@ -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).
|
|
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,43 @@ 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 `
|
|
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 0.39.0 on, each release's GitHub Release carries its manifest, `typesol-<version>-manifest.json`, attached by
|
|
25
|
+
hand after the npm publish (written by `scripts/release-manifest.ts` from the tag's sources; the scripts need Node 22.18
|
|
26
|
+
or later):
|
|
27
|
+
|
|
28
|
+
- the compiler and toolchain versions (clang, platform-tools, Node, TypeScript, the runtime header's sha256);
|
|
29
|
+
- the sha256 of the SBF binary, IDL and C that every program under `examples/` and `showcase/program-examples/` builds to;
|
|
30
|
+
- the sha256 of the reference binaries the differential tests run against (`test/programs/`);
|
|
31
|
+
- a hash of the test corpus.
|
|
32
|
+
|
|
33
|
+
It also carries `binary-diff.txt`: the previous release's sources built by the previous package and by this one,
|
|
34
|
+
compared program by program. That is the check behind a changelog line such as "programs that use none of these compile to the
|
|
35
|
+
same binaries". To redo it, or to compare other versions:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
git worktree add ../typesol-prev v0.37.0 # the sources to build
|
|
39
|
+
npm install --prefix /tmp/a @typesol/cli@0.37.0
|
|
40
|
+
npm install --prefix /tmp/b @typesol/cli@0.38.0
|
|
41
|
+
node scripts/release-manifest.ts --compiler /tmp/a/node_modules/@typesol/cli --sources ../typesol-prev --out a.json
|
|
42
|
+
node scripts/release-manifest.ts --compiler /tmp/b/node_modules/@typesol/cli --sources ../typesol-prev --out b.json
|
|
43
|
+
node scripts/release-manifest.ts --diff a.json b.json
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For 0.37.0 → 0.38.0 (run by hand before release manifests existed): all 67 programs of the 0.37.0 sources build to
|
|
47
|
+
the same binary and IDL with both packages.
|
|
48
|
+
|
package/docs/troubleshooting.md
CHANGED
|
@@ -17,6 +17,12 @@ printed commands yourself.
|
|
|
17
17
|
Restore it from your backup. Without it you cannot upgrade the deployed program; removing `"address"` from
|
|
18
18
|
`typesol.json` gives the program a new address.
|
|
19
19
|
|
|
20
|
+
**A build error you don't recognize** — the compiler adds a `hint:` line under TypeScript's message where TypeScript's
|
|
21
|
+
own advice points the wrong way for a program. The usual ones: integers are `bigint` (`1n`, `u64` parameters, not
|
|
22
|
+
`number`); `require`, `log`, `min`, `max` and `fixedArray` are imported from `"typesol"`; arrays are read with `.get(i)`
|
|
23
|
+
and written with `.set(i, v)`; an account you change is a `Mut<T>` parameter; there is no `async`, `try`, `throw` or
|
|
24
|
+
`class`. The full list of what the subset covers is in [language.md](language.md).
|
|
25
|
+
|
|
20
26
|
**A transaction fails with a custom error** — see [errors.md](errors.md). Failures raised by the
|
|
21
27
|
compiler's checks log their TypeScript location, e.g. `TypeSOL: arithmetic overflow (vault.ts:42)`.
|
|
22
28
|
|
package/lib/typesol.d.ts
CHANGED
|
@@ -177,11 +177,21 @@ 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).
|
|
181
|
-
*
|
|
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
|
+
/**
|
|
188
|
+
* A native (non-Anchor) program's own account as a fixed-layout struct, as a `#[repr(C)]` type's `load_checked` /
|
|
189
|
+
* `load_mut_checked` reads it: owned by this program (3007) and at least as large as the struct (3003). There is no
|
|
190
|
+
* discriminator: the fields start at byte 0. `loadRawMut` also requires the account to be writable and not loaded
|
|
191
|
+
* mutably twice in the instruction (2040). Bind it with const: `const amm = loadRawMut<AmmInfo>(ammInfo)`.
|
|
192
|
+
*/
|
|
193
|
+
export declare function loadRaw<T>(account: RemainingAccount | AccountInfo): Account<T>;
|
|
194
|
+
export declare function loadRawMut<T>(account: RemainingAccount | AccountInfo): Mut<T>;
|
|
185
195
|
|
|
186
196
|
/** 32 bytes of hash output (sha256 / keccak256, Merkle roots). Compare with `===`. */
|
|
187
197
|
export interface Hash {
|
|
@@ -551,6 +561,17 @@ export declare function masterEditionAddress(mint: Pubkey): Pubkey;
|
|
|
551
561
|
*/
|
|
552
562
|
export declare function bigEndian(value: bigint): Seed;
|
|
553
563
|
export declare function findProgramAddress(seeds: Seed[], program: Pubkey): Pubkey;
|
|
564
|
+
/**
|
|
565
|
+
* `Pubkey::create_program_address(seeds, program)`: the address of these seeds with the bump given as the last seed,
|
|
566
|
+
* or null when they give no program address (a point on the curve, or too many / too long seeds).
|
|
567
|
+
*/
|
|
568
|
+
export declare function createProgramAddress(seeds: Seed[], program: Pubkey): Pubkey | null;
|
|
569
|
+
/**
|
|
570
|
+
* Log `prefix` followed by the base64 (standard, padded) of a struct value's bytes, as a native program's
|
|
571
|
+
* `msg!("ray_log: {}", base64(bincode(log)))` does. The struct holds integers, Pubkeys and fixed arrays of them only,
|
|
572
|
+
* so its bytes are its serialized form.
|
|
573
|
+
*/
|
|
574
|
+
export declare function logBase64(prefix: string, value: object): void;
|
|
554
575
|
/** The bump of that canonical program address (`Pubkey::find_program_address(seeds, program).1`), to sign with it. */
|
|
555
576
|
export declare function findProgramAddressBump(seeds: Seed[], program: Pubkey): u8;
|
|
556
577
|
/** This program's address (`crate::ID`). */
|
|
@@ -655,6 +676,12 @@ export declare const AuthorityType: {
|
|
|
655
676
|
* the struct size. Accounts ending in a Vec size themselves through push/pop/clear.
|
|
656
677
|
*/
|
|
657
678
|
export declare function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void;
|
|
679
|
+
/**
|
|
680
|
+
* Resize a `Mut<AccountInfo>` of this program to `newSize` bytes (Rust's `AccountInfo::resize`): the data length only,
|
|
681
|
+
* the new bytes zeroed. No rent moves: fund the account first (`rentExempt(newSize)`), the runtime refuses an account
|
|
682
|
+
* left short. At most 10 KiB past its size when the instruction started (3016).
|
|
683
|
+
*/
|
|
684
|
+
export declare function resizeAccount(account: Mut<AccountInfo>, newSize: u64): void;
|
|
658
685
|
|
|
659
686
|
/**
|
|
660
687
|
* Token-2022 extensions of a mint (any account works; legacy SPL Token mints have none).
|
|
@@ -725,8 +752,8 @@ export type Account<T> = Readonly<T> & AccountMeta;
|
|
|
725
752
|
*/
|
|
726
753
|
export type Mut<T, E = never> = T & AccountMeta;
|
|
727
754
|
|
|
728
|
-
/** A PDA seed: a string, a Pubkey, an integer (at its width) or a unit enum value (one byte). */
|
|
729
|
-
export type Seed = string | Pubkey | bigint | number;
|
|
755
|
+
/** A PDA seed: a string, a Pubkey, a Hash (its 32 bytes), an integer (at its width) or a unit enum value (one byte). */
|
|
756
|
+
export type Seed = string | Pubkey | Hash | bigint | number;
|
|
730
757
|
|
|
731
758
|
/**
|
|
732
759
|
* The seeds (with the bump) of one PDA signature, for helpers that sign CPIs: declare a `seeds: SignerSeeds`
|
|
@@ -831,7 +858,7 @@ export type MintOf<A, AuthorityParam extends string, FreezeAuthorityParam extend
|
|
|
831
858
|
/**
|
|
832
859
|
* Anchor's `dup`: this writable account may be the same account as another writable parameter (TypeSOL refuses that
|
|
833
860
|
* otherwise, 2040). Both are read and written in place, so a write through one is seen through the other: read
|
|
834
|
-
* what you need before writing. Not for accounts that are created, closed
|
|
861
|
+
* 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).
|
|
835
862
|
*/
|
|
836
863
|
export type Dup<A> = A & { readonly __dup?: true };
|
|
837
864
|
/**
|
|
@@ -1516,6 +1543,8 @@ export interface CompressedLeaf {
|
|
|
1516
1543
|
/** The current slot and epoch (Clock sysvar). */
|
|
1517
1544
|
export declare function currentSlot(): u64;
|
|
1518
1545
|
export declare function currentEpoch(): u64;
|
|
1546
|
+
/** The Unix time the current epoch started at (Clock.epoch_start_timestamp). */
|
|
1547
|
+
export declare function epochStartTimestamp(): i64;
|
|
1519
1548
|
/** The EpochSchedule sysvar: slots per epoch (after warmup), whether epochs warm up, and where normal epochs start. */
|
|
1520
1549
|
export declare function slotsPerEpoch(): u64;
|
|
1521
1550
|
export declare function epochWarmup(): boolean;
|
|
@@ -1632,6 +1661,13 @@ export interface SystemProgram extends AccountMeta {
|
|
|
1632
1661
|
* `Mut<Signer>` keypair, or a PDA of this program when you pass its `signerSeeds` (with the bump).
|
|
1633
1662
|
*/
|
|
1634
1663
|
createAccount(payer: Mut<Signer>, account: AccountMeta, lamports: u64, space: u64, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1664
|
+
/**
|
|
1665
|
+
* Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: `account` must be the PDA of this
|
|
1666
|
+
* program for `seeds` (no bump; 2006 otherwise); it is created with `space` bytes owned by `owner`, or, when someone
|
|
1667
|
+
* already funded the address, topped up to rent, allocated and assigned. Returns the bump. Among the creates a body
|
|
1668
|
+
* starts with, it runs before the other accounts' constraints, as Anchor's `init` does.
|
|
1669
|
+
*/
|
|
1670
|
+
createPda(payer: Mut<Signer>, account: Mut<AccountInfo>, space: u64, owner: Pubkey, seeds: Seed[]): u8;
|
|
1635
1671
|
/** System Allocate: give `account` `space` bytes of data. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
|
|
1636
1672
|
allocate(account: AccountMeta, space: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1637
1673
|
/** System Assign: make `owner` the account's owner. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
|
|
@@ -1820,9 +1856,13 @@ export interface UncheckedProgram extends AccountMeta {
|
|
|
1820
1856
|
export interface CpiAccount {
|
|
1821
1857
|
readonly __cpi_account: void;
|
|
1822
1858
|
}
|
|
1823
|
-
|
|
1859
|
+
/**
|
|
1860
|
+
* An optional account (`A | null`) passed as it is, without `!`: left out of the CPI's list when it was not passed
|
|
1861
|
+
* (Rust's `if let Some(a) = &self.a { accounts.push(a) }`, as for `with_remaining_accounts`).
|
|
1862
|
+
*/
|
|
1863
|
+
export declare function readonly(account: AccountMeta | RemainingAccount | null): CpiAccount;
|
|
1824
1864
|
export declare function readonly(accounts: RemainingAccounts | RemainingSlice): Iterable<CpiAccount>;
|
|
1825
|
-
export declare function writable(account: AccountMeta | RemainingAccount): CpiAccount;
|
|
1865
|
+
export declare function writable(account: AccountMeta | RemainingAccount | null): CpiAccount;
|
|
1826
1866
|
export declare function writable(accounts: RemainingAccounts | RemainingSlice): Iterable<CpiAccount>;
|
|
1827
1867
|
export declare function readonlySigner(account: AccountMeta | RemainingAccount): CpiAccount;
|
|
1828
1868
|
export declare function writableSigner(account: AccountMeta | RemainingAccount): CpiAccount;
|
|
@@ -1968,9 +2008,52 @@ export declare enum AnchorError {
|
|
|
1968
2008
|
/**
|
|
1969
2009
|
* Abort with the given error unless `condition` holds. The error is a member of an exported string enum, any
|
|
1970
2010
|
* `AnchorError` member, or a string literal: each distinct literal becomes an error named `RequireFailed<N>` with code
|
|
1971
|
-
* 6000 + N, numbered after the program's error enums and listed in the IDL.
|
|
2011
|
+
* 6000 + N, numbered after the program's error enums and listed in the IDL. A `u32` value instead fails with that code
|
|
2012
|
+
* as computed at run time (`require(r.err === 0n, r.err)`, a helper returning its error as a value, as Rust's `?` passes
|
|
2013
|
+
* one on); a zero code fails with 5100.
|
|
2014
|
+
*/
|
|
2015
|
+
export declare function require(condition: boolean, error: string | AnchorError | ProgramError | u32): asserts condition;
|
|
2016
|
+
|
|
2017
|
+
/**
|
|
2018
|
+
* Solana's built-in program errors (`solana_program::program_error::ProgramError`, no custom code): a native program's
|
|
2019
|
+
* `Err(ProgramError::InvalidInstructionData)`. `require(condition, ProgramError.InvalidInstructionData)` fails the same
|
|
2020
|
+
* way (the runtime reports the built-in error, not a custom one). Not listed in the IDL's errors.
|
|
2021
|
+
*/
|
|
2022
|
+
export declare enum ProgramError {
|
|
2023
|
+
InvalidArgument = 2,
|
|
2024
|
+
InvalidInstructionData = 3,
|
|
2025
|
+
InvalidAccountData = 4,
|
|
2026
|
+
AccountDataTooSmall = 5,
|
|
2027
|
+
InsufficientFunds = 6,
|
|
2028
|
+
IncorrectProgramId = 7,
|
|
2029
|
+
MissingRequiredSignature = 8,
|
|
2030
|
+
AccountAlreadyInitialized = 9,
|
|
2031
|
+
UninitializedAccount = 10,
|
|
2032
|
+
NotEnoughAccountKeys = 11,
|
|
2033
|
+
AccountBorrowFailed = 12,
|
|
2034
|
+
MaxSeedLengthExceeded = 13,
|
|
2035
|
+
InvalidSeeds = 14,
|
|
2036
|
+
BorshIoError = 15,
|
|
2037
|
+
AccountNotRentExempt = 16,
|
|
2038
|
+
UnsupportedSysvar = 17,
|
|
2039
|
+
IllegalOwner = 18,
|
|
2040
|
+
MaxAccountsDataAllocationsExceeded = 19,
|
|
2041
|
+
InvalidRealloc = 20,
|
|
2042
|
+
MaxInstructionTraceLengthExceeded = 21,
|
|
2043
|
+
BuiltinProgramsMustConsumeComputeUnits = 22,
|
|
2044
|
+
InvalidAccountOwner = 23,
|
|
2045
|
+
ArithmeticOverflow = 24,
|
|
2046
|
+
Immutable = 25,
|
|
2047
|
+
IncorrectAuthority = 26,
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/**
|
|
2051
|
+
* Stop the program as a Rust `panic!` / `unwrap()` on `None` / `unreachable!()` does: the message is logged and the
|
|
2052
|
+
* instruction fails with ProgramFailedToComplete (no error code). For porting native programs whose failures panic:
|
|
2053
|
+
* `location` ("program/src/instruction.rs:482:17") is the place the runtime reports, as the original's panic gives it;
|
|
2054
|
+
* by default this source line.
|
|
1972
2055
|
*/
|
|
1973
|
-
export declare function
|
|
2056
|
+
export declare function panic(message?: string, location?: string): never;
|
|
1974
2057
|
/**
|
|
1975
2058
|
* Anchor's `constraint = condition @ error` on `account`. Written at the start of an instruction's body (before any
|
|
1976
2059
|
* other statement), it runs with that account's checks, after its has_one and before its owner check, so a transaction
|
|
@@ -1984,7 +2067,18 @@ export declare function constraint(account: AccountMeta | RemainingAccount | nul
|
|
|
1984
2067
|
* `data.get(i)`, or pass it on to `invokeInstruction`. A `/** @fallback *\/` instruction (Anchor's fallback: no
|
|
1985
2068
|
* parameters, run when no instruction matches) reads its input this way, and its accounts with remainingAccounts().
|
|
1986
2069
|
*/
|
|
1987
|
-
export declare function instructionData():
|
|
2070
|
+
export declare function instructionData(): InstructionBytes;
|
|
2071
|
+
|
|
2072
|
+
/** The instruction data, read in place: its bytes, and little-endian values at a byte offset. */
|
|
2073
|
+
export interface InstructionBytes extends IndexedList<u8> {
|
|
2074
|
+
/** The little-endian value at `offset`; reading past the end fails the instruction (5104). */
|
|
2075
|
+
readU8(offset: u64): u8;
|
|
2076
|
+
readU16(offset: u64): u16;
|
|
2077
|
+
readU32(offset: u64): u32;
|
|
2078
|
+
readU64(offset: u64): u64;
|
|
2079
|
+
readU128(offset: u64): u128;
|
|
2080
|
+
readPubkey(offset: u64): Pubkey;
|
|
2081
|
+
}
|
|
1988
2082
|
|
|
1989
2083
|
/** Write a string, integer or pubkey to the program log. */
|
|
1990
2084
|
export declare function log(value: string | bigint | Pubkey | Hash): void;
|
|
@@ -2038,6 +2132,15 @@ export declare function mulDiv(a: u64, b: u64, c: u64): u64;
|
|
|
2038
2132
|
export declare function mulDivCeil(a: u64, b: u64, c: u64): u64;
|
|
2039
2133
|
/** floor(sqrt(x)) for unsigned integers up to u128. */
|
|
2040
2134
|
export declare function isqrt<T extends bigint>(x: T): T;
|
|
2135
|
+
|
|
2136
|
+
/**
|
|
2137
|
+
* A 64-bit float, held as its IEEE 754 bits (Borsh writes an f64 as those 8 bytes, little-endian); the IDL calls it
|
|
2138
|
+
* f64. There is no float arithmetic: make one from bits the program computed in integers (`f64FromBits`), as
|
|
2139
|
+
* Marginfi's events report I80F48 amounts, and read the bits back with `f64Bits`.
|
|
2140
|
+
*/
|
|
2141
|
+
export type f64 = bigint & { readonly __f64: unique symbol };
|
|
2142
|
+
export declare function f64FromBits(bits: u64): f64;
|
|
2143
|
+
export declare function f64Bits(value: f64): u64;
|
|
2041
2144
|
export declare function min<T extends bigint>(a: T, b: T): T;
|
|
2042
2145
|
export declare function max<T extends bigint>(a: T, b: T): T;
|
|
2043
2146
|
|
|
@@ -2046,6 +2149,11 @@ export declare function max<T extends bigint>(a: T, b: T): T;
|
|
|
2046
2149
|
* `readData<u64>(pool, 72n)`, `readData<Pubkey>(pool, 8n)`. Check the account's owner yourself first.
|
|
2047
2150
|
*/
|
|
2048
2151
|
export declare function readData<T extends bigint | boolean | Pubkey | Hash>(account: AccountMeta | RemainingAccount, offset: u64): T;
|
|
2152
|
+
/**
|
|
2153
|
+
* Write a little-endian value at `offset` in a `Mut<AccountInfo>`'s data (bounds-checked, error 3003):
|
|
2154
|
+
* `writeData<u64>(archive, 72n, count)`. Only this program's accounts can change: check the owner first.
|
|
2155
|
+
*/
|
|
2156
|
+
export declare function writeData<T extends bigint | boolean | Pubkey | Hash>(account: Mut<AccountInfo>, offset: u64, value: T): void;
|
|
2049
2157
|
|
|
2050
2158
|
/**
|
|
2051
2159
|
* View another program's Anchor account as a struct declared here (same field layout): the owner must be
|