@typesol/cli 0.40.0 → 0.42.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 +120 -0
- package/README.md +9 -5
- package/dist/ai.d.ts +10 -0
- package/dist/ai.js +43 -0
- package/dist/cli.js +15 -1
- package/dist/compiler/analyze.js +44 -3
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/emit/base.d.ts +40 -7
- package/dist/compiler/emit/base.js +33 -0
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +102 -2
- package/dist/compiler/emit/calls.js +671 -50
- package/dist/compiler/emit/cpi-core.d.ts +9 -3
- package/dist/compiler/emit/cpi-core.js +12 -7
- package/dist/compiler/emit/cpi.js +8 -14
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +51 -2
- package/dist/compiler/emit/function.js +2 -2
- package/dist/compiler/emit/outline.d.ts +24 -0
- package/dist/compiler/emit/outline.js +100 -0
- package/dist/compiler/emit/program.js +7 -2
- package/dist/compiler/emit/shared.d.ts +35 -1
- package/dist/compiler/emit/shared.js +9 -1
- package/dist/compiler/emit/statements.d.ts +31 -0
- package/dist/compiler/emit/statements.js +272 -14
- package/dist/compiler/emit/storage.d.ts +27 -1
- package/dist/compiler/emit/storage.js +124 -11
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/model.d.ts +20 -1
- package/dist/compiler/model.js +5 -0
- package/dist/testing-stake.d.ts +216 -0
- package/dist/testing-stake.js +526 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -0
- 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/architecture.md +1 -1
- package/docs/audit.md +16 -14
- package/docs/case-study-raydium-cp-swap.md +77 -41
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +107 -14
- package/docs/security-model.md +4 -0
- package/docs/stability.md +69 -0
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/lib/typesol.d.ts +241 -40
- package/llms-full.txt +1352 -0
- package/llms.txt +30 -0
- package/package.json +4 -2
- package/runtime/typesol_rt.h +69 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Case study: SPL Stake Pool
|
|
2
|
+
|
|
3
|
+
This page ports [SPL Stake Pool](https://github.com/solana-program/stake-pool) (Apache-2.0), the program behind most
|
|
4
|
+
liquid staking tokens on Solana (JitoSOL's pool is one of its accounts). The port is checked against the binary that
|
|
5
|
+
runs on mainnet as `SPoo1Ku8WFXoNDMHPsrGSTSG1Y47rzgn41SLUNakuHy` (deployed in slot 429882117, 2026-06-30), not a
|
|
6
|
+
rebuild.
|
|
7
|
+
|
|
8
|
+
**Which source.** The binary's security.txt names `program@v2.0.3`, but that string is fixed in the source and the
|
|
9
|
+
deployed code carries a fee-cap message main only gained later. The tag `program@v2.1.0` (54cdced, on a release
|
|
10
|
+
branch) rebuilt with `solana-verify build --library-name spl_stake_pool --base-image
|
|
11
|
+
solanafoundation/solana-verifiable-build:3.1.14` gives the deployed executable's hash
|
|
12
|
+
(`8df58bc9f9428c02bf34fa845ae2961274156e7ff07a8dc1be0018dd765baeff`). The port follows that tag
|
|
13
|
+
([`test/programs/SOURCES.md`](../test/programs/SOURCES.md)).
|
|
14
|
+
|
|
15
|
+
Stake Pool is a native program: one entrypoint decodes a Borsh instruction (a tag byte, then the variant's fields,
|
|
16
|
+
every byte consumed), the processor takes its accounts by position, the pool account is plain Borsh with Options and
|
|
17
|
+
data enums, the validator list is a header and a `BigVec` of 73-byte entries over a preallocated account of up to
|
|
18
|
+
20,000 validators, and every stake move is a CPI into the Stake program across epochs.
|
|
19
|
+
|
|
20
|
+
| File | Holds |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| [`stake_pool.ts`](../showcase/mainnet/spl-stake-pool/stake_pool.ts) | the entrypoint: the instruction decoded as `try_from_slice` does, dispatch to the 27 instructions |
|
|
23
|
+
| [`state.ts`](../showcase/mainnet/spl-stake-pool/state.ts), [`errors.ts`](../showcase/mainnet/spl-stake-pool/errors.ts) | StakePool (Borsh, 611 bytes at most), ValidatorList with its `BigVec<ValidatorStakeInfo>`, the stake account layout, StakePoolError from code 0 |
|
|
24
|
+
| [`util.ts`](../showcase/mainnet/spl-stake-pool/util.ts) | PDAs, fee arithmetic, the pool-token and lamport conversions, token account and mint checks (Token-2022 extensions included), the stake CPIs as solana_program's builders make them |
|
|
25
|
+
| `admin.ts`, `validators.ts`, `update.ts`, `sol.ts`, `stake_deposit.ts`, `stake_withdraw.ts`, `rebalance.ts`, `metadata.ts` | the instructions by subject |
|
|
26
|
+
|
|
27
|
+
## What is ported
|
|
28
|
+
|
|
29
|
+
All 27 instructions: Initialize; adding, removing and cleaning up validators and the preferred validators; the epoch
|
|
30
|
+
update of the list and of the pool; SOL and stake deposits and withdrawals with their slippage forms; increasing and
|
|
31
|
+
decreasing validator stake (the deprecated decrease, the additional forms with ephemeral stake, the decrease funded
|
|
32
|
+
from the reserve); the manager's and staker's setters and the funding authorities; the Metaplex token metadata; and
|
|
33
|
+
Redelegate, which the deployed program refuses ("will not be enabled"), as the port does.
|
|
34
|
+
|
|
35
|
+
## What it needed
|
|
36
|
+
|
|
37
|
+
TypeSOL gained these features for it (docs/language.md, "Porting a native program"; every other program compiles
|
|
38
|
+
to the same C as before):
|
|
39
|
+
|
|
40
|
+
- `loadBorsh<T>` / `storeBorsh`: a Borsh account without a discriminator, read into a local struct and written back
|
|
41
|
+
as `try_from_slice_unchecked` and `serialize` do, the bytes after a shrunk value left as they were (about 280 CU to
|
|
42
|
+
read the 611-byte pool, 610 to read and write it).
|
|
43
|
+
- `BigVec<T>`: SPL's `big_vec`, a list over the rest of an account with `push`, `retain`, `slice` and the list
|
|
44
|
+
methods, its loops emitted as functions of their own so they keep their registers (16 CU per entry for the pool's
|
|
45
|
+
update sum, against the original's 27).
|
|
46
|
+
- `programAt<P>` / `sysvarAt<S>` and typed CPIs that take remaining accounts, the Stake program's `split`, `merge`,
|
|
47
|
+
`getMinimumDelegation` and lockups, and `named(account, address)`: a sysvar named by address as solana_program's
|
|
48
|
+
builders name it, with the slot's account passed as Rust's `invoke_signed` passes it.
|
|
49
|
+
- `NATIVE_ACCOUNT_WRITES`: account data written in place and judged by the runtime afterwards, as a native program's
|
|
50
|
+
is; `epochRewards()`; `panic(null, location)` and `abort()`; local lists, the instruction data as a list and
|
|
51
|
+
`invokeInstruction` in helpers (the Metaplex CPI); a ternary between accounts.
|
|
52
|
+
- In `typesol/testing`: `warpToEpoch`, `StakeCluster` (the StakeHistory a cluster writes, so stake warms up and cools
|
|
53
|
+
down over epochs as on mainnet, matched to the runtime's Stake program to the lamport), and vote and stake account
|
|
54
|
+
builders.
|
|
55
|
+
|
|
56
|
+
## How it is checked
|
|
57
|
+
|
|
58
|
+
The mainnet binary and the port run in two LiteSVMs under the same program id, with the same clock and the same
|
|
59
|
+
StakeHistory written into both by one `StakeCluster`. Every transaction must give the same outcome, the same log
|
|
60
|
+
lines (the "Instruction: …" lines, every message with its numbers, the error lines, panic locations) and the same
|
|
61
|
+
bytes in every account it names. There are 2,107 such transactions in six files:
|
|
62
|
+
|
|
63
|
+
- **The instructions** (`spl-stake-pool.test.ts`, `-stake`, `-rebalance`, `-metadata`; 1,406): every instruction's
|
|
64
|
+
success paths and every refusal that can be built, account by account (wrong signers, PDAs, owners, mints and
|
|
65
|
+
Token-2022 extensions, sysvars, short account lists), fee limits, slippage, preferred validators, funding
|
|
66
|
+
authorities, read-only and repeated accounts (the original's RefCell panics included), pools of 50 to 60 validators,
|
|
67
|
+
warmup and cooldown over several epochs.
|
|
68
|
+
- **The original's own tests** (`spl-stake-pool-upstream.test.ts`; 701): each of the 221 test functions in
|
|
69
|
+
`program/tests` at the tag is mapped to a case ([the mapping](../showcase/test/spl-stake-pool-upstream.md)): 143
|
|
70
|
+
were covered already, 78 are added there, none is left out. huge_pool.rs runs at 3,000 and 20,000 validators.
|
|
71
|
+
- **A random walk over epochs** (`spl-stake-pool-fuzz.test.ts`): validators added and removed, users depositing and
|
|
72
|
+
withdrawing SOL and stake, rebalancing, updates in random chunks, fee and authority changes, rewards, slow warmup,
|
|
73
|
+
and invalid inputs at a low rate (`FUZZ_SEED`, `STAKE_POOL_FUZZ_STEPS`). Five seeds of 600 steps (215 epochs, about
|
|
74
|
+
3,700 transactions) found no difference. Each run is 1,000 steps by default and requires every main kind of
|
|
75
|
+
instruction (SOL and stake deposits and withdrawals, increases, decreases, both updates, adding a validator) to
|
|
76
|
+
succeed at least once.
|
|
77
|
+
|
|
78
|
+
The random walk found one: a stake withdrawal that searched the list in one pass where the original searches twice
|
|
79
|
+
ran out of the default compute budget at 3,550 validators, where the original does not. The port now searches as the
|
|
80
|
+
original does, and a regression case runs at 3,550 validators.
|
|
81
|
+
|
|
82
|
+
## Cost
|
|
83
|
+
|
|
84
|
+
Compute units per transaction, mainnet original against the port, from those tests (the stake, token and Metaplex
|
|
85
|
+
CPIs are the same work in both; the port's own part is about a third of the original's):
|
|
86
|
+
|
|
87
|
+
| Instruction | Original | TypeSOL | |
|
|
88
|
+
| --- | ---: | ---: | ---: |
|
|
89
|
+
| `Initialize` | 16,535 | 6,311 | 38% |
|
|
90
|
+
| `DepositSol` | 16,090 | 7,090 | 44% |
|
|
91
|
+
| `WithdrawSol` | 21,247 | 12,236 | 58% |
|
|
92
|
+
| `AddValidatorToPool` | 41,117 | 31,518 | 77% |
|
|
93
|
+
| `RemoveValidatorFromPool` | 21,027 | 14,868 | 71% |
|
|
94
|
+
| `UpdateValidatorListBalance`, 12 validators | 104,835 | 29,605 | 28% |
|
|
95
|
+
| `UpdateStakePoolBalance` | 10,080 | 3,554 | 35% |
|
|
96
|
+
| `CleanupRemovedValidatorEntries` | 4,847 | 944 | 19% |
|
|
97
|
+
| `DepositStake` | 86,950 | 64,353 | 74% |
|
|
98
|
+
| `WithdrawStake` | 67,809 | 52,184 | 77% |
|
|
99
|
+
| `IncreaseValidatorStake` | 42,088 | 33,109 | 79% |
|
|
100
|
+
| `DecreaseValidatorStakeWithReserve` | 59,340 | 47,497 | 80% |
|
|
101
|
+
| `SetFee` | 3,624 | 1,628 | 45% |
|
|
102
|
+
| `UpdateTokenMetadata` (without Metaplex's part) | 10,250 | 5,285 | 52% |
|
|
103
|
+
|
|
104
|
+
At 20,000 validators (huge_pool.rs, with a 1.4M CU budget): `UpdateStakePoolBalance` 547,385 against 321,997 (59%),
|
|
105
|
+
the cleanup 184,870 against 101,025 (55%), `DepositStake` 611,313 against 153,300 (25%), `WithdrawStake` 783,846
|
|
106
|
+
against 310,716 (40%). Within the default 200,000 the port updates a pool of 6,800 validators in 110,647 and cleans up
|
|
107
|
+
19,000 in 95,875, as the original does in 190,835 and 175,720.
|
|
108
|
+
|
|
109
|
+
The binary is 202,240 bytes against the original's 338,912.
|
|
110
|
+
|
|
111
|
+
## Differences
|
|
112
|
+
|
|
113
|
+
None that a transaction can reach. Two need the pool's bytes rewritten by hand, which no instruction allows:
|
|
114
|
+
|
|
115
|
+
- The validator list given again in the place of an account the pool stores (the reserve, the mint, the fee account):
|
|
116
|
+
the original would panic on a second borrow of the list there; the port does not model that borrow.
|
|
117
|
+
- A withdraw authority whose stored bump is not the canonical one: the metadata instructions sign with the stored bump,
|
|
118
|
+
the original finds the canonical one again.
|
|
119
|
+
|
|
120
|
+
The tests run on LiteSVM, whose Stake program computes warmup with the f64 formula; `StakeCluster` follows it
|
|
121
|
+
(`math: "integer"` when the runtime moves to the integer one). Account-data direct mapping is not enabled there; both
|
|
122
|
+
programs write in place, so both would fault at the same write.
|
package/docs/errors.md
CHANGED
|
@@ -39,7 +39,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
|
|
|
39
39
|
| 4102 | cast overflow (InvalidNumericConversion) |
|
|
40
40
|
| 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
|
|
41
41
|
| 5103 | sysvar unavailable |
|
|
42
|
-
| 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) |
|
|
42
|
+
| 5104 | index out of bounds (arrays, Vecs, remaining accounts, `pop()` on an empty Vec, `push` on a full FixedVec or `pushAll` past its room, a `slice` of the instruction data out of range, a stored `map` / `filter` result one element too small) |
|
|
43
43
|
| 5105 | string longer than the FixedString capacity |
|
|
44
44
|
| 5106 | missing or mismatched return data |
|
|
45
45
|
| 5107 | event larger than 1024 bytes |
|
package/docs/language.md
CHANGED
|
@@ -15,7 +15,8 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
15
15
|
| Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit. A cast is a value: import `u64`, not `type u64` (one import serves as both) |
|
|
16
16
|
| Logging | `log("text")`, `log(value)`, `log(pubkey)` |
|
|
17
17
|
| Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
|
|
18
|
-
| Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack; also a struct literal's field value (`{ prices: fixedArray<u64, 16>(0n), … }`), filled in place |
|
|
18
|
+
| Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack; also a struct literal's field value (`{ prices: fixedArray<u64, 16>(0n), … }`), filled in place. Elements may be structs of fixed size or `FixedString<N>` (`fixedArray<Meta, 2>({ pubkey, isSigner: false, isWritable: true })`: the fill built once and copied into each slot), and `fixedArray<T, N>(fill)` written inline feeds a chain, a list method or `for … of` (`fixedArray<u64, 3>(2n).map((x) => x * 5n).reduce(…)`) |
|
|
19
|
+
| Local lists | `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey: k, isSigner: false, isWritable: false }])`, `const buf: FixedVec<u8, 600> = fixedVec([])`, `const pair: FixedArray<Meta, 2> = fixedArray(meta)` — a FixedVec or FixedArray of integers, booleans, Pubkeys, enums, `FixedString<N>` or fixed-size structs on the stack, with `get`, `set`, `push`, `pushAll`, `pop`, `clear`, `.length`, `for … of` and the list methods; given another list (`const y: FixedVec<Pubkey, 4> = xs`) it is a copy, as a struct local is. One list holds at most 2 KiB (the 4 KiB stack frame is shared with the rest of the function): a bigger one is a compile error naming its size |
|
|
19
20
|
| Strings | `string` arguments and literals; `name: FixedString<32>` in account data (u32 length + 32 bytes); `===`, `byteLength(s)`, `log(s)`, `+=`, as PDA seeds; too-long writes abort (5105). A local bound to account text keeps its own copy |
|
|
20
21
|
| Copies | `a.home = b.home`, `a.trail.set(0n, a.home)` copy whole structs / arrays of the same type: assignment copies (like Rust/Anchor), binding with `const` references |
|
|
21
22
|
| Destructuring | `const { owner, pos: p } = acct` (or `let` for scalars to change) from a name or a field path — one declaration per name, read like `acct.owner`: scalars are copies, nested structs are references. No rest, defaults or nesting |
|
|
@@ -26,36 +27,38 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
26
27
|
| Options | `best: Option<u64>` (or `u64 \| null`) — `null`, `=== null`, TypeScript narrowing; `===` between options or with a value follows JS (null equals null, empty never equals a value); empty use aborts (5108); `acct?.field` on an optional account and `x.home?.field` on an `Option<struct>` give an Option (empty when the account was left out / the option is empty), `a ?? b` takes b only when a is empty (b runs only then; the result is an Option when b can be null), `x!` is the value or aborts with 5108; `${opt}` prints the value or `null`. Borsh `option` in arguments/events, fixed `{ is_some, value }` in account data |
|
|
27
28
|
| Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
|
|
28
29
|
| 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 |
|
|
30
|
+
| A native program's Borsh accounts | `const pool = loadBorsh<StakePool>(acct)` / `storeBorsh(acct, pool)`: Borsh from byte 0 with no discriminator and no owner check, read into a local struct and written back, as Rust's `try_from_slice_unchecked` and `serialize` do (trailing bytes ignored when reading, left as they were when writing; invalid bytes or an account too small fail with `ProgramError.BorshIoError`). Any struct of integers, booleans, Pubkeys, enums, FixedArrays, FixedStrings, FixedVecs, Options, data enums with fixed-size payloads and nested structs of those; see [Porting a native program](#porting-a-native-program) |
|
|
29
31
|
| Zero-copy types as Anchor's IDL describes them | `/** @repr c */` (`@repr c packed`, `@repr c align 8`, `@repr rust` on an enum) and `/** @serialization bytemuck */` on a struct or enum put the IDL's `repr` and `serialization` there, as Anchor's `#[account(zero_copy)]` / `#[repr(C)]` types have them. TypeSOL stores fields back to back, so an unpacked `@repr c` struct must have its fields where C puts them: a field off its alignment, or a size that is not a multiple of the struct's, is a compile error naming the padding to add (Anchor zero-copy types spell their padding out as `_pad` fields, so a port matches). A 16-byte integer's alignment differs between targets: hold it as below or mark the struct packed |
|
|
30
32
|
| Field names and bytes for the IDL | `/** @bytes */` on an integer field: stored as the integer (little-endian), shown in the IDL as `[u8; N]` (Marginfi's `WrappedI80F48 { value: [u8; 16] }`, read and written as an `i128`); on a FixedArray of integers, each element as its bytes (`[[u8; 8]; 16]` for a `FixedArray<u64, 16>`). `/** @idlName _pad0 */`: the field's IDL name where the source cannot use it (a leading `_`). A field named like an account member plus `_` (`key_`, `lamports_`) is `key` / `lamports` in the IDL |
|
|
31
33
|
| Floats in events and accounts | `f64` holds a 64-bit float as its IEEE bits (Borsh writes those 8 bytes; the IDL says `f64`). There is no float arithmetic: `f64FromBits(bits)` makes one from bits the program computed in integers (Marginfi's events report I80F48 amounts this way), `f64Bits(x)` reads them back |
|
|
32
34
|
| 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 |
|
|
33
|
-
| Fixed-capacity lists | `owners: FixedVec<Pubkey, 8>` — any field, any number of them, in nested structs too: a u32 length and room for N elements (always 4 + N × size bytes), the same `get`, `set`, `push(v)`, `pop()`, `clear()`, `.length` and `for … of`; `push` on a full one fails (5104); `acct.owners = fixedVec([a, b])` writes a whole one (unused slots zeroed), and `acct.owners = owners` copies a `Vec` argument (or another list of the same elements) into it, Anchor's `multisig.owners = owners` (more than N fail with 5104). In account data, returned structs and events; as an argument (`ids: FixedVec<u64, 8>`) it is a Borsh Vec of at most N elements, read like a `Vec` argument (more fail with 102) |
|
|
35
|
+
| Fixed-capacity lists | `owners: FixedVec<Pubkey, 8>` — any field, any number of them, in nested structs too: a u32 length and room for N elements (always 4 + N × size bytes), the same `get`, `set`, `push(v)`, `pop()`, `clear()`, `.length` and `for … of`; `push` on a full one fails (5104); `xs.pushAll(items)` appends a whole list of the same elements in one copy (another FixedVec, a FixedArray or Vec, a Vec argument, the instruction data or a slice of it: a memcpy, about 0.01 CU a byte for 1000 bytes against 11 for a `push` loop), failing with 5104 and appending nothing when it does not fit (`Vec` declares it so a Vec still passes for a FixedVec, but a Vec grows one `push` at a time); `acct.owners = fixedVec([a, b])` writes a whole one (unused slots zeroed), and `acct.owners = owners` copies a `Vec` argument (or another list of the same elements) into it, Anchor's `multisig.owners = owners` (more than N fail with 5104). In account data, returned structs and events; as an argument (`ids: FixedVec<u64, 8>`) it is a Borsh Vec of at most N elements, read like a `Vec` argument (more fail with 102) |
|
|
36
|
+
| Native zero-copy lists | `validators: BigVec<ValidatorStakeInfo>` — SPL's `big_vec` (the stake pool's validator list): the last field of a fixed-layout struct read with `loadRaw` / `loadRawMut`, a u32 length then the elements, in an account allocated up front; its room is the account's (`.capacity`: (size − fixed fields − 4) / size(T)) and it is never resized. Loading checks that the length fits (ProgramError::AccountDataTooSmall), and every access afterwards is bounded by the room as well: a length written again after the load (writeData, another view, storeBorsh) is read as at most `.capacity`, so `.length`, `get` / `set`, the loops, `slice` and `retain` never reach past the account. `get` / `set` (5104 past the length), `push(v)` (AccountDataTooSmall when full, as BigVec::push), `retain((x) => keep)` (in place, one pass, kept runs moved with the memmove syscall; bytes past the new end keep what they held, as BigVec::retain), `for … of`, the list callbacks (`findIndex`, `find(f)!.field` on struct elements), `.length`. `list.slice(start, end?)` is BigVec::deserialize_mut_slice(start, end − start), used where it is written (`for (const v of l.validators.slice(skip, skip + n))`, `.slice(a, b).forEach(…)`, `.get(i)`, `.length`); out of range fails with AccountDataTooSmall instead of clamping. Elements are references into the account. Not an account parameter, an argument, a local, nested, or in a `@layout borsh` struct |
|
|
34
37
|
| 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) |
|
|
35
38
|
| 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 |
|
|
36
39
|
| 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) |
|
|
37
40
|
| Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
|
|
38
41
|
| 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 |
|
|
39
42
|
| 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 |
|
|
40
|
-
| Ternaries | `const fee = vip ? 0n : 30n` — only the chosen branch runs |
|
|
43
|
+
| Ternaries | `const fee = vip ? 0n : 30n` — only the chosen branch runs. Between accounts too: `const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or `RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a remaining account does (typed CPIs, `readData`, `loadRaw` / `loadRawMut`, `loadBorsh`, helpers taking a `RemainingAccount`) |
|
|
41
44
|
| Constants | top-level `const SEED = "vault"`, `const FEE: u16 = 30n`, `const ON = true` — inlined, usable as seeds (and described in the IDL) |
|
|
42
45
|
| 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 |
|
|
43
46
|
| 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) |
|
|
44
|
-
| Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58) — built on the 32 KiB heap (5110 when full): a template is joined in one allocation, text known at compile time (literals, string and Pubkey constants) is folded in, and `s += …` grows the newest heap string in place |
|
|
47
|
+
| Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58; an `Option` of an integer, boolean, Pubkey or Hash as its value, or `null` when empty, as JS prints it: after `x !== null` that is the value) — built on the 32 KiB heap (5110 when full): a template is joined in one allocation, text known at compile time (literals, string and Pubkey constants) is folded in, and `s += …` grows the newest heap string in place |
|
|
45
48
|
| `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
|
|
46
49
|
| Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash` (a PDA seed too: its 32 bytes, as Marginfi seeds an order with the hash of its bank keys); `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump; `programId()` → this program's address; `a.compare(b)` orders Pubkeys and Hashes as Rust orders their 32 bytes (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
|
|
47
50
|
| 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">`) |
|
|
48
51
|
| 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 |
|
|
49
52
|
| 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 |
|
|
50
53
|
| Loops | `for (let i = 0n; i < n; i++)`, `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
|
|
51
|
-
| Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); no recursion. A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
|
|
54
|
+
| Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
|
|
52
55
|
| 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) |
|
|
53
56
|
| 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) |
|
|
54
57
|
| 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) |
|
|
55
58
|
| 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) |
|
|
56
59
|
| 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()`) |
|
|
57
60
|
| `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
|
|
58
|
-
| Sysvars | `now()`, `currentSlot()`, `currentEpoch()`, `epochStartTimestamp()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()`; `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
|
|
61
|
+
| Sysvars | `now()`, `currentSlot()`, `currentEpoch()`, `epochStartTimestamp()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()`; `epochRewards()` (EpochRewards through its syscall, Rust's `EpochRewards::get()`, no account: a read-only copy with `distributionStartingBlockHeight`, `numPartitions`, `parentBlockhash` (Hash), `totalPoints` (u128), `totalRewards`, `distributedRewards`, `active`; `const er = epochRewards()` or `epochRewards().active` inline, not a helper parameter); `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
|
|
59
62
|
| 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) |
|
|
60
63
|
| 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) |
|
|
61
64
|
| 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) |
|
|
@@ -72,7 +75,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
72
75
|
| `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable). A zero-copy type (`@serialization bytemuck`) is checked as Anchor's `AccountLoader` checks it: owner first (3007, also for an account never created), then a discriminator to read (3001) and match (3002), then the size |
|
|
73
76
|
| `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 |
|
|
74
77
|
| `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 |
|
|
75
|
-
| `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL |
|
|
78
|
+
| `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL. The data is a read-only list of u8: `for (const b of data)`, `map` / `filter` / `reduce` / `some` and the other list methods, `data.slice(start, end?)` (a view, nothing copied; unlike JS it does not clamp: past the length fails with 5104), `out.pushAll(data.slice(a, b))` into a local FixedVec, and a helper takes it or a slice as an `InstructionBytes` parameter |
|
|
76
79
|
| 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 |
|
|
77
80
|
| `constraint(acct, condition, error?)` | Anchor's `constraint = condition @ error` on `acct`: statements at the very start of the body, run with that account's checks (after its `has_one`, before the next account; with the other constraints after the creates the body starts with), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
|
|
78
81
|
| `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 |
|
|
@@ -98,7 +101,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
98
101
|
| `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
|
|
99
102
|
| `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
|
|
100
103
|
| `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)` |
|
|
101
|
-
| `StakeProgram` | `initialize(stake, rentSysvar, staker, withdrawer)` (
|
|
104
|
+
| `StakeProgram` | `initialize(stake, rentSysvar, staker, withdrawer, lockup?)` (`lockup`: `{ unixTimestamp, epoch, custodian }`, none when left out), `authorize(stake, clockSysvar, authority, newAuthority, "staker" \| "withdrawer", custodian?)`, `delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker)`, `split(stake, splitStake, staker, lamports)`, `deactivate(stake, clockSysvar, staker)`, `withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, custodian?)`, `merge(destination, source, clockSysvar, stakeHistorySysvar, staker)`, `getMinimumDelegation()` (a CPI, then the u64 the Stake program returns; fails as solana_program's `get_minimum_delegation` does); instruction tags and account lists as solana-stake-interface's builders; the sysvar and config accounts are parameters, as in anchor-spl's stake module, or `named(account, address)` (a native port): the instruction names `address` (`SysvarC1ock…`), as solana_program's builders do, and `account`, the slot's account, is what the runtime gets, as Rust's `invoke_signed(&ix, &[stake, clock_info, …])` passes it; the runtime looks the address up among the CPI's accounts only, so a slot holding another account fails the call (MissingAccount), as the original does, even when the sysvar is elsewhere in the transaction (`named` is valid only there); authorities and the lockup custodian sign (PDAs with signerSeeds, given last) |
|
|
102
105
|
| `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) |
|
|
103
106
|
| `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 |
|
|
104
107
|
| `Program<"Address…">` | exact program address + executable |
|
|
@@ -194,9 +197,23 @@ invokeInstruction(transaction.programId, transaction.accounts, transaction.data,
|
|
|
194
197
|
```
|
|
195
198
|
|
|
196
199
|
- the accounts are a list of structs with `pubkey`, `isSigner` and `isWritable` (a Vec or FixedVec in account data, a
|
|
197
|
-
Vec argument,
|
|
198
|
-
|
|
199
|
-
|
|
200
|
+
Vec argument, a stored `map` result, or a local list built on the stack); the data a list of u8 (the same, the
|
|
201
|
+
instruction data or a slice of it).
|
|
202
|
+
- every account in the fourth argument (`remainingAccounts()` or a slice; in a helper, its `RemainingAccounts`
|
|
203
|
+
parameter or a slice of it) is handed to the runtime, which finds each meta's account there by key: one that is
|
|
204
|
+
missing fails the call, as under Rust (MissingAccount, "Instruction references an unknown account").
|
|
205
|
+
- so a native port builds the instruction as Rust's instruction builders do, in a helper too, with metas naming
|
|
206
|
+
accounts by key:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
function transfer(rest: RemainingAccounts, data: InstructionBytes, to: Pubkey): void {
|
|
210
|
+
const metas: FixedVec<Meta, 2> = fixedVec([{ pubkey: rest.get(0n).key, isSigner: true, isWritable: true }]);
|
|
211
|
+
metas.push({ pubkey: to, isSigner: false, isWritable: true });
|
|
212
|
+
const ix: FixedVec<u8, 12> = fixedVec([2n, 0n, 0n, 0n]); // system_instruction::transfer
|
|
213
|
+
ix.pushAll(data.slice(1n, 9n)); // the lamports, as sent
|
|
214
|
+
invokeInstruction(rest.get(2n).key, metas, ix, rest);
|
|
215
|
+
}
|
|
216
|
+
```
|
|
200
217
|
- the runtime checks the privileges: a meta may be a signer or writable only as the transaction passed that account,
|
|
201
218
|
or as a PDA of this program the seeds (fifth argument) sign for. See `showcase/mainnet/multisig/multisig.ts`.
|
|
202
219
|
|
|
@@ -212,21 +229,97 @@ When an instruction calls `x.create(payer, seeds)` or `requirePda(x, seeds, bump
|
|
|
212
229
|
an integer literal, an argument, `acct.key` or a scalar field of an account, the IDL entry for `x` gets Anchor `pda.seeds`
|
|
213
230
|
(`const` / `arg` / `account`), so Anchor and Codama clients derive the address themselves.
|
|
214
231
|
|
|
232
|
+
## Programs and sysvars passed as remaining accounts
|
|
233
|
+
|
|
234
|
+
A native program takes its programs and sysvars by position too. `programAt<P>(account)` checks a remaining account
|
|
235
|
+
(or an `AccountInfo` parameter) is that program, once, by its key, and gives it P's typed methods:
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
const rest = remainingAccounts();
|
|
239
|
+
const stake = programAt<StakeProgram>(rest.get(12n)); // ProgramError.IncorrectProgramId if it is another account
|
|
240
|
+
stake.split(rest.get(3n), rest.get(4n), rest.get(1n), lamports, [pool.key, "withdraw", bump]);
|
|
241
|
+
const minimum = stake.getMinimumDelegation();
|
|
242
|
+
programAt<TokenInterface>(rest.get(10n)).mintTo(rest.get(7n), rest.get(8n), rest.get(1n), amount, seeds);
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
- P is `StakeProgram`, `SystemProgram`, `TokenProgram`, `Token2022Program`, `TokenInterface` (either token program),
|
|
246
|
+
`AssociatedTokenProgram` or `MemoProgram`. Bind it with `const`, or call a method on it directly; pass it to a helper
|
|
247
|
+
that takes that program type.
|
|
248
|
+
- `sysvarAt<StakeHistorySysvar>(account)` does the same for the StakeHistory sysvar (ProgramError.InvalidArgument for
|
|
249
|
+
another account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)` … as on a parameter (read its fields
|
|
250
|
+
through a `const` bound to it; methods also work on the call itself).
|
|
251
|
+
- Every typed CPI (System, SPL Token and Token-2022, ATA, Memo, Stake) takes, for each account, a declared parameter,
|
|
252
|
+
a remaining account (`rest.get(i)`, a local bound to one, a `RemainingAccount` helper parameter), a struct loaded
|
|
253
|
+
from one, or an `AccountInfo` parameter where a `TokenAccount` or `Mint` goes. Declared parameters keep their
|
|
254
|
+
compile-time checks (writable slots need `Mut<…>`, an authority without signerSeeds a `Signer`). A remaining account
|
|
255
|
+
is not checked by the compiler, and unlike `invoke` the typed calls add no runtime check of their own: the runtime
|
|
256
|
+
refuses a CPI that makes an account writable or a signer when the transaction did not (and no seeds sign for it),
|
|
257
|
+
and the called program checks the rest (a token account's mint and owner, a stake account's authorities).
|
|
258
|
+
- The cost is the key check (four 8-byte compares) and the call itself: within a few compute units of the same call
|
|
259
|
+
written with `invoke`, which checks only the executable flag (test/integrations/native-cpi.test.ts measures it).
|
|
260
|
+
|
|
215
261
|
## Porting a native program
|
|
216
262
|
|
|
217
263
|
A program written without Anchor (Raydium AMM v4, SPL programs) reads a tag byte and its arguments itself and takes its
|
|
218
264
|
accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-amm` and `test/fixtures/native.ts`):
|
|
219
265
|
|
|
220
266
|
- One `/** @fallback */` entry: `const data = instructionData()` gives the bytes, with `data.readU8/U16/U32/U64/U128/
|
|
221
|
-
readPubkey(offset)` (little-endian, bounds-checked: 5104)
|
|
267
|
+
readPubkey(offset)` (little-endian, bounds-checked: 5104), and the list methods, `for … of`, `data.slice(a, b)`
|
|
268
|
+
(a view, 5104 out of range) and `out.pushAll(data.slice(a, b))` (a memcpy into a local FixedVec); a helper takes it as
|
|
269
|
+
an `InstructionBytes` parameter. `remainingAccounts()` gives the accounts by position.
|
|
270
|
+
- Calls to System, Token and Stake: `programAt<P>(acct)` and the typed methods, with remaining accounts (above), not
|
|
271
|
+
hand-encoded `invoke` data.
|
|
222
272
|
- Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
|
|
223
273
|
byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
|
|
224
274
|
original's own checks (an exact size, its error codes) before the load. Structs are packed, as `#[repr(C, packed)]`.
|
|
275
|
+
- Borsh accounts without a discriminator (SPL Stake Pool's `StakePool`, read with `try_from_slice_unchecked` and
|
|
276
|
+
written with `serialize`): `const pool = loadBorsh<StakePool>(acct)` decodes the data from byte 0 into a local
|
|
277
|
+
struct (a copy: fields updated, Options narrowed and set to null or a value, data enums switched, copied, passed to
|
|
278
|
+
helpers), and `storeBorsh(acct, pool)` encodes it back from byte 0. As Rust: no owner check and no discriminator
|
|
279
|
+
(check the owner first, as the original does); bytes after the value are ignored when reading and left as they were
|
|
280
|
+
when writing (an Option that became None leaves its old bytes behind it); data too short, an Option tag or boolean
|
|
281
|
+
other than 0/1, an enum tag out of range, a String that is not UTF-8 or longer than its `FixedString<N>`, or an
|
|
282
|
+
account too small for the encoding fail with `ProgramError.BorshIoError`. `acct` is a remaining account, a
|
|
283
|
+
`RemainingAccount` helper parameter or an `AccountInfo` parameter (`Mut<AccountInfo>` for `storeBorsh`; a remaining
|
|
284
|
+
account must be writable, 3006). `T` may hold integers, booleans, Pubkeys, enums, FixedArrays, `FixedString<N>`,
|
|
285
|
+
`FixedVec<T, N>`, Options, data enums with fixed-size payloads and nested structs of those, with or without
|
|
286
|
+
`@layout borsh`; not `Vec<T>` or `string` (they would need the heap or a view). Each struct gets its own
|
|
287
|
+
straight-line decoder and encoder (no heap): about 280 CU to read a 611-byte `StakePool` and 610 CU to read and
|
|
288
|
+
write it back. The local lives on the stack (4 KiB per function).
|
|
289
|
+
- Lists over the rest of an account (SPL's `big_vec`): a struct ending in `BigVec<T>`, `const list =
|
|
290
|
+
loadRawMut<ValidatorList>(acct)`, then `list.validators.push(…)`, `.retain((v) => …)`, `.findIndex((v) => …)`,
|
|
291
|
+
`for (const v of list.validators.slice(skip, skip + len))` (`deserialize_mut_slice(skip, len)`). The load fails with
|
|
292
|
+
AccountDataTooSmall when the stored length does not fit, where the Rust would only panic on reaching such an element:
|
|
293
|
+
check the length first (`readData<u32>(acct, offset)`) where the original returns an error of its own before that.
|
|
294
|
+
- Writes as the original makes them: `export const NATIVE_ACCOUNT_WRITES = true` (anywhere in the program; opt-in, for
|
|
295
|
+
native ports). A native program writes account data in place and the runtime judges afterwards: a read-only account
|
|
296
|
+
whose data actually changed fails the instruction (`ReadonlyDataModified`, or an access violation at the write under
|
|
297
|
+
account-data direct mapping), one that was only read (or written with the bytes it held) is fine, and an account
|
|
298
|
+
passed twice is two `AccountInfo`s over one buffer. By default
|
|
299
|
+
`loadRawMut` and `storeBorsh` check writability up front (3006), `loadRawMut` claims the account once and
|
|
300
|
+
`storeBorsh` refuses an account passed more than once (2040, as a write to a remaining account's lamports), so a
|
|
301
|
+
port fails where the original succeeds (a read-only validator list that is only read; the list passed again as a
|
|
302
|
+
stake account, which the original skips by its address checks). With the flag, `loadRawMut`, `storeBorsh` and the
|
|
303
|
+
BigVec writes through a `loadRawMut` view skip both, and both take a plain `AccountInfo` parameter (no `Mut<…>`
|
|
304
|
+
needed). Owner and size checks stay. **The trade-off:** a write to a read-only account is reported by the runtime at
|
|
305
|
+
the end, not at the write, and two loads of one account are two views of the same bytes (a write through one is
|
|
306
|
+
read through the other), where Rust's `RefCell` would fail a second `borrow_mut()` while the first is held (a panic,
|
|
307
|
+
or `AccountBorrowFailed` through `try_borrow_mut_data`). The original's own address and type checks normally refuse
|
|
308
|
+
such a pair before it is loaded (SPL Stake Pool's PDA checks); make them in the same order, before the load. Only
|
|
309
|
+
data writes are affected: with or without the flag every view reads the account's bytes in place, so a `loadRaw`
|
|
310
|
+
of an account also loaded with `loadRawMut` (or written with `storeBorsh`) reads what was written, BigVec pushes
|
|
311
|
+
included; the flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position or
|
|
312
|
+
another, is 2040 without it). `.lamports` on remaining accounts, `loadAccountMut`, CPI account metas and the checks of
|
|
313
|
+
`Mut<…>` parameters stay as they are, and programs without the flag compile exactly as before.
|
|
225
314
|
- Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
|
|
226
315
|
`ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
|
|
227
316
|
built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
|
|
228
|
-
reporting that location
|
|
229
|
-
|
|
317
|
+
reporting that location; `panic(null, "src/lib.rs:105:19")` logs no message, for an original whose panic handler
|
|
318
|
+
writes none, so only the runtime's "SBF program Panicked in src/lib.rs at 105:19" is left); `abort()` for Rust's
|
|
319
|
+
abort (the allocator's out-of-memory error: `log("Error: memory allocation failed, out of memory"); abort();`), the
|
|
320
|
+
runtime's `abort` syscall, which logs "SBF program panicked" with no location; `const PANIC_ON_OVERFLOW = true`
|
|
321
|
+
makes arithmetic overflow and division by zero panic as `checked_*().unwrap()` does instead of failing with 5100 /
|
|
322
|
+
5101.
|
|
230
323
|
- Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
|
|
231
324
|
"Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`);
|
|
232
325
|
`logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
|
package/docs/security-model.md
CHANGED
|
@@ -87,6 +87,10 @@ Each holds for every instruction of every program the compiler accepts. A break
|
|
|
87
87
|
from the arguments.
|
|
88
88
|
- **`Dup<…>`.** A parameter marked `Dup` may be the same account as another writable one. Reads see every write
|
|
89
89
|
(both are the same bytes), so a value read before a write through the other slot is stale: read, then write.
|
|
90
|
+
- **`NATIVE_ACCOUNT_WRITES`.** A program that declares it gives up the up-front writability check and the
|
|
91
|
+
one-view-per-account refusal for `loadRawMut`, `storeBorsh` and BigVec writes, as a native program has neither: the
|
|
92
|
+
runtime still refuses a changed read-only account, but two loads of one account alias each other. Make the
|
|
93
|
+
original's address and type checks before loading.
|
|
90
94
|
- **Instruction introspection.** The Instructions sysvar holds what the transaction's author put there. Require things
|
|
91
95
|
of the transaction with it (that a repay instruction follows), never treat it as proof of who did what.
|
|
92
96
|
- **Oracles.** `pythPrice` checks verification, feed and age (pass the exponent you scale by); the raw `update.*`
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Stability and the road to 1.0
|
|
2
|
+
|
|
3
|
+
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
|
|
4
|
+
generated programs and error codes, and says so in the CHANGELOG ([versioning
|
|
5
|
+
policy](https://github.com/typesol-lang/.github/blob/main/VERSIONING.md)). This page says what 1.0 will promise, which
|
|
6
|
+
parts are already meant to stay as they are, and what has to be settled first.
|
|
7
|
+
|
|
8
|
+
## What 1.0 will promise
|
|
9
|
+
|
|
10
|
+
From 1.0 on, within a major version:
|
|
11
|
+
|
|
12
|
+
- **Sources keep compiling.** A program that compiles with 1.x compiles with every later 1.y, to a program with the same
|
|
13
|
+
account layouts, IDL, instruction and account discriminators and error codes. New releases add; they do not take away.
|
|
14
|
+
- **Binaries are reproducible and only change for a reason.** A release that changes the binary of a program that uses
|
|
15
|
+
none of its new features says so, with the release manifest's diff (`binary-diff.txt`) as the evidence.
|
|
16
|
+
- **The checks stay.** No check a program gets from its parameter types (owner, discriminator, signer, writability,
|
|
17
|
+
aliasing, checked arithmetic, constraints) is removed or weakened.
|
|
18
|
+
- **The tools keep their interfaces**: `typesol build`, `test` (via `typesol/testing`), `check --json`, `deploy`,
|
|
19
|
+
`verify`, `idl`, the typed client, and `typesol.json`.
|
|
20
|
+
|
|
21
|
+
## Stable already
|
|
22
|
+
|
|
23
|
+
Meant to stay as they are; a change before 1.0 would be a breaking change listed as one:
|
|
24
|
+
|
|
25
|
+
- Types: the integers (`u8` … `u128`, `i8` … `i128`), `boolean`, `Pubkey`, `Hash`, structs, `FixedArray`, `FixedVec`,
|
|
26
|
+
`Vec`, `FixedString`, `Option`, unit and data enums, `u256` in computation.
|
|
27
|
+
- Account parameters and their checks: `Signer`, `Account<T>`, `Mut<T>`, `Init<T>`, `InitIfNeeded<T>`, `Zeroed<T>`,
|
|
28
|
+
optional accounts, token accounts and mints, programs, sysvars, account groups; the constraints (`HasOne`, `Seeds`,
|
|
29
|
+
`CloseTo`, `Ata`, `Address`, `Owner`, `Executable`).
|
|
30
|
+
- Errors and events: error enums and their codes, `require`, `AnchorError`, `emit`, `emitCpi`.
|
|
31
|
+
- CPIs: System, SPL Token, Token-2022, Associated Token, Memo, generic `invoke` with PDA signing.
|
|
32
|
+
- Layouts: account data (Anchor's discriminator and fixed or `@layout borsh` layout), the IDL, the client.
|
|
33
|
+
|
|
34
|
+
## Experimental
|
|
35
|
+
|
|
36
|
+
Useful today, but may still change before 1.0 (each change listed in the CHANGELOG):
|
|
37
|
+
|
|
38
|
+
- The native-program surface (0.40.0): `loadRaw` / `loadRawMut`, the instruction data readers, error code 0,
|
|
39
|
+
`ProgramError`, `panic`, `PANIC_ON_OVERFLOW`, `ERROR_LOG_PREFIX` / `PROGRAM_ERROR_LOG_PREFIX`, `logBase64`,
|
|
40
|
+
`createProgramAddress`.
|
|
41
|
+
- `loadBorsh` / `storeBorsh` (0.42.0): a native program's Borsh accounts read into a local struct and written back.
|
|
42
|
+
- `BigVec<T>` (0.42.0): SPL's `big_vec`, a list over the rest of a native account.
|
|
43
|
+
- `panic(null, location)` (no log line) and `abort()` (Rust's abort, "SBF program panicked") (0.42.0).
|
|
44
|
+
- Local `FixedVec` / `FixedArray` lists of structs, `FixedVec.pushAll`, the instruction data as a list (`slice`,
|
|
45
|
+
`InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0).
|
|
46
|
+
- `epochRewards()` and `EpochRewards` (0.42.0): the EpochRewards sysvar through its syscall.
|
|
47
|
+
- `NATIVE_ACCOUNT_WRITES` (0.42.0): opt-in native write semantics for `loadRawMut`, `storeBorsh` and BigVec writes
|
|
48
|
+
(writability and aliasing left to the runtime). It drops checks a program would otherwise get, so it stays outside
|
|
49
|
+
"the checks stay" promise above: it only applies to programs that declare it.
|
|
50
|
+
- Metaplex CPIs (Token Metadata, Core, Bubblegum), oracles (Pyth, Switchboard), the Stake program.
|
|
51
|
+
- `programAt<P>` / `sysvarAt<S>` and remaining accounts in the typed CPIs (System, Token, ATA, Memo, Stake); a ternary
|
|
52
|
+
between remaining accounts and `AccountInfo` parameters (0.42.0).
|
|
53
|
+
- Functions chosen at run time and lists of functions, closures returned from functions.
|
|
54
|
+
- `typesol/testing`'s epochs and staking: `warpToEpoch`, `nextEpoch`, `StakeCluster`, `stakeActivation`, the vote and
|
|
55
|
+
stake account builders and `readStakeAccount`.
|
|
56
|
+
- Tools: `typesol port`, `clone`, `profile`, `cpi`, the editor plugin, the MCP server and the agent files `init`
|
|
57
|
+
writes, the SBPF v1 and v2 targets.
|
|
58
|
+
|
|
59
|
+
## Before 1.0
|
|
60
|
+
|
|
61
|
+
- **An external audit** of the compiler and runtime ([audit package](audit.md)), its findings fixed and published.
|
|
62
|
+
- **Settle the open edges**, each either supported or refused with a clear error:
|
|
63
|
+
- a struct holding a FixedVec as both an argument and account data (two layouts, one IDL type);
|
|
64
|
+
- helpers that take a writable struct which is not an account (a `loadRaw` view, a local), now refused;
|
|
65
|
+
- `require` with an error code computed at run time that is 0: fails as an overflow (5100) today, where a native
|
|
66
|
+
program returns CUSTOM_ZERO;
|
|
67
|
+
- which experimental parts above become stable, and which stay outside the 1.0 promise.
|
|
68
|
+
- **A release candidate** (1.0.0-rc) used for the showcase ports and the templates, with no breaking change between it
|
|
69
|
+
and 1.0.0.
|
|
@@ -60,6 +60,53 @@ instruction that takes the bump as an argument.
|
|
|
60
60
|
| `t.tokenBalance(address)` | the amount a token account holds, or `null` when it does not exist |
|
|
61
61
|
| `t.warp({ unixTimestamp?, slot?, seconds? })` | moves the Clock: to a timestamp or slot, or forward by `seconds` |
|
|
62
62
|
|
|
63
|
+
## Epochs and staking
|
|
64
|
+
|
|
65
|
+
LiteSVM's `warpToSlot` leaves `Clock.epoch` where it was, and its StakeHistory stays empty, so the Stake program takes
|
|
66
|
+
every delegation as fully active one epoch after it was made. For a program that stakes, these helpers make epochs and
|
|
67
|
+
warmup / cooldown behave as on a cluster:
|
|
68
|
+
|
|
69
|
+
| Helper | Does |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `warpToEpoch(svm, epoch, { secondsPerSlot? })` | moves the Clock to the first slot of `epoch` by the VM's EpochSchedule (warmup epochs included): slot, epoch, leader schedule epoch, `unixTimestamp` (+0.4 s a slot by default) and `epochStartTimestamp`; expires the blockhash. `nextEpoch(svm)` moves one epoch |
|
|
72
|
+
| `new StakeCluster(svms, opts?)` | one or more LiteSVMs that get the same Clock, EpochSchedule and StakeHistory. `cluster.nextEpoch()` / `cluster.warpToEpoch(e)` end each epoch as a cluster does: the StakeHistory gets the epoch's entry (the sum of every stake account's activation at that epoch, plus `base`, the rest of the cluster), then the Clock moves on. `cluster.activation(stake)` gives a stake account's `{ effective, activating, deactivating }` now |
|
|
73
|
+
| `stakeActivation(delegation, epoch, history, newRateActivationEpoch?, { math? })` | a delegation's activation at an epoch: an exact port of the Stake program's `stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0) |
|
|
74
|
+
| `createVoteAccount(svm, payer, { node?, voter?, withdrawer?, commission? })` | a vote account made by the Vote program; returns its address |
|
|
75
|
+
| `createStakeAccount(svm, payer, { staker, withdrawer, lamports, lockup? })` | a stake account made by the Stake program, `lamports` in all (rent-exempt minimum included) |
|
|
76
|
+
| `delegateStake(svm, payer, { stake, vote, staker? })` | delegates it |
|
|
77
|
+
| `readStakeAccount(svm, address)` | the account's StakeStateV2: `{ kind: "Stake", meta, stake: { delegation, creditsObserved }, stakeFlags }`, `Initialized`, `Uninitialized` or `RewardsPool`; `null` when it does not exist |
|
|
78
|
+
| `readStakeHistory(svm)` / `writeStakeHistory(svms, entries)` | the StakeHistory sysvar as a `Map` of epoch → `stakeHistoryEntry(effective, activating, deactivating)` |
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const cluster = new StakeCluster([original.svm, port.svm], { base: stakeHistoryEntry(1000n * SOL) });
|
|
82
|
+
const vote = await createVoteAccount(original.svm, payer);
|
|
83
|
+
// ... the program under test delegates a stake account
|
|
84
|
+
cluster.nextEpoch(); // 9% of the cluster's effective stake may warm up per epoch: 90 SOL here
|
|
85
|
+
expect(cluster.activation(stake).effective).toBe(90n * SOL);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- **The rest of the cluster.** `base` defaults to 400M SOL effective with nothing activating or deactivating: as on
|
|
89
|
+
mainnet, a delegation under 36M SOL warms up in one epoch. Give a smaller `effective`, or `activating` /
|
|
90
|
+
`deactivating` above 9% of it, to make warmup and cooldown take several epochs; `base` may also be a function of
|
|
91
|
+
the epoch. With `allStakeAccounts: false` only the accounts passed to `cluster.track(...)` count.
|
|
92
|
+
- **One history for every VM.** The delegations are read from the first VM; the Clock and EpochSchedule of the first
|
|
93
|
+
VM are copied to the others when the cluster is made, so a differential test's two VMs see the same sysvars.
|
|
94
|
+
- **No gaps.** The Stake program finds an entry by its distance from the newest one, which must be the previous
|
|
95
|
+
epoch's: a history that skips an epoch is misread. The cluster writes one entry per epoch it passes; it refuses a VM
|
|
96
|
+
whose history stops before the previous epoch or has an entry for the current epoch or a later one (an epoch that
|
|
97
|
+
has not ended), and `cluster.warpToEpoch` / `nextEpoch` refuse to go on once the Clock was moved past the history
|
|
98
|
+
some other way. Warping a VM with stake accounts by `warpToEpoch` alone leaves the history behind.
|
|
99
|
+
- **A new LiteSVM's slot.** Its Clock is at epoch 0 but at slot 454,464,000; the first warp moves the slot back to the
|
|
100
|
+
first slot of the epoch warped to (32 for epoch 1 by the default warmup schedule), the timestamps forward.
|
|
101
|
+
- **Float or integer.** The Stake program in LiteSVM 1.6.1 computes warmup and cooldown with f64 (the algorithm
|
|
102
|
+
solana-stake-interface 4.3.0 keeps as the deprecated `stake_activating_and_deactivating`); Stake program 5.1
|
|
103
|
+
(SIMD-0391) uses basis-point integers. They differ by a few lamports once amounts pass 2^53 lamports (about 9M SOL).
|
|
104
|
+
`StakeCluster` uses `math: "float"` by default, so its history and `activation` match LiteSVM to the lamport;
|
|
105
|
+
`stakeActivation` uses the integer algorithm unless given `{ math: "float" }`. Both take the 9% rate from epoch 0
|
|
106
|
+
(`newRateActivationEpoch` 0, as the Stake program has it); `null` gives the original 25%.
|
|
107
|
+
- **Rent.** In LiteSVM 1.6.1 the Stake program holds back the Rent sysvar's minimum for 200 bytes
|
|
108
|
+
(`svm.minimumBalanceForRentExemption(200n)`), which is less than the `rentExemptReserve` its Initialize stores.
|
|
109
|
+
|
|
63
110
|
## Accounts from a cluster
|
|
64
111
|
|
|
65
112
|
To test against accounts that exist on mainnet (a mint, an oracle, another program), list them in `typesol.json` as
|
package/docs/testing.md
CHANGED
|
@@ -19,6 +19,25 @@ run prints its seed; reproduce with `FUZZ_SEED=<n>`, widen with `FUZZ_RUNS` / `F
|
|
|
19
19
|
Compute-unit and binary-size comparisons with Anchor, native Rust and Pinocchio are in the README
|
|
20
20
|
([Numbers](../README.md#numbers)).
|
|
21
21
|
|
|
22
|
+
## Epochs and staking
|
|
23
|
+
|
|
24
|
+
`typesol/testing`'s `warpToEpoch`, `StakeCluster` and `stakeActivation` ([test-your-program.md](test-your-program.md#epochs-and-staking))
|
|
25
|
+
are checked in `test/cli/testing-stake.test.ts` against the Stake program LiteSVM runs, the core BPF build bundled in
|
|
26
|
+
LiteSVM 1.6.1 (its program data holds a 202,280-byte ELF, sha256 `c9cba7f3…cd2352a8`). The oracle is a withdrawal: from a deactivated stake account the
|
|
27
|
+
program lets go of lamports − rent-exempt minimum − the stake it computes as still effective, so withdrawing exactly
|
|
28
|
+
the predicted amount must succeed and one lamport more must fail.
|
|
29
|
+
|
|
30
|
+
- Rate-limited warmup and cooldown over 13 epochs in two VMs: each epoch, the program's held-back stake equals
|
|
31
|
+
`cluster.activation`, merging two delegations fails while either is still activating and succeeds the epoch both are
|
|
32
|
+
fully active, and both VMs' Clock and StakeHistory bytes are equal.
|
|
33
|
+
- Warmup read back at the deactivation epoch, after three rate-limited epochs, then its cooldown.
|
|
34
|
+
- 25 mainnet-sized cases (stakes up to 30M SOL against 300–500M SOL effective, over two cooldown epochs): the program
|
|
35
|
+
matches the f64 algorithm to the lamport, where the integer one is a few lamports off; the case of
|
|
36
|
+
solana-stake-interface's `high_ulp_case` test is among them.
|
|
37
|
+
- `stakeActivation`'s integer algorithm against hand-worked values and the Rust crate's own test cases (bootstrap
|
|
38
|
+
stake, activation and deactivation in one epoch, missing history, the rate change, u128 saturation, the one-lamport
|
|
39
|
+
minimum step).
|
|
40
|
+
|
|
22
41
|
## Reproducing a release
|
|
23
42
|
|
|
24
43
|
From 0.39.0 on, each release's GitHub Release carries its manifest, `typesol-<version>-manifest.json`, attached by
|