@typesol/cli 0.40.0 → 0.41.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 +28 -0
- package/README.md +7 -4
- package/dist/ai.d.ts +10 -0
- package/dist/ai.js +43 -0
- package/dist/cli.js +15 -1
- package/dist/compiler/analyze.js +3 -2
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/emit/calls.js +8 -1
- package/dist/tools/mcp.d.ts +11 -0
- package/dist/tools/mcp.js +208 -0
- package/dist/workspace.js +8 -0
- package/docs/ai.md +52 -0
- package/docs/audit.md +16 -14
- package/docs/case-study-raydium-cp-swap.md +77 -41
- package/docs/stability.md +56 -0
- package/llms-full.txt +1195 -0
- package/llms.txt +30 -0
- package/package.json +4 -2
package/llms-full.txt
ADDED
|
@@ -0,0 +1,1195 @@
|
|
|
1
|
+
# TypeSOL: the rules and the reference
|
|
2
|
+
|
|
3
|
+
## Writing TypeSOL
|
|
4
|
+
|
|
5
|
+
TypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live
|
|
6
|
+
in `programs/`, tests in `tests/`; `typesol.json` lists the programs.
|
|
7
|
+
|
|
8
|
+
- Exported functions are instructions; their parameters are the accounts (`Signer`, `Account<T>`, `Mut<T>`,
|
|
9
|
+
`Init<T>`, token accounts, programs) and then the arguments. Account data types are exported interfaces.
|
|
10
|
+
- Integers are bigint: `u8` … `u128`, `i8` … `i128` (write `1n`, never `1`; take `u64`, never `number`).
|
|
11
|
+
Arithmetic is checked: an overflow fails the instruction. There is no floating point.
|
|
12
|
+
- Import everything from `"typesol"`: types, and functions such as `require`, `log`, `min`, `max`,
|
|
13
|
+
`fixedArray`, `emit`, `invoke`.
|
|
14
|
+
- Fail with `require(condition, MyError.Name)` (an exported string enum of messages) or `require(condition, "message")`.
|
|
15
|
+
There is no `throw`, `try`, `async`, `class`, `console` or `Math`.
|
|
16
|
+
- An account the instruction changes is `Mut<T>`; one it creates is `Init<T>` (`acct.create(payer, seeds)`).
|
|
17
|
+
- Lists: `FixedArray<T, N>`, `FixedVec<T, N>`, `Vec<T>`; read with `.get(i)` and write with `.set(i, v)`
|
|
18
|
+
(`i` a bigint), not `xs[i]`. `map`, `filter`, `find`, `some`, `reduce` work on them.
|
|
19
|
+
- Strings are `FixedString<N>` in account data; `Option<T>` (`T | null`) for optional values.
|
|
20
|
+
|
|
21
|
+
## Checking your work
|
|
22
|
+
|
|
23
|
+
- `npx typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a
|
|
24
|
+
`hint` that says what to write instead. Fix those first; they are faster than a build.
|
|
25
|
+
- `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx typesol build`
|
|
26
|
+
writes `target/<name>/`: the `.so`, the IDL and a typed client.
|
|
27
|
+
- The MCP server (`npx typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,
|
|
28
|
+
the IDL and the docs as tools.
|
|
29
|
+
- The language reference: `node_modules/typesol/docs/language.md`, or https://typesol.com/llms-full.txt.
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
You need Node.js 22.12 or later and the Agave CLI (`sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)"`).
|
|
34
|
+
Run `cargo-build-sbf --version` once; this downloads the platform-tools that TypeSOL compiles with. Rust is not needed.
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
npx @typesol/cli init my-app --name counter # typesol.json, programs/counter.ts, tests/counter.test.ts, tsconfig
|
|
38
|
+
cd my-app && npm install
|
|
39
|
+
npm test # builds the program and runs it in LiteSVM, an in-process Solana runtime
|
|
40
|
+
npx typesol build # target/counter/{counter.so, counter.json (IDL), counter.client.ts, counter.build.json}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`npx typesol doctor` checks all of this (Node.js, platform-tools, Solana CLI, keypair, RPC) and prints the command
|
|
44
|
+
that fixes anything missing. To deploy, on devnet:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
solana-keygen new # once, if you have no keypair (~/.config/solana/id.json)
|
|
48
|
+
solana airdrop 2 --url devnet # test SOL for the rent (rate-limited: https://faucet.solana.com also works)
|
|
49
|
+
npx typesol deploy --url devnet
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
or on a local validator: `solana-test-validator` in another terminal, `solana airdrop 5 --url localhost`, then
|
|
53
|
+
`npx typesol deploy --url localhost`. `deploy` checks the RPC and the payer's balance before sending anything.
|
|
54
|
+
|
|
55
|
+
`--template vault` or `--template escrow` starts from a SOL vault or an SPL token escrow instead of the counter, each
|
|
56
|
+
with a passing LiteSVM test.
|
|
57
|
+
|
|
58
|
+
The npm package is [`@typesol/cli`](https://www.npmjs.com/package/@typesol/cli). Projects install it under the name
|
|
59
|
+
`typesol`, which is what programs import (`import { … } from "typesol"`); `typesol init` sets that up. To add it to an
|
|
60
|
+
existing project: `npm install -D typesol@npm:@typesol/cli`.
|
|
61
|
+
|
|
62
|
+
Deploying again upgrades the program in place. Keep `target/deploy/<name>-keypair.json`: that keypair is your
|
|
63
|
+
program's address.
|
|
64
|
+
|
|
65
|
+
**Your first change.** Open `programs/counter.ts`, add an instruction (say `decrement`, with
|
|
66
|
+
`require(counter.count >= 1n, …)` before `counter.count -= 1n`), call it from `tests/counter.test.ts` and run `npm test`.
|
|
67
|
+
If the build refuses something, the error points at the line and, for the usual first mistakes (`1` instead of `1n`,
|
|
68
|
+
`console.log`, a missing import, `async`), adds a `hint:` with what to write instead; your editor shows the same.
|
|
69
|
+
|
|
70
|
+
**Where next**
|
|
71
|
+
- The language, every type and built-in: [docs/language.md](docs/language.md).
|
|
72
|
+
- Tests with `typesol/testing` (accounts by name, plain values): [docs/test-your-program.md](docs/test-your-program.md).
|
|
73
|
+
- Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, and
|
|
74
|
+
`typesol port` starts from your program's IDL; [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one
|
|
75
|
+
program through the port.
|
|
76
|
+
- Real programs checked against their mainnet binaries: [Showcase](#showcase-ports-checked-against-mainnet), with a
|
|
77
|
+
case study each (Marginfi v2 in full: all 124 instructions, the same on 2,081 transactions; Raydium AMM v4, a native
|
|
78
|
+
program, down to its log lines).
|
|
79
|
+
- To mainnet (wallet, cost, deploy, IDL, verification): [docs/mainnet.md](docs/mainnet.md).
|
|
80
|
+
- With an AI coding agent: [docs/ai.md](docs/ai.md) (agent rules, [llms.txt](https://typesol.com/llms.txt), the MCP server).
|
|
81
|
+
|
|
82
|
+
<!-- docs/language.md -->
|
|
83
|
+
|
|
84
|
+
# The TypeSOL language
|
|
85
|
+
|
|
86
|
+
The full reference. For a tour, start with the [README](../README.md).
|
|
87
|
+
|
|
88
|
+
## Types and statements
|
|
89
|
+
|
|
90
|
+
| Concept | TypeSOL |
|
|
91
|
+
| --- | --- |
|
|
92
|
+
| Instruction | an exported function returning `void`, one integer / boolean / `Pubkey`, a `string` (a Borsh String), or a fixed-size struct (sent as return data, at most 1024 bytes; `returns` in the IDL, and the generated client decodes it) |
|
|
93
|
+
| Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
|
|
94
|
+
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
|
|
95
|
+
| Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
|
|
96
|
+
| Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
|
|
97
|
+
| Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+ (`/** @code 6200 */` before a member jumps to that code, Anchor's `Name = 200`; `Name = ""` has no message in the IDL); `require(cond, "message")` makes an error of its own (`RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL); `require(cond, AnchorError.RequireKeysEqViolated)` fails with one of Anchor's own codes (2502 here; any anchor-lang `ErrorCode` can be raised this way); `require(cond, code)` with a `u32` value fails with that code as computed at run time (a helper returning its error: `require(r.err === 0n, r.err)`). See [errors.md](errors.md) |
|
|
98
|
+
| Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit. A cast is a value: import `u64`, not `type u64` (one import serves as both) |
|
|
99
|
+
| Logging | `log("text")`, `log(value)`, `log(pubkey)` |
|
|
100
|
+
| Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
|
|
101
|
+
| Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack; also a struct literal's field value (`{ prices: fixedArray<u64, 16>(0n), … }`), filled in place |
|
|
102
|
+
| 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 |
|
|
103
|
+
| 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 |
|
|
104
|
+
| 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 |
|
|
105
|
+
| 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` |
|
|
106
|
+
| Pubkey constants | `const ADMIN = pubkey("4Nd1…")` (checked at compile time) or inline `pubkey("…")`; usable as seeds |
|
|
107
|
+
| 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 |
|
|
108
|
+
| Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
|
|
109
|
+
| 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 |
|
|
110
|
+
| 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 |
|
|
111
|
+
| 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 |
|
|
112
|
+
| 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 |
|
|
113
|
+
| 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 |
|
|
114
|
+
| 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 |
|
|
115
|
+
| 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 |
|
|
116
|
+
| 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) |
|
|
117
|
+
| 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) |
|
|
118
|
+
| 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 |
|
|
119
|
+
| 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) |
|
|
120
|
+
| Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
|
|
121
|
+
| 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 |
|
|
122
|
+
| 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 |
|
|
123
|
+
| Ternaries | `const fee = vip ? 0n : 30n` — only the chosen branch runs |
|
|
124
|
+
| Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL) |
|
|
125
|
+
| 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 |
|
|
126
|
+
| 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) |
|
|
127
|
+
| 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 |
|
|
128
|
+
| `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
|
|
129
|
+
| 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) |
|
|
130
|
+
| 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">`) |
|
|
131
|
+
| 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 |
|
|
132
|
+
| 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 |
|
|
133
|
+
| 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 |
|
|
134
|
+
| 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) |
|
|
135
|
+
| 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) |
|
|
136
|
+
| 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) |
|
|
137
|
+
| 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) |
|
|
138
|
+
| 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) |
|
|
139
|
+
| 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()`) |
|
|
140
|
+
| `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
|
|
141
|
+
| 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) |
|
|
142
|
+
| 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) |
|
|
143
|
+
| 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) |
|
|
144
|
+
| 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) |
|
|
145
|
+
| Heap | 32 KiB by default; `const HEAP_SIZE_KIB = 64n` (32–256) lets the program use more, when clients add ComputeBudget `requestHeapFrame` |
|
|
146
|
+
| Docs | JSDoc on instructions, `@param`, structs, fields and data enums becomes `docs` in the IDL |
|
|
147
|
+
| Metaplex Core | `core: MplCoreProgram` — `createCollection`, `createAsset` (in a collection, PDA authorities via signerSeeds), `transferAsset`, `burnAsset` (`null` leaves an optional account out); plugins as a literal list after the uri (`[{ kind: "Royalties", basisPoints: 500n, creators: [{ address, percentage: 100n }] }, { kind: "PermanentFreezeDelegate", frozen: false, authority: studio.key }]`), and `addPlugin` / `updatePlugin` / `removePlugin(…, "FreezeDelegate")` with their `…CollectionPlugin` forms. Plugins: Royalties (with an optional `ruleSet: { programAllowList \| programDenyList: [...] }`), FreezeDelegate, BurnDelegate, TransferDelegate, UpdateDelegate, PermanentFreezeDelegate, Attributes, PermanentTransferDelegate, PermanentBurnDelegate, Edition, MasterEdition (collections: `maxSupply?`, `name?`, `uri?`), AddBlocker, ImmutableMetadata, VerifiedCreators, Autograph, BubblegumV2, FreezeExecute, PermanentFreezeExecute (Groups is kept by Core's group instructions); `authority` is `"owner"`, `"updateAuthority"`, `"none"` or a Pubkey; `coreAssetOwner(asset)`, `coreAssetCollection(asset)`. External plugin adapters: `addExternalPlugin` / `removeExternalPlugin` / `writeExternalPluginData` (and the Collection forms) with `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle", baseAddress, checks: [{ event: "transfer", canReject: true }], resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram, checks, extraAccounts?, dataAuthority?, schema? }` and the Linked forms; a key names one (`{ kind: "AppData", dataAuthority }`, `{ kind: "Oracle", address }`); data is a string, a `Vec<u8>` argument or `null` (Core currently answers lifecycle hooks with NotAvailable, 23) |
|
|
148
|
+
| Compressed NFTs | `bubblegum: BubblegumProgram` — V1 (trees on SPL Account Compression): `createTree`, `mint` (MintV1, no collection/creators), `mintToCollection` (MintToCollectionV1: into a verified Token Metadata collection), `transfer`, `burn`, `delegate` (the leaf owner or delegate signs; a PDA owner signs with the seeds). V2 (trees on mpl-account-compression with mpl-noop): `createTreeV2`, `mintV2(…, { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable? }, { collection, authority, cpiSigner }?)` (into a Core collection that has the `BubblegumV2` plugin), `transferV2`, `burnV2`, `delegateV2`, `freezeV2` / `thawV2`, `setNonTransferableV2`, `updateMetadataV2(…, currentMetadata, { name?, symbol?, uri?, creators?, … })`, `verifyCreatorV2` / `unverifyCreatorV2`, `setCollectionV2`. Each takes the leaf (`{ root, dataHash, creatorHash, assetDataHash?, flags?, nonce, index }`, or `{ root, assetDataHash?, flags?, nonce, index }` with the leaf's current metadata for the metadata instructions) and its proof as `remainingAccounts()` / `rest.slice(a)` |
|
|
149
|
+
|
|
150
|
+
## Account parameters and the checks they emit
|
|
151
|
+
|
|
152
|
+
| Parameter type | Checked before your code runs |
|
|
153
|
+
| --- | --- |
|
|
154
|
+
| `Signer` / `Mut<Signer>` | signed (and writable) |
|
|
155
|
+
| `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 |
|
|
156
|
+
| `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 |
|
|
157
|
+
| `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 |
|
|
158
|
+
| `/** @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 |
|
|
159
|
+
| 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 |
|
|
160
|
+
| `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) |
|
|
161
|
+
| `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 |
|
|
162
|
+
| `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>` |
|
|
163
|
+
| `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) |
|
|
164
|
+
| `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) |
|
|
165
|
+
| `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 |
|
|
166
|
+
| `Address<A, "4Nd1…">` | exact address (2012; `address` in the IDL) |
|
|
167
|
+
| `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 |
|
|
168
|
+
| `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) |
|
|
169
|
+
| `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 |
|
|
170
|
+
| `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` |
|
|
171
|
+
| `EventAuthority`, `SelfProgram` | Anchor's `["__event_authority"]` PDA, and this program's own address, for `emitCpi` |
|
|
172
|
+
| `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 { … }` |
|
|
173
|
+
| `Zeroed<T>` | accounts (up to 10 MiB) the client allocated with System `CreateAccount`, Anchor's `zero`: discriminator still zero (2013, checked first as under Anchor), owned by this program, big enough, rent-exempt — then initialized. A `@layout borsh` struct starts empty and is written as Borsh when the instruction returns |
|
|
174
|
+
| `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 |
|
|
175
|
+
| `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) |
|
|
176
|
+
| `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) |
|
|
177
|
+
| `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` |
|
|
178
|
+
| `Mint` / `Mut<Mint>` | owned by SPL Token or Token-2022, initialized; `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
|
|
179
|
+
| `SystemProgram`, `TokenProgram`, `Token2022Program` | exact program address |
|
|
180
|
+
| `TokenInterface` | either token program |
|
|
181
|
+
| `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
|
|
182
|
+
| `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
|
|
183
|
+
| `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)` |
|
|
184
|
+
| `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) |
|
|
185
|
+
| `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) |
|
|
186
|
+
| `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 |
|
|
187
|
+
| `Program<"Address…">` | exact program address + executable |
|
|
188
|
+
| `UncheckedProgram` | executable only — check `.key` yourself |
|
|
189
|
+
| `AccountInfo` / `Mut<AccountInfo>` | nothing (writable for `Mut`); `owner`, `executable` |
|
|
190
|
+
| `SystemAccount` / `Mut<SystemAccount>` | owned by the System Program, e.g. a wallet (Anchor `SystemAccount`, 3011) |
|
|
191
|
+
|
|
192
|
+
Every account exposes `key`, `lamports`, `dataLen`, `isSigner`, `isWritable`. At most 32 accounts per instruction (more is refused, 5113); `export const MAX_ACCOUNTS = 128n` (up to 255, Anchor takes what the runtime allows) raises it for programs that take many remaining accounts, keeping the CPI scratch lists on the heap instead of the stack (programs that do not declare it compile exactly as before).
|
|
193
|
+
|
|
194
|
+
Two writable parameters can never be the same account: aliasing is refused with error 2040 (also when a remaining
|
|
195
|
+
account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
|
|
196
|
+
(Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed
|
|
197
|
+
or `@layout borsh`; a close destination may be one, the rent reaching it through either): a write through either is
|
|
198
|
+
seen through the other, so read what you need before writing. A remaining account
|
|
199
|
+
can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
|
|
200
|
+
with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
|
|
201
|
+
`AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
|
|
202
|
+
of a position, as Raydium CLMM's tick arrays).
|
|
203
|
+
|
|
204
|
+
## Built-ins
|
|
205
|
+
|
|
206
|
+
- `systemProgram.transfer(from, to, lamports, signerSeeds?)` (`from` is a `Mut<Signer>`, or a system-owned PDA of this
|
|
207
|
+
program, a SOL vault, with its seeds), `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
|
|
208
|
+
(the new account signs: a keypair `Mut<Signer>` or this program's PDA), `systemProgram.createPda(payer, account, space,
|
|
209
|
+
owner, seeds)` (Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: a `Mut<AccountInfo>`
|
|
210
|
+
that must be this program's PDA for `seeds` (2006), created owned by `owner`, or topped up, allocated and assigned when
|
|
211
|
+
someone funded the address first; returns the bump, records the PDA in the IDL, and among the creates a body starts
|
|
212
|
+
with runs before the constraints), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
|
|
213
|
+
- Token programs (`TokenProgram`, `Token2022Program`, `TokenInterface`) — pass `signerSeeds` (with the bump) when the authority is a PDA:
|
|
214
|
+
`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),
|
|
215
|
+
`approve(source, delegate, owner, amount)`, `revoke`, the checked forms `mintToChecked(mint, to, authority, amount)`,
|
|
216
|
+
`burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
|
|
217
|
+
come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
|
|
218
|
+
`freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
|
|
219
|
+
`initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`; and the Token Group interface: `initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize)` (a collection mint with a GroupPointer to itself; fund the rent for the group, which Token-2022 adds to the account), `initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority)`, `updateGroupMaxSize(group, authority, maxSize)`, `updateGroupAuthority(group, authority, next | null)`. Each takes optional signerSeeds
|
|
220
|
+
- `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
|
|
221
|
+
- `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
|
|
222
|
+
stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
|
|
223
|
+
among up to 256 addresses for the same seeds
|
|
224
|
+
|
|
225
|
+
## Implementing another program's interface (transfer hooks)
|
|
226
|
+
|
|
227
|
+
`/** @discriminator spl-transfer-hook-interface:execute */` above an instruction replaces its Anchor discriminator with
|
|
228
|
+
sha256(preimage)[..8] (or `@discriminator 0x…` for raw bytes), so a TypeSOL program can be a Token-2022 transfer hook:
|
|
229
|
+
`execute(source, mint, destination, owner, extraMetas, ...extraAccounts, amount)` plus
|
|
230
|
+
`initExtraAccountMetas(payer, account, mint, systemProgram, extraAccounts?)` for the validation account (an
|
|
231
|
+
ExtraAccountMetaList). Extra accounts are listed as `{ address, isSigner?, isWritable? }` (a fixed address) or
|
|
232
|
+
`{ seeds: [...], program?, isSigner?, isWritable? }` (a PDA of this program, or with `program: i` of the program at account
|
|
233
|
+
index i), with seeds from string literals, `seedAccountKey(i)`, `seedAccountData(i, offset, length)` and
|
|
234
|
+
`seedInstructionData(offset, length)`; Token-2022 resolves and checks them on every transfer. The first extra account has
|
|
235
|
+
index 5. `updateExtraAccountMetas(...)` rewrites and resizes an existing list. See `test/fixtures/hook.ts` and the
|
|
236
|
+
transfer-hook ports.
|
|
237
|
+
|
|
238
|
+
## Calling other programs
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
export function relayIncrement(authority: Signer, counter: Mut<AccountInfo>, counterProgram: Program<"JD2v…99Y2">, by: u64): void {
|
|
242
|
+
invoke(counterProgram, [readonlySigner(authority), writable(counter)], [sighash("increment"), by]);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Sign for a PDA of this program: raw System transfer (u32 tag 2, u64 lamports) out of a treasury PDA.
|
|
246
|
+
export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: Mut<SystemAccount>, systemProgram: SystemProgram, amount: u64, bump: u8): void {
|
|
247
|
+
invoke(systemProgram, [writableSigner(treasury), writable(recipient)], [u32(2n), amount], ["treasury", admin.key, bump]);
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
- program: a `Program<"address">` (key and executable checked on entry), an `UncheckedProgram`, an
|
|
252
|
+
`Address<AccountInfo, "address">` (Anchor's `#[account(address = ID)]` on an `UncheckedAccount`: only the key is
|
|
253
|
+
checked, 2012), the system or a token program, or a remaining account.
|
|
254
|
+
- accounts: `readonly(x)`, `writable(x)`, `readonlySigner(x)`, `writableSigner(x)`. The compiler refuses `writable` on a
|
|
255
|
+
non-`Mut` parameter and a signer flag on an account that neither signed nor is covered by `signerSeeds`. An optional
|
|
256
|
+
account passed as it is (`readonly(x)` / `writable(x)` with `x: A | null`, no `!`) is left out of the list when it
|
|
257
|
+
was not passed, as Rust's `if let Some(x) = &self.x { accounts.push(…) }` does.
|
|
258
|
+
- data (Borsh): integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
|
|
259
|
+
Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
|
|
260
|
+
`sighash("name")` (Anchor discriminator), `hex("0a0b")`. Up to 1024 bytes.
|
|
261
|
+
- `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
|
|
262
|
+
lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
|
|
263
|
+
- A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
|
|
264
|
+
wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
|
|
265
|
+
signer([…, bump])`.
|
|
266
|
+
- `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
|
|
267
|
+
- After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
|
|
268
|
+
A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
|
|
269
|
+
unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
|
|
270
|
+
declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106.
|
|
271
|
+
|
|
272
|
+
A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
|
|
273
|
+
`invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`):
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
invokeInstruction(transaction.programId, transaction.accounts, transaction.data, remainingAccounts(), [multisig.key, multisig.nonce]);
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
- the accounts are a list of structs with `pubkey`, `isSigner` and `isWritable` (a Vec or FixedVec in account data, a
|
|
280
|
+
Vec argument, or a stored `map` result); the data a list of u8.
|
|
281
|
+
- every account in the fourth argument (`remainingAccounts()` or a slice) is handed to the runtime, which finds each
|
|
282
|
+
meta's account there by key: one that is missing fails the call, as under Rust.
|
|
283
|
+
- the runtime checks the privileges: a meta may be a signer or writable only as the transaction passed that account,
|
|
284
|
+
or as a PDA of this program the seeds (fifth argument) sign for. See `showcase/mainnet/multisig/multisig.ts`.
|
|
285
|
+
|
|
286
|
+
Typed calls from an IDL: `typesol cpi other.json --out other_cpi.ts` writes one helper per instruction
|
|
287
|
+
(`vaultDeposit(program, owner, vault, systemProgram, amount, seeds)`), with the account flags, discriminator and
|
|
288
|
+
argument encoding taken from the IDL (Anchor 0.30+ / 1.x, or TypeSOL's own). Call it with `signer([...seeds, bump])`
|
|
289
|
+
when a PDA of your program signs, or `signer([])`. Instructions whose arguments have no Borsh-identical TypeSOL type
|
|
290
|
+
(strings or Options inside structs, data-carrying enums) are listed and left out.
|
|
291
|
+
|
|
292
|
+
## PDAs in the IDL
|
|
293
|
+
|
|
294
|
+
When an instruction calls `x.create(payer, seeds)` or `requirePda(x, seeds, bump)` and every seed is a string literal,
|
|
295
|
+
an integer literal, an argument, `acct.key` or a scalar field of an account, the IDL entry for `x` gets Anchor `pda.seeds`
|
|
296
|
+
(`const` / `arg` / `account`), so Anchor and Codama clients derive the address themselves.
|
|
297
|
+
|
|
298
|
+
## Porting a native program
|
|
299
|
+
|
|
300
|
+
A program written without Anchor (Raydium AMM v4, SPL programs) reads a tag byte and its arguments itself and takes its
|
|
301
|
+
accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-amm` and `test/fixtures/native.ts`):
|
|
302
|
+
|
|
303
|
+
- One `/** @fallback */` entry: `const data = instructionData()` gives the bytes, with `data.readU8/U16/U32/U64/U128/
|
|
304
|
+
readPubkey(offset)` (little-endian, bounds-checked: 5104); `remainingAccounts()` gives the accounts by position.
|
|
305
|
+
- Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
|
|
306
|
+
byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
|
|
307
|
+
original's own checks (an exact size, its error codes) before the load. Structs are packed, as `#[repr(C, packed)]`.
|
|
308
|
+
- Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
|
|
309
|
+
`ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
|
|
310
|
+
built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
|
|
311
|
+
reporting that location); `const PANIC_ON_OVERFLOW = true` makes arithmetic overflow and division by zero panic as
|
|
312
|
+
`checked_*().unwrap()` does instead of failing with 5100 / 5101.
|
|
313
|
+
- Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
|
|
314
|
+
"Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`);
|
|
315
|
+
`logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
|
|
316
|
+
`createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
|
|
317
|
+
|
|
318
|
+
## Not supported yet
|
|
319
|
+
|
|
320
|
+
A struct holding a FixedVec that is both an argument and account data (its bytes differ there, and the IDL describes a
|
|
321
|
+
type one way: declare one for each), growing an account by more than 10 KiB in one instruction (Solana's limit: realloc
|
|
322
|
+
again in the next instruction), `?.` and `!` on anything but optional accounts, Options and a `find` on struct elements,
|
|
323
|
+
functions stored in a struct, chosen from a list by index or returned from an instruction, a fused `map` to strings
|
|
324
|
+
(store it, annotated), floating point (by design).
|
|
325
|
+
They are rejected at compile time rather than half-supported.
|
|
326
|
+
|
|
327
|
+
`Init.create` handles a PDA address someone pre-funded: it tops up rent, then allocates and assigns instead of
|
|
328
|
+
`create_account` (which would fail).
|
|
329
|
+
|
|
330
|
+
<!-- docs/errors.md -->
|
|
331
|
+
|
|
332
|
+
# Error codes
|
|
333
|
+
|
|
334
|
+
Framework errors use Anchor's numbers where Anchor has the same check, so clients and explorers read them the same way.
|
|
335
|
+
|
|
336
|
+
| Code | Meaning |
|
|
337
|
+
| --- | --- |
|
|
338
|
+
| 100 / 101 / 102 | instruction data missing / unknown instruction / malformed arguments (InstructionMissing / FallbackNotFound / DidNotDeserialize) |
|
|
339
|
+
| 2000 | a `Mut<…>` / `Init<…>` account passed read-only (ConstraintMut) |
|
|
340
|
+
| 2001 | HasOne constraint failed (ConstraintHasOne) |
|
|
341
|
+
| 2002 | a `Signed<…>` account (or the event authority) did not sign (ConstraintSigner) |
|
|
342
|
+
| 2003 | a `constraint(acct, condition)` without its own error failed (ConstraintRaw) |
|
|
343
|
+
| 2004 | Owner constraint failed (ConstraintOwner) |
|
|
344
|
+
| 2005 | Zeroed account is not rent-exempt (ConstraintRentExempt) |
|
|
345
|
+
| 2006 | PDA seeds mismatch (ConstraintSeeds) |
|
|
346
|
+
| 2007 | Executable constraint failed (ConstraintExecutable) |
|
|
347
|
+
| 2009 | not the associated token account (ConstraintAssociated) |
|
|
348
|
+
| 2012 | not the expected address (ConstraintAddress) |
|
|
349
|
+
| 2013 | a `Zeroed<…>` account whose discriminator is already set (ConstraintZero; checked before its owner, as under Anchor) |
|
|
350
|
+
| 2014 / 2015 | token account mint / owner mismatch (ConstraintTokenMint / ConstraintTokenOwner) |
|
|
351
|
+
| 2016 / 2017 / 2018 | mint authority / freeze authority / decimals mismatch (2018: an existing mint `createIfNeeded` found) |
|
|
352
|
+
| 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
|
|
353
|
+
| 2024–2039 | an existing mint `createIfNeeded` found lacks a Token-2022 extension it was given, or holds other keys in it: group pointer 2024–2026, group member pointer 2027–2029, metadata pointer 2030–2032, close authority 2033–2034, permanent delegate 2035–2036, transfer hook 2037–2039 (the first code of each: the extension is missing; the next: the authority / address differs) (ConstraintMint…Extension…) |
|
|
354
|
+
| 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
|
|
355
|
+
| 0 (from the System Program) | an `Init` / `create` on an address already in use (AccountAlreadyInUse): the System Program refuses it, as under Anchor's `init` |
|
|
356
|
+
| 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
|
|
357
|
+
| 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
|
|
358
|
+
| 3002 | discriminator mismatch (AccountDiscriminatorMismatch) |
|
|
359
|
+
| 3003 | data too small, not an initialized token account / mint, a read past the end, or a `@layout borsh` account whose bytes are not a valid Borsh value (AccountDidNotDeserialize) |
|
|
360
|
+
| 3004 | a `@layout borsh` account too small for the value it would now hold (AccountDidNotSerialize) |
|
|
361
|
+
| 3005 | not enough accounts (AccountNotEnoughKeys) |
|
|
362
|
+
| 3006 | a remaining account or CPI account the program needs writable was passed read-only (AccountNotMutable) |
|
|
363
|
+
| 3007 | wrong owner program (AccountOwnedByWrongProgram) |
|
|
364
|
+
| 3008 / 3009 | wrong program address / not executable (InvalidProgramId / InvalidProgramExecutable) |
|
|
365
|
+
| 3010 | account must sign (AccountNotSigner; also a new keypair account a `create(payer, null, …)` makes) |
|
|
366
|
+
| 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
|
|
367
|
+
| 3012 | account not initialized: empty system account where a program account, a token account or a mint was expected (AccountNotInitialized; not for zero-copy accounts, which Anchor's AccountLoader reports as 3007) |
|
|
368
|
+
| 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
|
|
369
|
+
| 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
|
|
370
|
+
| 4102 | cast overflow (InvalidNumericConversion) |
|
|
371
|
+
| 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
|
|
372
|
+
| 5103 | sysvar unavailable |
|
|
373
|
+
| 5104 | index out of bounds (arrays, Vecs, remaining accounts, `pop()` on an empty Vec, `push` on a full FixedVec, a stored `map` / `filter` result one element too small) |
|
|
374
|
+
| 5105 | string longer than the FixedString capacity |
|
|
375
|
+
| 5106 | missing or mismatched return data |
|
|
376
|
+
| 5107 | event larger than 1024 bytes |
|
|
377
|
+
| 5108 | empty Option used as a value |
|
|
378
|
+
| 5110 | out of heap building strings |
|
|
379
|
+
| 5111 | oracle check failed (unverified, stale, wrong feed, no samples) |
|
|
380
|
+
| 5112 | data enum is not the variant the code expected |
|
|
381
|
+
| 5113 | more accounts in one instruction (or one CPI) than the program takes: 32, or its `MAX_ACCOUNTS` |
|
|
382
|
+
| 5114 | a function with a result ended without returning one |
|
|
383
|
+
| 5115 | an optional account that was left out was used |
|
|
384
|
+
| 6000+ | your error enums' members, in declaration order (imported files first), then one `RequireFailed<N>` error (code 6000 + N, after the highest code) per distinct `require(cond, "message")` string |
|
|
385
|
+
|
|
386
|
+
A member's string is its message (the IDL's `msg`); `X = ""` leaves the message out, as an Anchor variant without
|
|
387
|
+
`#[msg]`. `/** @code 6200 */` before a member gives it that code, and the members after it continue from there (Anchor's
|
|
388
|
+
`Variant = 200`); codes only go up. `require(cond, "message")` errors come after the highest code.
|
|
389
|
+
|
|
390
|
+
Any of Anchor's own codes can be raised directly: `require(cond, AnchorError.RequireKeysEqViolated)` fails with 2502,
|
|
391
|
+
as `require_keys_eq!` does.
|
|
392
|
+
|
|
393
|
+
A code can also be computed at run time: `require(cond, code)` with a `u32` value fails with that code. This is how a
|
|
394
|
+
helper passes an error on as Rust's `?` does, when it returns the error as a value instead of failing (a price read
|
|
395
|
+
whose error the caller may record or ignore): `const r = price(feed); require(r.err === 0n, r.err);`. The code is
|
|
396
|
+
reported as it is (use one of your errors' codes, so clients can decode it); a zero code fails with 5100.
|
|
397
|
+
|
|
398
|
+
## Which error a transaction gets
|
|
399
|
+
|
|
400
|
+
A transaction can break several checks; it fails with the first. Within each account's constraints the checks run in
|
|
401
|
+
the order Anchor's generated code runs them, so a transaction gets the same code under both:
|
|
402
|
+
|
|
403
|
+
1. The account count (3005), then each account in parameter order: its type, signer (3010), `Mut` (2000), owner,
|
|
404
|
+
discriminator and size of a program account (3007 / 3012 / 3002 / 3003; a zero-copy one as Anchor's AccountLoader:
|
|
405
|
+
3007 / 3001 / 3002, then 3003), token account or mint, program address.
|
|
406
|
+
2. Two writable parameters naming one account (2040).
|
|
407
|
+
3. The instruction's arguments (102).
|
|
408
|
+
4. Each account in parameter order, its constraints in Anchor's order: seeds (2006), associated token account (owner
|
|
409
|
+
2015, then address 2009), `has_one` (2001), `constraint(…)` (2003 or its error), owner (2004), executable (2007), address (2012), then `TokenOf` /
|
|
410
|
+
`MintOf` (2015, 2014, 2021 / 2016, 2017, 2022).
|
|
411
|
+
|
|
412
|
+
Where TypeSOL's order differs, only a transaction that breaks two of these checks at once sees it:
|
|
413
|
+
|
|
414
|
+
- Anchor decodes the arguments first, and checks `mut` with the constraints (after seeds and the associated token
|
|
415
|
+
account). TypeSOL keeps both earlier and later as above, which keeps binaries smaller.
|
|
416
|
+
- Too few accounts fails with 3005 before any account is checked; Anchor fails on the first account it cannot find.
|
|
417
|
+
- Accounts the instruction creates (`Init<…>`, `create(…)`) are created in the body, after every other check, where
|
|
418
|
+
Anchor creates them before checking the other accounts.
|
|
419
|
+
- TypeSOL refuses any two writable parameters naming one account (2040) unless one is `Dup<…>`, where Anchor only compares program and token
|
|
420
|
+
accounts: a signer passed as two writable parameters fails with 2040 here and later, or not at all, under Anchor.
|
|
421
|
+
|
|
422
|
+
<!-- docs/test-your-program.md -->
|
|
423
|
+
|
|
424
|
+
# Test your program
|
|
425
|
+
|
|
426
|
+
`typesol/testing` runs your program in LiteSVM, an in-process Solana runtime: no validator, no SOL, a few
|
|
427
|
+
milliseconds per transaction. Projects from `typesol init` already use it in `tests/<name>.test.ts`.
|
|
428
|
+
|
|
429
|
+
```ts
|
|
430
|
+
import { testProgram, type TestProgram } from "typesol/testing";
|
|
431
|
+
import { beforeAll, expect, it } from "vitest";
|
|
432
|
+
|
|
433
|
+
let t: TestProgram;
|
|
434
|
+
beforeAll(async () => {
|
|
435
|
+
t = await testProgram("counter", import.meta.url); // builds the program of typesol.json and loads it
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
it("counts", async () => {
|
|
439
|
+
const alice = await t.wallet(); // a funded keypair (10 SOL)
|
|
440
|
+
const counter = await t.pda("counter", alice); // seeds: text, addresses or keypairs, bytes, bigints (u64)
|
|
441
|
+
t.ok(await t.send(alice, t.ix("initialize", {}, { authority: alice, counter })));
|
|
442
|
+
t.ok(await t.send(alice, t.ix("increment", { by: 5n }, { authority: alice, counter })));
|
|
443
|
+
expect((await t.account<{ count: bigint }>("Counter", counter))?.count).toBe(5n);
|
|
444
|
+
});
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
## Instructions
|
|
448
|
+
|
|
449
|
+
`t.pda(...seeds)` derives this program's PDA for the seeds; `t.pdaWithBump(...seeds)` gives `[address, bump]`, for an
|
|
450
|
+
instruction that takes the bump as an argument.
|
|
451
|
+
|
|
452
|
+
`t.ix(name, args, accounts, remaining?)` builds one instruction.
|
|
453
|
+
|
|
454
|
+
- **Accounts by name**, in camelCase or snake_case. Their signer and writable flags come from the IDL, and accounts
|
|
455
|
+
with a fixed address (the System Program, token programs, sysvars) are filled in, as are PDAs whose seeds are
|
|
456
|
+
constants, arguments or other accounts' keys (`t.ix("initialize", {}, { authority: alice })` derives `counter`). Pass a keypair for an account that
|
|
457
|
+
signs, an address otherwise, and `null` to leave an optional account out.
|
|
458
|
+
- **Arguments as plain values:** bigints or numbers for integers, address strings for Pubkeys, `null` for an empty
|
|
459
|
+
Option, objects for structs (camelCase or snake_case fields), arrays for Vecs.
|
|
460
|
+
- **Remaining accounts:** `[{ address, writable?, signer? }]`, where `signer` is the account's `KeyPairSigner` (it then
|
|
461
|
+
signs as a signer account; `writable` defaults to false).
|
|
462
|
+
|
|
463
|
+
`t.send(payer, ...ixs)` sends them in one transaction; keypairs given as accounts sign too.
|
|
464
|
+
|
|
465
|
+
## Results
|
|
466
|
+
|
|
467
|
+
| Helper | Gives |
|
|
468
|
+
| --- | --- |
|
|
469
|
+
| `t.ok(res)` | the successful result, or throws with the error, its name (`NotAdmin`) and the program's logs |
|
|
470
|
+
| `t.errorCode(res)` | the custom error code of a failed transaction: 6000 + the member's index in your error enum, or a framework code ([errors.md](errors.md)) |
|
|
471
|
+
| `t.account(type, address)` | the account decoded by its IDL type (bigints, address strings), or `null` once closed. TypeSOL fixed layouts come back as their IDL structs: a `FixedString<N>` as `{ len, bytes }`, a `FixedVec<T, N>` as `{ len, items }` (the generated client gives strings and arrays) |
|
|
472
|
+
| `t.returned(instruction, res)` | the instruction's return data: an integer, boolean, Pubkey or struct |
|
|
473
|
+
| `t.balance(address)` | lamports |
|
|
474
|
+
| `t.errorName(code)` | the name of an error code: your program's, TypeSOL's or Anchor's |
|
|
475
|
+
| `t.connection` | `{ rpc, rpcSubscriptions }` answered by this LiteSVM, for the generated client: `counter.sendInstructions(t.connection, alice, [ix])`, `counter.accounts.Counter.fetch(t.connection.rpc, address)`, views, `resolve`, `watch` and `watchEvents` (as on a cluster: `watch` yields when a later transaction changes the account, not at once; `watchEvents` gets transactions sent after it subscribed, failed ones included in the stream and skipped by the client) |
|
|
476
|
+
|
|
477
|
+
## Tokens and time
|
|
478
|
+
|
|
479
|
+
| Helper | Does |
|
|
480
|
+
| --- | --- |
|
|
481
|
+
| `t.mint({ authority, decimals?, supply?, freezeAuthority?, tokenProgram?, address? })` | writes a mint straight into the VM, as CreateAccount + InitializeMint2 leave it (SPL Token unless `tokenProgram` is Token-2022; no extensions), and returns its address |
|
|
482
|
+
| `t.tokenAccount({ mint, owner, amount?, tokenProgram?, address? })` | writes a token account holding `amount`; pass `address` for an associated token account |
|
|
483
|
+
| `t.tokenBalance(address)` | the amount a token account holds, or `null` when it does not exist |
|
|
484
|
+
| `t.warp({ unixTimestamp?, slot?, seconds? })` | moves the Clock: to a timestamp or slot, or forward by `seconds` |
|
|
485
|
+
|
|
486
|
+
## Accounts from a cluster
|
|
487
|
+
|
|
488
|
+
To test against accounts that exist on mainnet (a mint, an oracle, another program), list them in `typesol.json` as
|
|
489
|
+
`"clone": ["<address>", …]` and run `typesol clone --url mainnet-beta` once (or `typesol clone <address>…`). They are
|
|
490
|
+
written to `tests/accounts/`, which `testProgram` loads into its LiteSVM before your first test; commit the directory so
|
|
491
|
+
the tests run offline. `loadClonedAccounts(svm, dir)` does the same for a LiteSVM of your own.
|
|
492
|
+
|
|
493
|
+
`t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else. `programHarness(svm, programId, idl)` gives the same helpers for a
|
|
494
|
+
program you loaded yourself, and `svmConnection(svm)` the RPC pair alone (for any LiteSVM, e.g. one with an Anchor
|
|
495
|
+
program loaded). Transactions sent through it run at once; `getProgramAccounts` (`fetchAll`) sees the accounts those
|
|
496
|
+
transactions named, plus any you `track(...)`.
|
|
497
|
+
|
|
498
|
+
The module needs `litesvm` and `@anchor-lang/core`, which `typesol init` adds to `devDependencies`.
|
|
499
|
+
|
|
500
|
+
<!-- docs/cli.md -->
|
|
501
|
+
|
|
502
|
+
# CLI reference
|
|
503
|
+
|
|
504
|
+
`typesol <command> --help` prints the same text for one command. Options are checked: an unknown option is an
|
|
505
|
+
error. Exit codes: **0** success, **1** failure (compile errors, failed deploy, …), **2** usage error,
|
|
506
|
+
**3** `verify` mismatch.
|
|
507
|
+
|
|
508
|
+
| Command | What it does |
|
|
509
|
+
| --- | --- |
|
|
510
|
+
| `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin), `.vscode/settings.json` (the workspace TypeScript, so the plugin loads) and `.gitignore`. `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
|
|
511
|
+
| `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name. |
|
|
512
|
+
| `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools, the Solana CLI, its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
|
|
513
|
+
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. |
|
|
514
|
+
| `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. A project program's `.ts` builds as that program. |
|
|
515
|
+
| `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
|
|
516
|
+
| `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
|
|
517
|
+
| `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
|
|
518
|
+
| `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …]` | Build, then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. Before sending anything it checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
|
|
519
|
+
| `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`). |
|
|
520
|
+
| `typesol cpi <idl.json> [--out <file.ts>] [--prefix <name>] [--address <base58>]` | Generate TypeSOL helpers that call another program from its IDL. Unsupported instructions are listed on stderr. |
|
|
521
|
+
| `typesol port <idl.json> [--out <file.ts>]` | A TypeSOL program skeleton from an Anchor IDL (0.30+/1.x), to port an Anchor program: account structs, enums, errors, events and one function per instruction with its accounts and arguments, each body `require(false, …NotPorted)` until written. Instruction discriminators (an explicit `@discriminator` when the name derives another), account names and error codes are kept, so existing clients keep working where the layouts match; notes on stderr list where they do not (Borsh `String`/`Option` in account data, a `Vec` that is not the last field). Error codes that skip ahead are kept with `@code`, and zero-copy types keep their IDL `repr`, `serialization` and field names (`@repr`, `@serialization`, `@idlName`). |
|
|
522
|
+
| `typesol client <idl.json> [--out <file.ts>] [--address <base58>]`, `typesol client --address <program id> [--url <rpc>] [--config <cli config>] [--out <file.ts>]` | Generate a typed TypeScript client on `@solana/kit` from an Anchor IDL (0.30+/1.x or TypeSOL); the IDL is validated first, and what the client leaves out is printed as notes. Without a file, the IDL is read from the chain: the canonical Program Metadata IDL, else Anchor's IDL account. See [client.md](client.md). |
|
|
523
|
+
| `typesol verify <program\|file.ts> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <cli config>] [--sbpf …]` | Rebuild and compare with what is deployed. Without a `.so`, reads the program from the cluster (`--url`, cluster monikers such as `mainnet-beta` included, else the Solana CLI config) at `--address` or the address `typesol.json` records, under any loader (v2, upgradeable v3, v4); prints the upgrade authority (or that the program is immutable) and the last deploy slot, and compares the IDL published with `typesol idl publish` (a published IDL that differs is a mismatch). With a `.so` (e.g. `solana program dump`), compares with that file. Trailing zero padding is ignored; the SBPF version is read from the deployed ELF unless `--sbpf` is given. |
|
|
524
|
+
| `typesol profile <logs.txt\|-> [--program <id>]` | Compute units per TypeScript line from the logs of a `--profile` build's transaction (exit 1 when the logs have no markers). |
|
|
525
|
+
| `typesol help <command>` | Same as `typesol <command> --help`. |
|
|
526
|
+
| `typesol --version` | Print the version. |
|
|
527
|
+
|
|
528
|
+
## typesol.json
|
|
529
|
+
|
|
530
|
+
```json
|
|
531
|
+
{
|
|
532
|
+
"programs": { "vault": { "path": "programs/vault.ts", "address": "…recorded on first build…" } },
|
|
533
|
+
"out": "target",
|
|
534
|
+
"sbpf": "v0"
|
|
535
|
+
}
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
`"clone": ["<address>", …]` lists the cluster accounts `typesol clone` copies for the tests, and `"accounts"` where
|
|
539
|
+
they are kept (default `tests/accounts`). `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
|
|
540
|
+
safe and out of git: it is the program's address, and it is needed to deploy it again. A clone without
|
|
541
|
+
it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
|
|
542
|
+
|
|
543
|
+
## Editor
|
|
544
|
+
|
|
545
|
+
`typesol init` projects load `typesol/ts-plugin` from `programs/tsconfig.json`: besides TypeScript's errors, the editor
|
|
546
|
+
underlines what the TypeSOL compiler refuses (an unsupported construct, a constraint that cannot hold…), for the text
|
|
547
|
+
being edited (unsaved changes in every open file), once TypeScript itself has nothing to report. It checks the program
|
|
548
|
+
entries listed in `typesol.json` and shows each problem in the file it is in, the entry or any file it imports. The
|
|
549
|
+
compiler runs inside the editor's TypeScript server once it has loaded (a check takes milliseconds; the first ones run
|
|
550
|
+
`typesol check --json --files` as a child process). Editors load tsconfig plugins from the project's own TypeScript:
|
|
551
|
+
`typesol init` writes `.vscode/settings.json` so VS Code offers to switch to it ("Use Workspace Version"). To add the
|
|
552
|
+
plugin to an existing project:
|
|
553
|
+
|
|
554
|
+
```json
|
|
555
|
+
{ "compilerOptions": { "plugins": [{ "name": "typesol/ts-plugin" }] } }
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
<!-- docs/client.md -->
|
|
559
|
+
|
|
560
|
+
# TypeScript client
|
|
561
|
+
|
|
562
|
+
Every `typesol build` writes a typed client next to the program: `<out>/<name>/<name>.client.ts`. It is one file, it
|
|
563
|
+
depends only on [`@solana/kit`](https://github.com/anza-xyz/kit) (8.5 or later), and it is rewritten on every build, so
|
|
564
|
+
it always matches the program. `typesol client <idl.json>` writes the same kind of client from an Anchor IDL (Anchor 0.30+
|
|
565
|
+
and 1.x), so one client style covers TypeSOL programs and the Anchor programs they talk to. `typesol client --address
|
|
566
|
+
<program id> --url <rpc>` reads the IDL from the chain instead: the canonical Program Metadata IDL (`typesol idl
|
|
567
|
+
publish`, Codama), else Anchor's IDL account (`anchor idl init`), so any deployed Anchor or TypeSOL program with a
|
|
568
|
+
published IDL gets a client from its address alone.
|
|
569
|
+
|
|
570
|
+
```ts
|
|
571
|
+
import { ledgerbook } from "./target/ledgerbook/ledgerbook.client.js";
|
|
572
|
+
|
|
573
|
+
// Instructions: fixed addresses (System Program, token programs, ...) and PDAs are filled in from the IDL.
|
|
574
|
+
const create = await ledgerbook.create({ admin: signer }, { title: "grants", approver: null });
|
|
575
|
+
|
|
576
|
+
// PDAs
|
|
577
|
+
const [book] = await ledgerbook.pdas.book({ admin: signer.address, title: "grants" });
|
|
578
|
+
const file = await ledgerbook.file({ who: signer, book }, { amount: 100n, note: "rent", memo: null });
|
|
579
|
+
|
|
580
|
+
// Accounts: decode bytes you already have, or fetch through an RPC.
|
|
581
|
+
const bookData = await ledgerbook.accounts.Book.fetch(rpc, book); // { title: string, approver: Address | null, entries: [...], ... }
|
|
582
|
+
|
|
583
|
+
// Send and confirm (one transaction, signers in the accounts sign too), or simulate
|
|
584
|
+
const signature = await ledgerbook.sendInstructions({ rpc, rpcSubscriptions }, signer, [create, file]);
|
|
585
|
+
const { err, logs, unitsConsumed, returnData } = await ledgerbook.simulate(rpc, signer, [file]);
|
|
586
|
+
|
|
587
|
+
// Errors: by name, from a kit SolanaError, a LiteSVM result, a simulation message or a code.
|
|
588
|
+
if (ledgerbook.isError(e, "NotApprover")) { /* ... */ }
|
|
589
|
+
ledgerbook.errorCode(e); // 6002
|
|
590
|
+
|
|
591
|
+
// Events written by `emit`, from a transaction's log messages
|
|
592
|
+
for (const ev of ledgerbook.parseEvents(logs)) if (ev.name === "Filed") ev.data.amount;
|
|
593
|
+
|
|
594
|
+
// Return data of an instruction that returns a value, or the value itself by simulation (Anchor's `.view()`)
|
|
595
|
+
ledgerbook.returns.total(returnDataBytes); // bigint
|
|
596
|
+
await ledgerbook.views.total(rpc, signer, { book }, { status: Status.Approved }); // bigint, nothing sent
|
|
597
|
+
|
|
598
|
+
// Every Book of the program, or those with given bytes at an offset (after the 8-byte discriminator)
|
|
599
|
+
const books = await ledgerbook.accounts.Book.fetchAll(rpc); // [{ address, data }]
|
|
600
|
+
const several = await ledgerbook.accounts.Book.fetchMultiple(rpc, [book, otherBook]); // (Book | null)[]
|
|
601
|
+
|
|
602
|
+
// Live updates, until the AbortSignal aborts
|
|
603
|
+
for await (const book of ledgerbook.accounts.Book.watch(rpcSubscriptions, address, { abortSignal })) render(book);
|
|
604
|
+
for await (const { signature, event } of ledgerbook.watchEvents(rpcSubscriptions, { abortSignal, rpc })) show(event); // with rpc: emitCpi events too
|
|
605
|
+
|
|
606
|
+
// Remaining accounts go after the instruction's own (Anchor's `.remainingAccounts([...])`)
|
|
607
|
+
await ledgerbook.approveMany({ approver: signer, book }, { indices: [0n, 1n] }, [{ address: extra, role: AccountRole.WRITABLE }]);
|
|
608
|
+
|
|
609
|
+
// has_one accounts that do not sign, read from the account that names them (Anchor resolves `relations` the same way)
|
|
610
|
+
const accounts = await ledgerbook.resolve.someInstruction(rpc, { book }, { signer }); // signers, and what book's fields name
|
|
611
|
+
|
|
612
|
+
// Events of a fetched transaction (getTransaction, json): log events and emitCpi events from inner instructions
|
|
613
|
+
ledgerbook.eventsOf(await rpc.getTransaction(signature, { encoding: "json", maxSupportedTransactionVersion: 0 }).send());
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
Signer accounts take a `TransactionSigner`, which kit uses to sign; an `Address` works too when you sign separately.
|
|
617
|
+
Kit's own transaction functions work with the instructions as well; `sendInstructions` is that pipeline in one call.
|
|
618
|
+
|
|
619
|
+
## What the client contains
|
|
620
|
+
|
|
621
|
+
| | |
|
|
622
|
+
| --- | --- |
|
|
623
|
+
| `<program>.<instruction>(accounts, args)` | Builds the `Instruction`. Accounts with a fixed address and PDAs whose seeds are constants, arguments (an Option one with its default too: Anchor's `id.unwrap_or(0)`) or other accounts' keys are optional and filled in; pass one to override. An optional account passed as `null` is left out (sent as the program id, the convention TypeSOL and Anchor share); left undefined, it is filled in like any other. |
|
|
624
|
+
| `<program>.<instruction>(accounts, args, remaining?)` | The same, with remaining accounts appended in order (kit `AccountMeta`s). |
|
|
625
|
+
| `<program>.accounts.<Name>` | `decode(bytes)`, `encode(value)`, `fetch(rpc, address)`, `fetchMaybe(rpc, address)`, `fetchMultiple(rpc, addresses)`, `fetchAll(rpc, filters?)` (getProgramAccounts by discriminator, plus `{ offset, bytes }` filters), `watch(rpcSubscriptions, address, { abortSignal })`, `discriminator`. `decode` checks the discriminator. |
|
|
626
|
+
| `<program>.pdas.<account>(seeds)` | The PDA (address and bump) for each account an instruction derives, also one seeded from its own fields (from the field values). |
|
|
627
|
+
| `<program>.returns.<instruction>(bytes)` | Decodes return data. |
|
|
628
|
+
| `<program>.resolve.<instruction>(rpc, accounts, args?, { signer? })` | Fills in what needs the chain or the wallet: signer accounts left out (`options.signer`, the default signer, like Anchor's provider wallet), `has_one` accounts that do not sign (read from the account that names them), and PDAs seeded from another account's fields, scalars, strings or bytes (`seeds = [b"vault", book.owner]`: the account is read, then the PDA derived). Given accounts are kept. |
|
|
629
|
+
| `<program>.views.<instruction>(rpc, feePayer, accounts, args)` | Simulates an instruction that returns a value and decodes it (throws with the logs if it fails). |
|
|
630
|
+
| `<program>.sendInstructions(connection, feePayer, instructions)`, `simulate(rpc, feePayer, instructions)` | One transaction sent and confirmed (kit's sendAndConfirm), or simulated without signatures (error, logs, units, this program's return data). |
|
|
631
|
+
| `<program>.errors`, `errorCode(e)`, `isError(e, name)` | The program's errors (6000+), and for TypeSOL programs also every Anchor framework error (`AnchorError` and the constraints raise them) and TypeSOL's runtime errors. |
|
|
632
|
+
| `<program>.parseEvents(logs)`, `parseCpiEvents(data)`, `eventsOf(tx)`, `watchEvents(rpcSubscriptions, { abortSignal })` | Events from `Program data:` log lines, from `emitCpi` inner instructions (bytes or base58), from a fetched transaction (both), or live from log subscriptions. |
|
|
633
|
+
| Types and codecs | Every defined type as a TypeScript type (`Book`, the decoded value) and an input type (`BookArgs`, which also accepts `number` for 64- and 128-bit integers), with a kit codec (`getBookCodec()`). |
|
|
634
|
+
|
|
635
|
+
Types follow the program's TypeScript: `u64`/`i64`/`u128`/`i128` are `bigint` (inputs accept `number` too), smaller
|
|
636
|
+
integers and floats are `number`, `Pubkey` is kit's `Address`, `string` and `FixedString<N>` are `string`, `Option<T>` is
|
|
637
|
+
`T | null`, unit enums are const objects (`Status.Pending`, also usable as a type), and data enums are unions on `kind`,
|
|
638
|
+
as in the program. Names are camelCase. For Anchor IDLs, data enums use `__kind`, as Codama-generated clients do. The
|
|
639
|
+
file uses no TypeScript-only syntax (no `enum`), so it also runs under Node's type stripping.
|
|
640
|
+
|
|
641
|
+
## Safety
|
|
642
|
+
|
|
643
|
+
An IDL can come from anywhere, so `typesol client` refuses one whose names are not identifiers, whose discriminators or
|
|
644
|
+
seed bytes are not bytes, or whose error codes are not integers, before anything reaches the output. Older (pre-0.30)
|
|
645
|
+
Anchor IDLs are refused with a hint to convert them (`anchor idl convert`).
|
|
646
|
+
|
|
647
|
+
## Limits
|
|
648
|
+
|
|
649
|
+
- **Errors are matched by code, not by program**: a program this one calls can raise the same error code. Events are
|
|
650
|
+
this program's own: `parseEvents` follows the `Program <id> invoke` / `success` / `failed` lines and reads a
|
|
651
|
+
`Program data:` line only while this program is the innermost one running, and `eventsOf` reads only the `emitCpi`
|
|
652
|
+
inner instructions that call this program (it needs `tx.transaction`'s account keys for that). `parseCpiEvents(data)`
|
|
653
|
+
on its own does not check the program: give it this program's inner instructions only.
|
|
654
|
+
- **Not filled in automatically** (pass them): PDAs seeded from struct fields (Anchor cannot seed with them either),
|
|
655
|
+
PDAs whose program is another account's field, and a PDA seeded from its own fields (derive it with its `pdas`
|
|
656
|
+
helper from the values). `typesol client` prints a note for each.
|
|
657
|
+
- **Anchor IDLs**: zero-copy (`bytemuck`) accounts decode and encode at their `#[repr(C)]` offsets as the program sees
|
|
658
|
+
them on SBF (padding included; `packed` and `align` honored; 128-bit integers align to 8). Generic types become one
|
|
659
|
+
type per use with concrete arguments (`Pair<u64, 2>` is `PairU64N2`). Left out, with a note: zero-copy types with
|
|
660
|
+
Rust's own layout (`repr(Rust)`) or holding a non-zero-copy type, and the generic definitions themselves.
|
|
661
|
+
- **In tests**: `svmConnection(svm)` from `typesol/testing` answers the client's RPC calls from LiteSVM, and
|
|
662
|
+
`testProgram(...)` has it as `t.connection` ([test-your-program.md](test-your-program.md)).
|
|
663
|
+
- `watchEvents` reads log events of transactions that succeeded (a failed one is skipped); with `rpc` it also fetches each transaction in which the program invoked itself and
|
|
664
|
+
reads its `emitCpi` events (log subscriptions do not carry inner instructions).
|
|
665
|
+
|
|
666
|
+
<!-- docs/migrate-from-anchor.md -->
|
|
667
|
+
|
|
668
|
+
# Migrate from Anchor
|
|
669
|
+
|
|
670
|
+
TypeSOL programs speak Anchor's wire format: the same instruction and account discriminators, Borsh arguments, an
|
|
671
|
+
Anchor-format IDL, the same error numbering and event logs. A ported program can keep its clients. This page maps
|
|
672
|
+
Anchor's constructs to TypeSOL's and shows the porting workflow. For one complete program ported this way, with the
|
|
673
|
+
original side by side, the checks run against it and its cost, see [Case study: porting Anchor's escrow](case-study-escrow.md).
|
|
674
|
+
|
|
675
|
+
## Start from the IDL
|
|
676
|
+
|
|
677
|
+
```sh
|
|
678
|
+
anchor build # in the Anchor project: target/idl/my_program.json
|
|
679
|
+
npx @typesol/cli init my-program && cd my-program
|
|
680
|
+
rm programs/my_program.ts tests/my_program.test.ts # the counter template's program and test
|
|
681
|
+
npx typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
`typesol port` writes the account structs, enums, errors and one function per instruction with its accounts and
|
|
685
|
+
arguments, each body failing with `NotPorted` until you write it. It keeps instruction discriminators, account names
|
|
686
|
+
and error codes. Its notes (on stderr) list what an existing Anchor client would see differently; see
|
|
687
|
+
[Account data](#account-data) below. Then, for each instruction:
|
|
688
|
+
|
|
689
|
+
1. Give each account its real type: `Account<T>` / `Mut<T>` for your structs, `Init<T>` for one the instruction creates,
|
|
690
|
+
token types for token accounts (the table below).
|
|
691
|
+
2. Move the constraints from `#[account(...)]` into the parameter types or the body.
|
|
692
|
+
3. Port the body. Integers are `bigint`s with `n` literals, and every `+ - * / %` is checked.
|
|
693
|
+
4. Test with `typesol/testing` ([test your program](test-your-program.md)), then compare the IDLs.
|
|
694
|
+
|
|
695
|
+
## Accounts and constraints
|
|
696
|
+
|
|
697
|
+
| Anchor | TypeSOL |
|
|
698
|
+
| --- | --- |
|
|
699
|
+
| `#[derive(Accounts)] struct Ctx` + `ctx.accounts.x` | the instruction's parameters, in the same order |
|
|
700
|
+
| a composite field, `pub pool: PoolAccounts<'info>` + `ctx.accounts.pool.vault` | an account group: `export interface PoolAccounts { vault: Mut<TokenAccount>; … }`, the parameter `pool: PoolAccounts`, and `pool.vault` |
|
|
701
|
+
| `Signer<'info>` / `#[account(mut)] Signer` | `Signer` / `Mut<Signer>` |
|
|
702
|
+
| `Account<'info, T>` / `#[account(mut)]` | `Account<T>` / `Mut<T>` |
|
|
703
|
+
| `#[account(init, payer = p, space = …, seeds = […], bump)]` | `Init<T>`, then `const bump = acct.create(p, ["seed", other.key])` (space is computed; `acct.create(p, […], 8n + 64n)` keeps an explicit `space`) |
|
|
704
|
+
| `#[account(init, payer = p, space = …)]` (a keypair account) | `Init<T>`, then `acct.create(p, null)` (the account signs the transaction, as in Anchor) |
|
|
705
|
+
| `init_if_needed` | `InitIfNeeded<T>`, then `const created = acct.createIfNeeded(p, seeds)` |
|
|
706
|
+
| `seeds = [b"vault", owner.key().as_ref()], bump = vault.bump` | `Seeds<Mut<Vault>, ["vault", "@owner"], "bump">` |
|
|
707
|
+
| `seeds = [b"offer", offer.maker.as_ref(), offer.id.to_le_bytes().as_ref()]` | `Seeds<…, ["offer", "@offer.maker", "@offer.id"], "bump">` |
|
|
708
|
+
| `has_one = owner` | `HasOne<Mut<T>, "owner">` |
|
|
709
|
+
| `has_one = owner @ ErrorCode::NotOwner` (also `address`, `owner`, `signer`, `mut` with `@ …`) | `HasOne<Mut<T>, "owner", ErrorCode.NotOwner>`; `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` |
|
|
710
|
+
| `close = destination` | `CloseTo<Mut<T>, "destination">`, or `close(acct, destination)` in the body |
|
|
711
|
+
| `address = ADMIN` | `Address<AccountInfo, "Admin1111…">` |
|
|
712
|
+
| `owner = program`, `executable` | `Owner<A, "…">`, `Executable<A>` |
|
|
713
|
+
| `constraint = expr @ MyError::X` (or without an error: 2003) | `constraint(acct, expr, MyError.X)` (or `constraint(acct, expr)`) at the start of the body: it runs with `acct`'s checks, where Anchor runs it |
|
|
714
|
+
| `realloc = n, realloc::payer = p` | `realloc(acct, n, p)` |
|
|
715
|
+
| `Option<Account<'info, T>>` | `Mut<T> \| null` (the client passes the program id to leave it out) |
|
|
716
|
+
| `UncheckedAccount` / `AccountInfo` | `AccountInfo` / `Mut<AccountInfo>`: check what you rely on yourself |
|
|
717
|
+
| `SystemAccount<'info>` | `SystemAccount` / `Mut<SystemAccount>` |
|
|
718
|
+
| `Migration<'info, From, To>` | `Migrate<From, To>`, then `acct.migrate(payer, value)`; the old struct keeps its on-chain discriminator with `/** @discriminator account:<OldName> */` |
|
|
719
|
+
| `#[account(discriminator = …)]` | `/** @discriminator <preimage or 0x8 bytes> */` on the struct |
|
|
720
|
+
| `AccountLoader<T>` with `#[account(zero)]` | `Zeroed<T>` (TypeSOL reads every account in place: no copy to avoid) |
|
|
721
|
+
| `Account<T>` with `#[account(zero)]` (Borsh) | `Zeroed<T>` of a `/** @layout borsh */` struct |
|
|
722
|
+
| `#[account(signer)]` on a non-`Signer` account | `Signed<A>`, e.g. `Signed<Zeroed<Multisig>>` |
|
|
723
|
+
| `seeds = [multisig.key().as_ref()], bump = multisig.nonce` | `Seeds<A, ["@multisig"], "@multisig.nonce">` |
|
|
724
|
+
| `Program<'info, System>` | `SystemProgram` |
|
|
725
|
+
| `Program<'info, Token>` / `Token2022` / `Interface<'info, TokenInterface>` | `TokenProgram` / `Token2022Program` / `TokenInterface` |
|
|
726
|
+
| `Account<'info, TokenAccount>` / `Account<'info, Mint>` (`InterfaceAccount`) | `TokenAccount` / `Mint` (`Mut<…>` when written) |
|
|
727
|
+
| `token::mint = m, token::authority = a` | `TokenOf<TokenAccount, "m", "a">` (2014 / 2015), or `HasOne<TokenAccount, "mint" \| "owner">` when the parameters have those names; `mint::authority = a, mint::freeze_authority = f` on an existing mint: `MintOf<Mint, "a", "f">` (2016 / 2017) |
|
|
728
|
+
| `mint::token_program = tp` / `token::token_program = tp` | `MintOf<Mint, never, never, "tp">` / `TokenOf<TokenAccount, never, never, "tp">` (2022 / 2021) |
|
|
729
|
+
| `extensions::metadata_pointer::authority = a, …` (with `mint::…`) | `mint.create(p, …, { metadataPointer: { authority: a.key, metadataAddress: mint.key }, … })`: transferHook, closeAuthority, permanentDelegate, nonTransferable, groupPointer, groupMemberPointer and more |
|
|
730
|
+
| `#[account(init, payer = p, seeds = […], bump, mint::decimals = 6, mint::authority = a, mint::freeze_authority = f)]` | `Init<Mint>`, then `const bump = mint.create(p, […], 6n, a.key, f.key)` (`null` seeds: a keypair mint; `InitIfNeeded<Mint>` + `createIfNeeded`) |
|
|
731
|
+
| `#[account(init, payer = p, seeds = […], bump, token::mint = m, token::authority = a)]` | `Init<TokenAccount>`, then `vault.create(p, […], m, a.key)` (`InitIfNeeded<TokenAccount>` + `createIfNeeded`) |
|
|
732
|
+
| `associated_token::mint = m, associated_token::authority = a` | `Ata<TokenAccount, "a", "m">`; `Ata<Init<TokenAccount>, "a", "m">` creates it |
|
|
733
|
+
| `ctx.remaining_accounts` | `remainingAccounts()` |
|
|
734
|
+
| `#[account(mut, dup)]` | `Dup<Mut<T>>` (in-place accounts only) |
|
|
735
|
+
| `sysvar::instructions` (`load_current_index_checked`, `load_instruction_at_checked`), `get_stack_height()` | `InstructionsSysvar`: `currentIndex()`, `get(i)`, `.length`; `stackHeight()` |
|
|
736
|
+
| `ctx.bumps.vault` | the value `create` returns, or `acct.pdaBump` |
|
|
737
|
+
|
|
738
|
+
## Account data
|
|
739
|
+
|
|
740
|
+
| Anchor | TypeSOL |
|
|
741
|
+
| --- | --- |
|
|
742
|
+
| `#[account] pub struct T { … }` | `export interface T { … }` |
|
|
743
|
+
| `u8` … `u128`, `i8` … `i128`, `bool`, `Pubkey` | `u8` … `u128`, `i8` … `i128`, `boolean`, `Pubkey` |
|
|
744
|
+
| `[T; N]` | `FixedArray<T, N>` |
|
|
745
|
+
| `String` with `#[max_len(n)]` | `FixedString<N>`: a u32 length and N bytes, always N bytes long |
|
|
746
|
+
| `Vec<T>` with `#[max_len(n)]` | `Vec<T>` (any number, declared anywhere, stored after the fixed-size fields; it grows with `push(v, payer)`), or `FixedVec<T, n>`: a u32 length and room for n, always 4 + n × size bytes; in a `@layout borsh` struct, `Vec<T>` is Anchor's own, bounded only by the account |
|
|
747
|
+
| `Option<T>` | `Option<T>`: fixed size (1 + size of T) |
|
|
748
|
+
| `#[derive(AnchorSerialize…)] enum` | `export enum` (unit variants) or a data enum `type A = { kind: "X"; … } \| …` |
|
|
749
|
+
|
|
750
|
+
TypeSOL keeps account data at a fixed layout by default, so three Anchor layouts differ: a Borsh `String` is
|
|
751
|
+
variable-length (TypeSOL uses `FixedString<N>`), a Borsh `Option` takes 1 byte when empty (TypeSOL always reserves the
|
|
752
|
+
value), and an Anchor `Vec` stays where it is declared (TypeSOL stores growable Vecs after the fixed-size fields; a
|
|
753
|
+
`FixedVec<T, N>` keeps its place but always takes its full capacity, where Anchor packs the elements and moves the
|
|
754
|
+
fields after them).
|
|
755
|
+
|
|
756
|
+
To keep an Anchor program's existing accounts, mark the struct `/** @layout borsh */`: it is then stored exactly as
|
|
757
|
+
Anchor stores it (`FixedString<N>` / `FixedVec<T, N>` / `Option<T>` become Borsh String / Vec / Option, N being the
|
|
758
|
+
`#[max_len]`), its IDL type is Anchor's, and the upgraded program reads and writes the accounts in place. `typesol port`
|
|
759
|
+
adds it for you. It costs some compute (the account is unpacked and packed in every instruction that uses it) but stays
|
|
760
|
+
several times cheaper than Anchor. Without it, accounts that use these types need a migration (or a new program) rather
|
|
761
|
+
than an in-place upgrade. Everything else, including instruction arguments (`String`, `Option`, `Vec` are Borsh there),
|
|
762
|
+
matches byte for byte. A `@layout borsh` struct passed as a whole argument, returned or emitted is Borsh too, so an
|
|
763
|
+
Anchor instruction that takes or returns a struct with `String` / `Vec` / `Option` fields keeps its client bytes.
|
|
764
|
+
|
|
765
|
+
## Code
|
|
766
|
+
|
|
767
|
+
| Anchor | TypeSOL |
|
|
768
|
+
| --- | --- |
|
|
769
|
+
| `pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()>` | `export function deposit(owner: Mut<Signer>, vault: Mut<Vault>, …, amount: u64): void` |
|
|
770
|
+
| `-> Result<u64>` / a struct | `: u64` / a struct: sent as return data, listed in the IDL |
|
|
771
|
+
| `#[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`) |
|
|
772
|
+
| `f64` fields (events) | `f64`, made from the bits the program computed (`f64FromBits`) |
|
|
773
|
+
| `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) |
|
|
774
|
+
| `#[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)) |
|
|
775
|
+
| `require!(c, MyError::X)`, `err!(MyError::X)` | `require(c, MyError.X)`, `require(false, MyError.X)` |
|
|
776
|
+
| `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)` |
|
|
777
|
+
| `init_if_needed` + `extensions::…` on a mint | `mint.createIfNeeded(…, { metadataPointer: {…}, … })`: an existing mint is checked as Anchor checks it (2024–2039) |
|
|
778
|
+
| `a.checked_add(b).ok_or(…)?` | `a + b` (every operation is checked; overflow aborts with 5100) |
|
|
779
|
+
| `emit!(Ev { … })` / `emit_cpi!` | `emit<Ev>({ … })` / `emitCpi<Ev>({ … }, eventAuthority, self)` |
|
|
780
|
+
| `msg!("…")` | `log("…")` |
|
|
781
|
+
| `Clock::get()?.unix_timestamp`, `.slot` | `now()`, `currentSlot()` |
|
|
782
|
+
| `Rent::get()?.minimum_balance(n)` | `rentExempt(n)`, `minimumBalance(acct)` |
|
|
783
|
+
| `system_program::transfer(CpiContext::new(…), lamports)` | `systemProgram.transfer(from, to, lamports)` |
|
|
784
|
+
| `token::transfer_checked(CpiContext::new_with_signer(…, seeds), amount, decimals)` | `tokenProgram.transferChecked(from, mint, to, authority, amount, ["seed", key, bump])` |
|
|
785
|
+
| `token::mint_to_checked` / `burn_checked` / `approve_checked` | `tokenProgram.mintToChecked(mint, to, authority, amount)` / `burnChecked(from, mint, authority, amount)` / `approveChecked(source, mint, delegate, owner, amount)` |
|
|
786
|
+
| `system_program::transfer(CpiContext::new_with_signer(…, &[vault_seeds]), lamports)` | `systemProgram.transfer(vault, to, lamports, ["vault", owner.key, bump])` |
|
|
787
|
+
| `invoke_signed(&ix, infos, &[seeds_a, seeds_b])` | `invoke(program, accounts, data, [seedsA, seedsB])` |
|
|
788
|
+
| `let (_, data) = get_return_data().unwrap(); Quote::try_from_slice(&data)?` | `const quote = returnData<Quote>(program)` (a `@layout borsh` struct when it holds Options, strings or Vecs) |
|
|
789
|
+
| `[test.validator.clone]` in Anchor.toml | `"clone": [...]` in typesol.json and `typesol clone` (loaded by `testProgram`) |
|
|
790
|
+
| `anchor_spl::metadata::update_metadata_accounts_v2` | `metadataProgram.updateMetadataAccountsV2(…)` |
|
|
791
|
+
| `anchor_spl::metadata::burn_nft` / mpl `BurnV1` | `metadataProgram.burnV1(…)` |
|
|
792
|
+
| `Sysvar<StakeHistory>` / `StakeHistory::get(epoch)` | `StakeHistorySysvar`: `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)`, `has(epoch)` |
|
|
793
|
+
| `EpochSchedule::get()?`, `LastRestartSlot::get()?` | `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()`; `lastRestartSlot()` |
|
|
794
|
+
| `anchor_spl::stake::{authorize, deactivate_stake, withdraw}`, `delegate_stake` | `stakeProgram.authorize / deactivate / withdraw / delegate(…)` |
|
|
795
|
+
| `RandomnessAccountData::parse(…)?.get_value(&clock)?` (switchboard-on-demand) | `randomness: SwitchboardRandomness`, `randomness.value()` / `valueU64()`, `randomness.seedSlot` |
|
|
796
|
+
| `pub fn fallback(program_id, accounts, data)` | `/** @fallback */ export function fallback(): void` with `instructionData()` and `remainingAccounts()` |
|
|
797
|
+
| `#[access_control(check(&ctx))]` | call the check first in the body (`check(vault, owner)`), or `constraint(acct, …)` for one that belongs with an account's checks |
|
|
798
|
+
| `spl_memo::build_memo` + `invoke` | `memoProgram.memo(text, [signers])` |
|
|
799
|
+
| `UncheckedAccount` at the SlotHashes address | `SlotHashesSysvar`: `latestSlot`, `latestHash` |
|
|
800
|
+
| `spl_token_group_interface` CPIs (`initialize_group`, `initialize_member`, …) | `token.initializeTokenGroup(…)`, `initializeGroupMember(…)`, `updateGroupMaxSize(…)`, `updateGroupAuthority(…)` |
|
|
801
|
+
| `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
|
|
802
|
+
| `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
|
|
803
|
+
| `multisig.owners = owners` (a `Vec` argument into account data) | the same |
|
|
804
|
+
| `declare_program!(other)` / CPI to another Anchor program | `typesol cpi other.json` generates typed helpers |
|
|
805
|
+
| `for x in v.iter()` | `for (const x of v)` |
|
|
806
|
+
| `v.iter().any(\|x\| …)`, `.all`, `.position`, `.find`, `.fold(init, …)`, `.contains(&x)` | `v.some((x) => …)`, `every`, `findIndex`, `find`, `reduce((acc, x) => …, init)`, `includes(x)` |
|
|
807
|
+
| a closure `\|x\| x + offset`, `let fee = \|x: u64\| x / 100;` | `const f = (x: u64): u64 => x + offset` (it may read and write the function's variables), `const fee = (x: u64): u64 => x / 100n;` |
|
|
808
|
+
| `x.unwrap_or(d)` | `x ?? d` |
|
|
809
|
+
| `fn max<T: PartialOrd>(a: T, b: T) -> T` | `function max<T extends bigint>(a: T, b: T): T` (one copy per type used) |
|
|
810
|
+
|
|
811
|
+
## Tooling
|
|
812
|
+
|
|
813
|
+
| Anchor | TypeSOL |
|
|
814
|
+
| --- | --- |
|
|
815
|
+
| `anchor init` | `typesol init` (`--template vault` / `escrow`) |
|
|
816
|
+
| `anchor build` | `typesol build` (writes the IDL and a TypeScript client next to the binary) |
|
|
817
|
+
| `anchor test` (mocha, bankrun) | `npm test` with `typesol/testing` in LiteSVM |
|
|
818
|
+
| `anchor deploy` | `typesol deploy` ([deploy to mainnet](mainnet.md)) |
|
|
819
|
+
| `anchor idl init` / `upgrade` | `typesol idl publish` |
|
|
820
|
+
| `anchor verify` | `typesol verify` (reads the deployed program and IDL from the cluster) |
|
|
821
|
+
| `@coral-xyz/anchor` `Program` client | the generated `<name>.client.ts` on `@solana/kit`, or Anchor's client with the IDL |
|
|
822
|
+
|
|
823
|
+
<!-- docs/troubleshooting.md -->
|
|
824
|
+
|
|
825
|
+
# Troubleshooting
|
|
826
|
+
|
|
827
|
+
**"Solana SBF SDK not found"** — install the Agave CLI (https://docs.anza.xyz/cli/install) and run
|
|
828
|
+
`cargo-build-sbf --version` once. TypeSOL looks in `~/.local/share/solana/install/active_release/bin/platform-tools-sdk/sbf`
|
|
829
|
+
and next to `cargo-build-sbf` on PATH; set `TYPESOL_SBF_SDK` to a `platform-tools-sdk/sbf` directory otherwise.
|
|
830
|
+
|
|
831
|
+
**"platform-tools missing" / "no SBPF v2 libraries"** — `cargo-build-sbf --force-tools-install`.
|
|
832
|
+
|
|
833
|
+
**Windows** — not tested; use WSL2 with the Linux Agave CLI.
|
|
834
|
+
|
|
835
|
+
**Node errors such as `ERR_UNKNOWN_FILE_EXTENSION` or `ERR_REQUIRE_ESM`** — use Node.js 22.12 or newer.
|
|
836
|
+
|
|
837
|
+
**"`solana` was not found on PATH"** (deploy) — install the Agave CLI, or use `typesol deploy --dry-run` and run the
|
|
838
|
+
printed commands yourself.
|
|
839
|
+
|
|
840
|
+
**"… is missing, but typesol.json records …"** — the program keypair under `target/deploy/` was deleted or replaced.
|
|
841
|
+
Restore it from your backup. Without it you cannot upgrade the deployed program; removing `"address"` from
|
|
842
|
+
`typesol.json` gives the program a new address.
|
|
843
|
+
|
|
844
|
+
**A build error you don't recognize** — the compiler adds a `hint:` line under TypeScript's message where TypeScript's
|
|
845
|
+
own advice points the wrong way for a program. The usual ones: integers are `bigint` (`1n`, `u64` parameters, not
|
|
846
|
+
`number`); `require`, `log`, `min`, `max` and `fixedArray` are imported from `"typesol"`; arrays are read with `.get(i)`
|
|
847
|
+
and written with `.set(i, v)`; an account you change is a `Mut<T>` parameter; there is no `async`, `try`, `throw` or
|
|
848
|
+
`class`. The full list of what the subset covers is in [language.md](language.md).
|
|
849
|
+
|
|
850
|
+
**A transaction fails with a custom error** — see [errors.md](errors.md). Failures raised by the
|
|
851
|
+
compiler's checks log their TypeScript location, e.g. `TypeSOL: arithmetic overflow (vault.ts:42)`.
|
|
852
|
+
|
|
853
|
+
**Heap errors (5110) building strings** — strings are allocated on a 32 KiB heap and never freed. Build less text,
|
|
854
|
+
or declare `const HEAP_SIZE_KIB = 64n` and add a ComputeBudget `requestHeapFrame` instruction to the transaction.
|
|
855
|
+
|
|
856
|
+
**`typesol idl publish` fails on a local validator with "invalid instruction data"** — the System Program of
|
|
857
|
+
`solana-test-validator` (Agave 3.1 included) rejects a System instruction that the current Program Metadata program
|
|
858
|
+
uses. Publishing works on mainnet-beta. The error shows the failing transaction's last log lines.
|
|
859
|
+
|
|
860
|
+
**"instruction X (with the helpers inlined into it) needs N bytes of stack; SBPF v0 gives each function 4096"** — under
|
|
861
|
+
SBPF v0 (the default) every function gets a fixed 4 KiB stack frame, and going past it corrupts memory, so the build
|
|
862
|
+
refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`) grow frames dynamically, so this limit does not apply there. Large structs and arrays copied into typed
|
|
863
|
+
locals (`const q: Big = acct.big`) are the usual cause: bind them without a type (`const q = acct.big`, a reference
|
|
864
|
+
into the account data) or move the work into helpers. Helpers are often inlined into their instruction, so their
|
|
865
|
+
locals count toward its frame.
|
|
866
|
+
|
|
867
|
+
<!-- docs/mainnet.md -->
|
|
868
|
+
|
|
869
|
+
# Deploy to mainnet
|
|
870
|
+
|
|
871
|
+
From an empty directory to a program on Solana mainnet-beta: create, test, deploy, publish the IDL, then check that
|
|
872
|
+
the deployed binary is the one your source builds. The program here is the counter that `typesol init` creates
|
|
873
|
+
(13.2 KiB); any TypeSOL project works the same way.
|
|
874
|
+
|
|
875
|
+
You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Requirements).
|
|
876
|
+
|
|
877
|
+
## 1. Create and test
|
|
878
|
+
|
|
879
|
+
```sh
|
|
880
|
+
npx @typesol/cli init my-app
|
|
881
|
+
cd my-app
|
|
882
|
+
npm install
|
|
883
|
+
npm test
|
|
884
|
+
```
|
|
885
|
+
|
|
886
|
+
`npm test` runs `tests/my_app.test.ts` in LiteSVM: it compiles the program and calls it, with no validator or SOL.
|
|
887
|
+
Write your program in `programs/my_app.ts` and keep the tests passing before you spend anything.
|
|
888
|
+
|
|
889
|
+
## 2. Build
|
|
890
|
+
|
|
891
|
+
```sh
|
|
892
|
+
npx typesol build
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
This writes `target/my_app/`: the program (`my_app.so`), its Anchor IDL (`my_app.json`), a TypeScript client
|
|
896
|
+
(`my_app.client.ts`) and the generated C. The first build also creates `target/deploy/my_app-keypair.json`, the
|
|
897
|
+
program's address, and records the address in `typesol.json`.
|
|
898
|
+
|
|
899
|
+
**Back up `target/deploy/my_app-keypair.json` now.** It is not committed (`.gitignore`), and without it you cannot
|
|
900
|
+
redeploy to that address.
|
|
901
|
+
|
|
902
|
+
## 3. A wallet with SOL
|
|
903
|
+
|
|
904
|
+
```sh
|
|
905
|
+
solana-keygen new -o ~/.config/solana/deployer.json
|
|
906
|
+
solana config set --url mainnet-beta --keypair ~/.config/solana/deployer.json
|
|
907
|
+
solana address
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
Send SOL to that address. Most of what a deploy costs is rent for the program's bytes, which you get back if you
|
|
911
|
+
ever close the program:
|
|
912
|
+
|
|
913
|
+
```sh
|
|
914
|
+
solana rent $(wc -c < target/my_app/my_app.so)
|
|
915
|
+
```
|
|
916
|
+
|
|
917
|
+
The counter needs 0.069 SOL of rent. During the deploy the program is first written to a buffer account that holds
|
|
918
|
+
the same amount again; it is returned when the deploy finishes. Fund about twice the rent plus 0.01 SOL for fees.
|
|
919
|
+
|
|
920
|
+
The public mainnet RPC is rate-limited; for deploys, set `--url` (or `solana config set --url`) to your RPC
|
|
921
|
+
provider's endpoint.
|
|
922
|
+
|
|
923
|
+
## 4. Deploy
|
|
924
|
+
|
|
925
|
+
```sh
|
|
926
|
+
npx typesol deploy --dry-run # builds and prints the solana command it will run
|
|
927
|
+
npx typesol deploy
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
It runs `solana program deploy` at the address in `target/deploy/my_app-keypair.json`, with your wallet as payer and
|
|
931
|
+
upgrade authority, and prints the program id. Deploying again upgrades the program in place.
|
|
932
|
+
|
|
933
|
+
If a deploy stops part-way, the buffer stays behind with its SOL. The error prints the buffer's address; recover it
|
|
934
|
+
with `solana program close <buffer address>`, or list yours with `solana program show --buffers`.
|
|
935
|
+
|
|
936
|
+
## 5. Publish the IDL
|
|
937
|
+
|
|
938
|
+
```sh
|
|
939
|
+
npx typesol idl publish
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
It writes the IDL to the Program Metadata program, signed by the upgrade authority, where Anchor clients and
|
|
943
|
+
explorers look for it. It costs a few thousandths of a SOL of rent.
|
|
944
|
+
|
|
945
|
+
## 6. Verify
|
|
946
|
+
|
|
947
|
+
```sh
|
|
948
|
+
npx typesol verify my_app
|
|
949
|
+
```
|
|
950
|
+
|
|
951
|
+
`verify` rebuilds the program from `programs/my_app.ts`, reads the deployed one at the address in `typesol.json` from
|
|
952
|
+
the cluster in your Solana CLI config, and compares the bytes. `match` means anyone with your source and the same
|
|
953
|
+
TypeSOL version gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
|
|
954
|
+
published in step 5. Anyone can run it against your program with `--address <program id> --url mainnet-beta`.
|
|
955
|
+
|
|
956
|
+
## 7. Call it
|
|
957
|
+
|
|
958
|
+
`target/my_app/my_app.client.ts` builds the program's instructions on `@solana/kit`; see [client.md](client.md).
|
|
959
|
+
|
|
960
|
+
## Later
|
|
961
|
+
|
|
962
|
+
- **Freeze it.** `solana program set-upgrade-authority <program id> --final` makes the program immutable. It cannot
|
|
963
|
+
be undone.
|
|
964
|
+
- **Close it.** `solana program close <program id> --bypass-warning` returns the rent to the authority. The program
|
|
965
|
+
id can never be used again.
|
|
966
|
+
|
|
967
|
+
A worked example: the official escrow, deployed to mainnet in TypeSOL, Pinocchio, native Rust and Anchor, with every
|
|
968
|
+
transaction linked, is in the README's [On mainnet](../README.md#on-mainnet) section.
|
|
969
|
+
|
|
970
|
+
<!-- docs/security-model.md -->
|
|
971
|
+
|
|
972
|
+
# Security model
|
|
973
|
+
|
|
974
|
+
What a program compiled by TypeSOL can rely on, who is trusted, and what is left to the program's author. This is the
|
|
975
|
+
specification the tests check and an audit measures the compiler against; [audit.md](audit.md) is the package for
|
|
976
|
+
auditors, [SECURITY.md](../SECURITY.md) how to report a problem.
|
|
977
|
+
|
|
978
|
+
## Trust
|
|
979
|
+
|
|
980
|
+
| Party | Trusted for |
|
|
981
|
+
| --- | --- |
|
|
982
|
+
| The program's author | the program's logic: what it allows, to whom, for how much |
|
|
983
|
+
| TypeSOL (this repository) | that the binary does what the source and these guarantees say, and nothing an attacker can steer beyond it |
|
|
984
|
+
| The toolchain | the TypeScript compiler API (parsing, types), Agave platform-tools (clang, lld), Node.js |
|
|
985
|
+
| The Solana runtime | account ownership and signer flags as passed, the loader's account serialization, CPI privilege rules, sysvars |
|
|
986
|
+
|
|
987
|
+
Everything a transaction carries is attacker-controlled: the instruction data, which accounts are passed in which
|
|
988
|
+
slots (any account, repeated or not), the flags the runtime then enforces, the data of accounts the program does not
|
|
989
|
+
own, remaining accounts, and what another program returns or writes.
|
|
990
|
+
|
|
991
|
+
## Guarantees
|
|
992
|
+
|
|
993
|
+
Each holds for every instruction of every program the compiler accepts. A break of any of them is a security bug
|
|
994
|
+
(SECURITY.md).
|
|
995
|
+
|
|
996
|
+
### Before the body runs
|
|
997
|
+
|
|
998
|
+
1. **Account count.** Fewer accounts than parameters fail (3005); more than the program takes (32, or its `MAX_ACCOUNTS`) fail before parsing (5113).
|
|
999
|
+
2. **Account types.** Each parameter is checked for what its type says: `Signer` signed (3010); `Mut<…>` writable
|
|
1000
|
+
(2000); a program account (`Account<T>`, `Mut<T>`) owned by this program (3007), initialized (3012), with `T`'s
|
|
1001
|
+
discriminator (3002) and at least its size (3003); `TokenAccount` / `Mint` owned by SPL Token or Token-2022 and an
|
|
1002
|
+
initialized account of that kind (3007 / 3003); program parameters at their fixed address and executable
|
|
1003
|
+
(3008 / 3009); `SystemAccount` owned by the System Program (3011); `Zeroed<T>` owned, all-zero discriminator and
|
|
1004
|
+
rent-exempt.
|
|
1005
|
+
3. **No aliasing.** Two writable parameters are never the same account (2040), whatever slots the transaction uses,
|
|
1006
|
+
unless the program marks one `Dup<…>`, and then only for accounts read and written in place (see below).
|
|
1007
|
+
4. **Arguments.** Every argument is length-checked before it is read; strings are valid UTF-8; booleans, enums and
|
|
1008
|
+
options have valid tags (102).
|
|
1009
|
+
5. **Constraints.** `Seeds` (2006, with the stored or the canonical bump), `Ata` (2015 / 2009 / 2014), `HasOne`
|
|
1010
|
+
(2001), `Owner` (2004), `Executable` (2007), `Address` (2012), `TokenOf` / `MintOf` (2014–2017, 2021, 2022) hold
|
|
1011
|
+
before the body, per account in Anchor's order ([errors.md](errors.md#which-error-a-transaction-gets)). A
|
|
1012
|
+
constraint naming an optional account is refused at compile time, so leaving the account out cannot skip it.
|
|
1013
|
+
|
|
1014
|
+
### While it runs
|
|
1015
|
+
|
|
1016
|
+
6. **Arithmetic.** Every `+ - * / % **`, compound assignment, `++` / `--`, unary minus, shift and cast is checked:
|
|
1017
|
+
overflow and lost bits fail (5100), division by zero fails (5101), a cast out of range fails (4102). There is no
|
|
1018
|
+
unchecked integer operation in the language.
|
|
1019
|
+
7. **Bounds.** Every index into an array, Vec, FixedVec or remaining-account list is checked (5104); a
|
|
1020
|
+
growable Vec's stored length is checked against the account's size before it is used (3003).
|
|
1021
|
+
8. **Account creation.** `create` / `createIfNeeded` is a top-level statement, and the account cannot be read or
|
|
1022
|
+
written before it (compile error). Creation refuses an account that already exists (3000), and an address someone
|
|
1023
|
+
pre-funded still gets created. `createIfNeeded` on an existing account re-derives the canonical PDA and checks
|
|
1024
|
+
owner, discriminator and size (token accounts: mint and owner; mints: decimals, authorities and the extensions it
|
|
1025
|
+
names). A `Migrate<From, To>` account is checked as an existing `From`; `migrate(…)` is a top-level statement every
|
|
1026
|
+
path reaches, builds the new value before rewriting the bytes, and nothing reads the old data after it (compile
|
|
1027
|
+
errors).
|
|
1028
|
+
9. **Writes through references.** A place is never written after the code that computes its value may have moved it:
|
|
1029
|
+
replacing or resizing what a live reference points into is a compile error, as is writing a Vec element with a
|
|
1030
|
+
right side that may resize the Vec.
|
|
1031
|
+
10. **Remaining accounts.** Writing one (`.lamports`, `loadAccountMut`) checks it is writable (3006) and not another
|
|
1032
|
+
account of the instruction (2040); `loadAccountMut` loads a given account once per instruction (2040);
|
|
1033
|
+
`loadAccount<T>` checks owner, discriminator and size, and validates the data as instruction arguments are.
|
|
1034
|
+
11. **Growth.** An account grows by at most 10 KiB per instruction (3016), the payer is a `Mut<Signer>`, new bytes are
|
|
1035
|
+
zero and the new rent is paid; shrinking keeps the lamports in the account.
|
|
1036
|
+
12. **CPIs.** A program signs only for its own PDAs (the runtime enforces it; the seeds are those written in the
|
|
1037
|
+
source). `invoke` marks an account writable or signer only when the parameter is `Mut` / `Signer` or the program
|
|
1038
|
+
signs for it; remaining accounts keep the flags they were passed with, or are checked for the role requested.
|
|
1039
|
+
`invokeInstruction` is the exception by design: its program, account flags and data come from values (stored in
|
|
1040
|
+
account data or passed in), so the compiler cannot check them; the runtime does, refusing any account the
|
|
1041
|
+
transaction did not pass that way and any signer the program's seeds do not cover. Only programs that store
|
|
1042
|
+
instructions to run (a multisig, a DAO) need it; review who can write those values.
|
|
1043
|
+
Return data is read only from the program named, at the expected size (5106).
|
|
1044
|
+
13. **Events.** `emitCpi` is accepted only from this program's event-authority PDA, signed (2002).
|
|
1045
|
+
|
|
1046
|
+
### When it ends
|
|
1047
|
+
|
|
1048
|
+
14. **Closing.** A `CloseTo<…>` or `close(…)` account has its lamports moved to the destination, its data zeroed and
|
|
1049
|
+
its owner reset to the System Program on every successful return, so it cannot be revived as the same account.
|
|
1050
|
+
15. **No silent success.** Every failed check returns its error code and the transaction fails: no code path continues
|
|
1051
|
+
or returns success after a failed check or CPI.
|
|
1052
|
+
|
|
1053
|
+
## Left to the author
|
|
1054
|
+
|
|
1055
|
+
- **Logic.** Who may call what, limits, prices, fees. TypeSOL checks what the types and constraints say, nothing more.
|
|
1056
|
+
- **`AccountInfo` / `UncheckedProgram`.** Unchecked by design, as in Anchor: check what you rely on.
|
|
1057
|
+
- **`requirePda(account, seeds, bump)`.** Any valid bump passes (Anchor's `bump = expr`). Use a stored bump, never one
|
|
1058
|
+
from the arguments.
|
|
1059
|
+
- **`Dup<…>`.** A parameter marked `Dup` may be the same account as another writable one. Reads see every write
|
|
1060
|
+
(both are the same bytes), so a value read before a write through the other slot is stale: read, then write.
|
|
1061
|
+
- **Instruction introspection.** The Instructions sysvar holds what the transaction's author put there. Require things
|
|
1062
|
+
of the transaction with it (that a repay instruction follows), never treat it as proof of who did what.
|
|
1063
|
+
- **Oracles.** `pythPrice` checks verification, feed and age (pass the exponent you scale by); the raw `update.*`
|
|
1064
|
+
fields are unchecked. `switchboardValue` needs the expected feed; set `minSamples`.
|
|
1065
|
+
- **`merkleVerify`.** Leaves and inner nodes hash alike: build leaves as `keccak256(keccak256(data))` in the program.
|
|
1066
|
+
- **Existing accounts in `createIfNeeded`.** An existing token account's delegate and close authority, and a mint's
|
|
1067
|
+
extensions the call does not name, are not checked (as in Anchor).
|
|
1068
|
+
- **Seeds of variable length.** Two adjacent string seeds can collide (`"ab" + "c"` and `"a" + "bc"`), as in Anchor.
|
|
1069
|
+
|
|
1070
|
+
## Where TypeSOL is stricter than Anchor
|
|
1071
|
+
|
|
1072
|
+
- Any two writable parameters naming one account are refused unless one is `Dup<…>` (Anchor compares only program
|
|
1073
|
+
and token accounts, and `dup` lifts that).
|
|
1074
|
+
- Arithmetic overflow returns an error code (5100) in every build; Anchor aborts the program, and only when
|
|
1075
|
+
overflow checks are enabled.
|
|
1076
|
+
|
|
1077
|
+
## Status
|
|
1078
|
+
|
|
1079
|
+
The compiler and runtime have had internal security reviews; the findings of the latest are fixed in 0.25.0
|
|
1080
|
+
(CHANGELOG). The releases after it have not had such a review yet, and there has been no external audit: see
|
|
1081
|
+
[audit.md](audit.md).
|
|
1082
|
+
|
|
1083
|
+
<!-- docs/ai.md -->
|
|
1084
|
+
|
|
1085
|
+
# Writing TypeSOL with an AI agent
|
|
1086
|
+
|
|
1087
|
+
TypeSOL is TypeScript, which AI coding agents write well, but a subset of it: a model's ordinary habits (`1` for an
|
|
1088
|
+
integer, `console.log`, `throw`, `xs[i]`) are refused. Four things close that gap.
|
|
1089
|
+
|
|
1090
|
+
## The rules in the project
|
|
1091
|
+
|
|
1092
|
+
`typesol init` writes the rules an agent needs into the project:
|
|
1093
|
+
|
|
1094
|
+
| File | Read by |
|
|
1095
|
+
| --- | --- |
|
|
1096
|
+
| `AGENTS.md` | Codex, Cursor, Zed, Aider and other agents that read AGENTS.md |
|
|
1097
|
+
| `CLAUDE.md` (`@AGENTS.md`) | Claude Code |
|
|
1098
|
+
| `.cursor/rules/typesol.mdc` | Cursor (always applied to `programs/` and `tests/`) |
|
|
1099
|
+
|
|
1100
|
+
They say what ordinary TypeScript habits break (bigint integers, imports from `"typesol"`, no `throw` / `async` /
|
|
1101
|
+
`class`, `Mut<T>` for an account that changes, `.get(i)` / `.set(i, v)` on lists) and how to check and test. Keep your
|
|
1102
|
+
own project notes below them in AGENTS.md.
|
|
1103
|
+
|
|
1104
|
+
## llms.txt
|
|
1105
|
+
|
|
1106
|
+
[typesol.com/llms.txt](https://typesol.com/llms.txt) is the index of the docs for models
|
|
1107
|
+
([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
|
|
1108
|
+
and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
|
|
1109
|
+
in one file, to paste into a chat or give to a model as context. Both also ship in the npm package
|
|
1110
|
+
(`node_modules/typesol/llms-full.txt`).
|
|
1111
|
+
|
|
1112
|
+
## Errors an agent can fix by itself
|
|
1113
|
+
|
|
1114
|
+
`typesol check --json` prints `{ "ok": false, "diagnostics": [...] }`; each diagnostic has `file`, `line`, `column`,
|
|
1115
|
+
`length`, `message` and, for the usual mistakes, `hint`: what to write instead ("integers (u64, u32, i64 …) are bigint
|
|
1116
|
+
in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on check → edit → check without building.
|
|
1117
|
+
|
|
1118
|
+
## The MCP server
|
|
1119
|
+
|
|
1120
|
+
`typesol mcp` serves the [Model Context Protocol](https://modelcontextprotocol.io) on stdio. `typesol init` writes
|
|
1121
|
+
`.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx typesol mcp`. Other clients take the
|
|
1122
|
+
same command:
|
|
1123
|
+
|
|
1124
|
+
```json
|
|
1125
|
+
{ "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
|
|
1126
|
+
```
|
|
1127
|
+
|
|
1128
|
+
| Tool | What it does |
|
|
1129
|
+
| --- | --- |
|
|
1130
|
+
| `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
|
|
1131
|
+
| `idl` | the Anchor-compatible IDL the program compiles to |
|
|
1132
|
+
| `docs` | searches the docs and returns the best-matching sections |
|
|
1133
|
+
| `rules` | the rules above |
|
|
1134
|
+
|
|
1135
|
+
Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
|
|
1136
|
+
files, which an agent should do in the open.
|
|
1137
|
+
|
|
1138
|
+
<!-- docs/stability.md -->
|
|
1139
|
+
|
|
1140
|
+
# Stability and the road to 1.0
|
|
1141
|
+
|
|
1142
|
+
TypeSOL is pre-1.0. Until 1.0, a minor release (0.x → 0.y) may change the language, the account and IDL layout of
|
|
1143
|
+
generated programs and error codes, and says so in the CHANGELOG ([versioning
|
|
1144
|
+
policy](https://github.com/typesol-lang/.github/blob/main/VERSIONING.md)). This page says what 1.0 will promise, which
|
|
1145
|
+
parts are already meant to stay as they are, and what has to be settled first.
|
|
1146
|
+
|
|
1147
|
+
## What 1.0 will promise
|
|
1148
|
+
|
|
1149
|
+
From 1.0 on, within a major version:
|
|
1150
|
+
|
|
1151
|
+
- **Sources keep compiling.** A program that compiles with 1.x compiles with every later 1.y, to a program with the same
|
|
1152
|
+
account layouts, IDL, instruction and account discriminators and error codes. New releases add; they do not take away.
|
|
1153
|
+
- **Binaries are reproducible and only change for a reason.** A release that changes the binary of a program that uses
|
|
1154
|
+
none of its new features says so, with the release manifest's diff (`binary-diff.txt`) as the evidence.
|
|
1155
|
+
- **The checks stay.** No check a program gets from its parameter types (owner, discriminator, signer, writability,
|
|
1156
|
+
aliasing, checked arithmetic, constraints) is removed or weakened.
|
|
1157
|
+
- **The tools keep their interfaces**: `typesol build`, `test` (via `typesol/testing`), `check --json`, `deploy`,
|
|
1158
|
+
`verify`, `idl`, the typed client, and `typesol.json`.
|
|
1159
|
+
|
|
1160
|
+
## Stable already
|
|
1161
|
+
|
|
1162
|
+
Meant to stay as they are; a change before 1.0 would be a breaking change listed as one:
|
|
1163
|
+
|
|
1164
|
+
- Types: the integers (`u8` … `u128`, `i8` … `i128`), `boolean`, `Pubkey`, `Hash`, structs, `FixedArray`, `FixedVec`,
|
|
1165
|
+
`Vec`, `FixedString`, `Option`, unit and data enums, `u256` in computation.
|
|
1166
|
+
- Account parameters and their checks: `Signer`, `Account<T>`, `Mut<T>`, `Init<T>`, `InitIfNeeded<T>`, `Zeroed<T>`,
|
|
1167
|
+
optional accounts, token accounts and mints, programs, sysvars, account groups; the constraints (`HasOne`, `Seeds`,
|
|
1168
|
+
`CloseTo`, `Ata`, `Address`, `Owner`, `Executable`).
|
|
1169
|
+
- Errors and events: error enums and their codes, `require`, `AnchorError`, `emit`, `emitCpi`.
|
|
1170
|
+
- CPIs: System, SPL Token, Token-2022, Associated Token, Memo, generic `invoke` with PDA signing.
|
|
1171
|
+
- Layouts: account data (Anchor's discriminator and fixed or `@layout borsh` layout), the IDL, the client.
|
|
1172
|
+
|
|
1173
|
+
## Experimental
|
|
1174
|
+
|
|
1175
|
+
Useful today, but may still change before 1.0 (each change listed in the CHANGELOG):
|
|
1176
|
+
|
|
1177
|
+
- The native-program surface (0.40.0): `loadRaw` / `loadRawMut`, the instruction data readers, error code 0,
|
|
1178
|
+
`ProgramError`, `panic`, `PANIC_ON_OVERFLOW`, `ERROR_LOG_PREFIX` / `PROGRAM_ERROR_LOG_PREFIX`, `logBase64`,
|
|
1179
|
+
`createProgramAddress`.
|
|
1180
|
+
- Metaplex CPIs (Token Metadata, Core, Bubblegum), oracles (Pyth, Switchboard), the Stake program.
|
|
1181
|
+
- Functions chosen at run time and lists of functions, closures returned from functions.
|
|
1182
|
+
- Tools: `typesol port`, `clone`, `profile`, `cpi`, the editor plugin, the MCP server and the agent files `init`
|
|
1183
|
+
writes, the SBPF v1 and v2 targets.
|
|
1184
|
+
|
|
1185
|
+
## Before 1.0
|
|
1186
|
+
|
|
1187
|
+
- **An external audit** of the compiler and runtime ([audit package](audit.md)), its findings fixed and published.
|
|
1188
|
+
- **Settle the open edges**, each either supported or refused with a clear error:
|
|
1189
|
+
- a struct holding a FixedVec as both an argument and account data (two layouts, one IDL type);
|
|
1190
|
+
- helpers that take a writable struct which is not an account (a `loadRaw` view, a local), now refused;
|
|
1191
|
+
- `require` with an error code computed at run time that is 0: fails as an overflow (5100) today, where a native
|
|
1192
|
+
program returns CUSTOM_ZERO;
|
|
1193
|
+
- which experimental parts above become stable, and which stay outside the 1.0 promise.
|
|
1194
|
+
- **A release candidate** (1.0.0-rc) used for the showcase ports and the templates, with no breaking change between it
|
|
1195
|
+
and 1.0.0.
|