@typesol/cli 0.43.0 → 0.44.1
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 +173 -0
- package/NOTICE +71 -0
- package/README.md +25 -11
- package/SECURITY.md +32 -5
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +5 -5
- package/dist/cli.js +196 -72
- package/dist/compiler/analyze.js +4 -0
- package/dist/compiler/emit/alias.d.ts +16 -2
- package/dist/compiler/emit/alias.js +70 -6
- package/dist/compiler/emit/base.d.ts +3 -1
- package/dist/compiler/emit/base.js +20 -3
- package/dist/compiler/emit/borsh.js +11 -5
- package/dist/compiler/emit/calls.d.ts +13 -0
- package/dist/compiler/emit/calls.js +105 -14
- package/dist/compiler/emit/cpi-core.d.ts +9 -1
- package/dist/compiler/emit/cpi-core.js +51 -10
- package/dist/compiler/emit/create.js +22 -11
- package/dist/compiler/emit/expressions.js +6 -1
- package/dist/compiler/emit/function.js +15 -5
- package/dist/compiler/emit/metaplex.js +17 -4
- package/dist/compiler/emit/shared.d.ts +17 -0
- package/dist/compiler/emit/shared.js +36 -3
- package/dist/compiler/emit/statements.js +17 -4
- package/dist/compiler/emit/storage.d.ts +2 -0
- package/dist/compiler/emit/storage.js +16 -8
- package/dist/compiler/emit/token.js +64 -39
- package/dist/compiler/index.d.ts +15 -1
- package/dist/compiler/index.js +40 -3
- package/dist/compiler/toolchain.d.ts +41 -1
- package/dist/compiler/toolchain.js +102 -3
- package/dist/testing-stake.d.ts +2 -1
- package/dist/testing-stake.js +2 -1
- package/dist/testing.js +6 -4
- package/dist/tools/clientgen.d.ts +15 -0
- package/dist/tools/clientgen.js +173 -7
- package/dist/tools/cpigen.d.ts +0 -15
- package/dist/tools/cpigen.js +19 -8
- package/dist/tools/doctor.d.ts +17 -2
- package/dist/tools/doctor.js +64 -4
- package/dist/tools/portgen.js +43 -18
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +173 -6
- package/docs/ai.md +10 -5
- package/docs/architecture.md +1 -1
- package/docs/audit.md +103 -18
- package/docs/case-study-escrow.md +1 -1
- package/docs/case-study-phoenix.md +10 -10
- package/docs/case-study-raydium-amm.md +3 -3
- package/docs/case-study-spl-stake-pool.md +5 -5
- package/docs/cli.md +17 -8
- package/docs/client.md +11 -3
- package/docs/errors.md +2 -2
- package/docs/language.md +16 -9
- package/docs/mainnet.md +21 -10
- package/docs/migrate-from-anchor.md +2 -1
- package/docs/runtime.md +11 -1
- package/docs/security-model.md +79 -12
- package/docs/stability.md +21 -2
- package/docs/testing.md +25 -0
- package/docs/troubleshooting.md +12 -0
- package/llms-full.txt +216 -63
- package/llms.txt +1 -1
- package/package.json +3 -1
- package/runtime/typesol_rt.h +30 -18
- package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/docs/audit.md
CHANGED
|
@@ -7,26 +7,29 @@ with TypeSOL are out of scope; their authors audit them.
|
|
|
7
7
|
|
|
8
8
|
## Scope
|
|
9
9
|
|
|
10
|
-
In order of priority. Line counts at 0.
|
|
10
|
+
In order of priority. Line counts at 0.44.0 (November 2026).
|
|
11
11
|
|
|
12
12
|
| Priority | Component | Files | Lines | Why |
|
|
13
13
|
| --- | --- | --- | ---: | --- |
|
|
14
|
-
| 1 | C runtime | `runtime/typesol_rt.h` | 2,
|
|
15
|
-
| 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` |
|
|
16
|
-
| 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` |
|
|
17
|
-
| 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` |
|
|
18
|
-
| 1 |
|
|
19
|
-
| 1 |
|
|
20
|
-
|
|
|
21
|
-
| 2 |
|
|
14
|
+
| 1 | C runtime | `runtime/typesol_rt.h` | 2,998 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
|
|
15
|
+
| 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 876 | Which checks each account parameter gets, and their order |
|
|
16
|
+
| 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 3,799 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
|
|
17
|
+
| 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 5,694 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
|
|
18
|
+
| 1 | Raw views and the red-black tree | `src/compiler/emit/views.ts`, `rbtree.ts` | 655 | Accounts read without a discriminator at run-time offsets (`loadRaw`, `loadRawAt`, `rawArrayAt`, `BigVec`), their bounds, and the red-black tree's node indexes (`rbTreeAt`) |
|
|
19
|
+
| 1 | Metaplex CPIs | `src/compiler/emit/metaplex.ts` | 1,465 | Token Metadata, Core and Bubblegum instruction layouts and their account lists |
|
|
20
|
+
| 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 2,088 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
|
|
21
|
+
| 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 3,486 | What the language accepts; constraints and account types as parsed from the source |
|
|
22
|
+
| 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,460 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
|
|
22
23
|
| 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, deploy and verification commands |
|
|
23
24
|
|
|
24
|
-
The language surface is `lib/typesol.d.ts` (2,
|
|
25
|
+
The language surface is `lib/typesol.d.ts` (2,581 lines): every type and built-in a program can use, with its
|
|
25
26
|
documented behavior. [docs/language.md](language.md) is the reference; [docs/architecture.md](architecture.md) maps
|
|
26
27
|
the code, [docs/runtime.md](runtime.md) the runtime's conventions.
|
|
27
28
|
|
|
28
29
|
Out of scope: the Solana runtime, platform-tools (clang, lld), the TypeScript compiler, and programs written with
|
|
29
|
-
TypeSOL.
|
|
30
|
+
TypeSOL. The platform-tools are part of what a binary trusts all the same: the tests cover the toolchain the release
|
|
31
|
+
declares (`TESTED_TOOLCHAIN` in `src/compiler/toolchain.ts`: Agave 3.1.10, platform-tools v1.52), builds with another
|
|
32
|
+
one warn, and the review of 0.43.0 traced one defect to how that backend passes struct arguments.
|
|
30
33
|
|
|
31
34
|
## What to check
|
|
32
35
|
|
|
@@ -48,14 +51,96 @@ accepts. Areas where a bug would be most damaging, and where earlier internal re
|
|
|
48
51
|
|
|
49
52
|
## Earlier reviews
|
|
50
53
|
|
|
51
|
-
Internal reviews, by the maintainers
|
|
52
|
-
|
|
54
|
+
Internal reviews, by the maintainers: none of them is an independent audit. Their findings and fixes are in the
|
|
55
|
+
CHANGELOG.
|
|
56
|
+
|
|
57
|
+
### 0.44.0 (2026-11-11)
|
|
58
|
+
|
|
59
|
+
A second internal review, of 0.44.0 as published, over the areas the review of 0.43.0 left out: the token,
|
|
60
|
+
Token-2022 and Metaplex CPI wrappers' emitters, the oracle readers, the Stake wrappers and signature introspection,
|
|
61
|
+
SBPF v1 and v2 builds, optional accounts, `Dup<…>`, and the heap and stack limits. It probed each with targeted
|
|
62
|
+
programs run in LiteSVM against the real token programs, and read the runtime header and the C generated for them.
|
|
63
|
+
|
|
64
|
+
Defects found, fixed in 0.44.1 (its CHANGELOG section, with a test for each):
|
|
65
|
+
|
|
66
|
+
- **A None authority in `mint.create`'s `transferFee` was 33 bytes.** Token-2022 reads a None COption as one byte,
|
|
67
|
+
so the 32 zero bytes after it became the next fields: a mint with a null config authority got no withdraw
|
|
68
|
+
authority and a fee of 0. The standalone `initializeTransferFeeConfig` was right.
|
|
69
|
+
- **A reference held across a resize through another slot.** The reference rule compared names only: with a
|
|
70
|
+
`Dup<…>` pair, a read-only and a writable account of one type, or a loaded struct naming one account, a reference
|
|
71
|
+
made through one slot outlived a push, pop or clear through the other and reached another record. Such programs are
|
|
72
|
+
now refused, as with one name.
|
|
73
|
+
- **Wrapper arguments out of source order.** Twelve token wrappers and the Stake wrappers read their signer seeds
|
|
74
|
+
before an earlier argument's code ran (a PDA other than the one the source names); amounts of `transfer` and the
|
|
75
|
+
like, and account text given to the metadata wrappers, were read after a later argument's code ran.
|
|
76
|
+
- **A 355-byte mint.** Extensions adding up to a Multisig's length made `mint.create` fail every time (Token-2022
|
|
77
|
+
sizes such a mint 357).
|
|
78
|
+
- **`updateExtraAccountMetas` growth.** The 10 KiB limit was counted from the current length, so after a
|
|
79
|
+
`resizeAccount` it could write past the runtime's room into the next account's record.
|
|
80
|
+
- **Heap Vec aliasing in the runtime.** `ts_hvec_reserve` wrote through a type the C aliasing rules let the optimizer
|
|
81
|
+
treat as unrelated to the generated code's (latent; no miscompile seen).
|
|
82
|
+
- **Oracle documentation.** What `pythPrice` and `switchboardValue` do not check was not said plainly; the readers are
|
|
83
|
+
unchanged (docs/security-model.md).
|
|
84
|
+
|
|
85
|
+
Examined and found sound: the other token and Token-2022 wrappers' optional keys (the standalone initializers'
|
|
86
|
+
COptions and Borsh Options, the OptionalNonZero keys of the pointer, hook, group and interest extensions); Token-2022
|
|
87
|
+
mints and accounts with extensions not taken for one another; several large token-metadata buffers in one
|
|
88
|
+
instruction; the Ed25519 signature readers against hostile offsets (into another instruction, a zero count, the same
|
|
89
|
+
bytes under another program id, a fake Instructions sysvar); optional accounts left out or passed unsigned; `Dup<…>`
|
|
90
|
+
pairs without references across a resize; the heap frame and stack limits; and checked arithmetic at every integer
|
|
91
|
+
width, built for SBPF v0, v1 and v2 from the same source, with the same results.
|
|
92
|
+
|
|
93
|
+
Not reviewed: the Metaplex wrappers for unusual argument shapes beyond reading them, the large ports (Marginfi,
|
|
94
|
+
Phoenix, Raydium, the Stake Pool) built for SBPF v1 and v2, and Windows.
|
|
95
|
+
|
|
96
|
+
### 0.43.0 (2026-11-11)
|
|
97
|
+
|
|
98
|
+
An internal review of 0.43.0 as published. It probed the compiler's semantics with targeted programs (helpers,
|
|
99
|
+
references, closures, seeds, `close()`, Borsh decoding), read the runtime header and the C generated for those
|
|
100
|
+
programs, and exercised the tooling (the CLI commands and `typesol/testing`). It did not cover the emitters of the
|
|
101
|
+
Metaplex and token CPI wrappers, the oracles, builds for SBPF v1 and v2, or Windows.
|
|
102
|
+
|
|
103
|
+
Defects found, fixed in 0.44.0 (its CHANGELOG section, with a test
|
|
104
|
+
for each):
|
|
105
|
+
|
|
106
|
+
- **Helper arguments were not copies.** A Pubkey, Option, string or u256 argument reaches a helper as a pointer to the
|
|
107
|
+
caller's object (that is how the SBF backend passes it), so a helper that was not inlined and wrote that object read
|
|
108
|
+
its own write through the parameter: an authorization check on the old value (`rotate(v, v.admin, caller)` with
|
|
109
|
+
`v.admin = v.pending` inside) passed on the new one. Whether it happened depended on clang's inlining.
|
|
110
|
+
- **Seed lists were read at the CPI instead of where they are written.** A list bound to a name, given to a helper,
|
|
111
|
+
or written beside an argument with side effects read its seeds when the CPI ran, so after `st.count += 1n` the
|
|
112
|
+
program signed for another PDA than the one the source names.
|
|
113
|
+
- **The reference rule was skipped for account-group fields and loaded accounts.** A reference into an account used
|
|
114
|
+
after a helper that may move the account's data is refused; it was not when the account reached the helper as an
|
|
115
|
+
account-group field or had been loaded with `loadAccountMut`, and such a program wrote through the stale reference.
|
|
116
|
+
- **Borsh length checks wrapped.** The decoder subtracted before comparing, so for an `Option` of a struct holding an
|
|
117
|
+
Option (or a Vec of such structs) a short buffer wrapped the subtraction and the read went past the end of the
|
|
118
|
+
input: bounded by the struct's size, and read only.
|
|
119
|
+
- **Evaluation order with closures.** A local read before a closure or list callback that changes it kept the new
|
|
120
|
+
value instead of the one it had when read; a string viewing text inside an `Inout` place was not copied for the
|
|
121
|
+
helper taking the place.
|
|
122
|
+
- **`close()` gaps.** Closing an account into itself compiled, `Dup<…>` was accepted on an account the body closes,
|
|
123
|
+
and an account could be used after `close()` in the same instruction (its writes were dropped).
|
|
124
|
+
- **Tooling: IDL text reached generated code unvalidated.** `typesol cpi` and `typesol port` wrote names and other text
|
|
125
|
+
from the IDL they were given into the TypeScript they generate without the checks `typesol client` makes.
|
|
126
|
+
|
|
127
|
+
Programs built with 0.43.0 or earlier should be rebuilt with 0.44.0 or later and redeployed. The first defect is
|
|
128
|
+
the one that can break an authorization check; [security-model.md](security-model.md#review-of-0430-2026-11-11)
|
|
129
|
+
says how to tell whether a program was exposed to it.
|
|
130
|
+
|
|
131
|
+
### Before 0.43.0
|
|
132
|
+
|
|
133
|
+
Internal reviews in October 2026. The releases from 0.26.0 to 0.42.0 were not reviewed one by one: the 0.43.0 review
|
|
134
|
+
read the code that includes them, but probed only the areas above. They add, among others, `u256`, big-endian seeds
|
|
53
135
|
and accounts loaded in the body (0.37.0), stored bumps in nested fields and error members without messages (0.38.0),
|
|
54
136
|
`@code`, `@repr` / `@serialization`, `@bytes` / `@idlName`, `f64`, Options inside Options in arguments and events,
|
|
55
137
|
loop-scoped `loadAccountMut` with `Dup<T>`, account resizing and raw writes, `systemProgram.createPda` (0.39.0), and
|
|
56
138
|
the native-program surface: `loadRaw` / `loadRawMut` (accounts without a discriminator), instruction data readers,
|
|
57
|
-
error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0)
|
|
58
|
-
|
|
139
|
+
error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0), the agent tooling (`typesol mcp`, 0.41.0),
|
|
140
|
+
Borsh accounts without a discriminator, `BigVec<T>`, typed CPIs on remaining accounts and the Stake program's CPIs
|
|
141
|
+
(0.42.0), views at run-time offsets (`loadRawAt`, `rawArrayAt`), the built-in red-black tree (`rbTreeAt`), `Inout<T>`
|
|
142
|
+
helper parameters and `closeRaw` (0.43.0). An external review should include them; the native-program surface first,
|
|
143
|
+
since it skips the account checks Anchor-style parameters get, and the areas the 0.43.0 review did not cover.
|
|
59
144
|
|
|
60
145
|
- **0.25.0** (runtime and emitted checks): two Medium issues fixed, a remaining account loaded mutably twice through
|
|
61
146
|
the same slot, and a Vec element written after its right side resized the Vec; plus a token program ambiguity,
|
|
@@ -67,8 +152,8 @@ the native-program surface first, since it skips the account checks Anchor-style
|
|
|
67
152
|
|
|
68
153
|
## Evidence
|
|
69
154
|
|
|
70
|
-
- **Tests**: by subject under `test/` (`docs/architecture.md`); the count of each run is in CI's log
|
|
71
|
-
|
|
155
|
+
- **Tests**: by subject under `test/` (`docs/architecture.md`); the count of each run is in CI's log.
|
|
156
|
+
`test/security/` holds the attacks.
|
|
72
157
|
- **Differential tests**: the same transactions to TypeSOL and to Anchor twins (`test/anchor-twins`), comparing
|
|
73
158
|
outcomes, account contents and balances after every step.
|
|
74
159
|
- **Model-based fuzzing** (`test/verification/`): arithmetic against BigInt at every width, `u256` against BigInt,
|
|
@@ -93,7 +178,7 @@ git clone https://github.com/typesol-lang/typesol && cd typesol
|
|
|
93
178
|
pnpm install && pnpm build
|
|
94
179
|
pnpm fetch:programs # Metaplex binaries for the token-metadata, Core and Bubblegum tests
|
|
95
180
|
pnpm build:twins # the Anchor twins (Rust + Anchor 1.0.2)
|
|
96
|
-
pnpm test # everything; CI runs it on Ubuntu (Node 22, 24) per change, macOS
|
|
181
|
+
pnpm test # everything; CI runs it on Ubuntu (Node 22, 24) per change, macOS on demand (macos.yml)
|
|
97
182
|
pnpm fuzz # the randomized checks, wide
|
|
98
183
|
```
|
|
99
184
|
|
|
@@ -212,7 +212,7 @@ with their Solscan links in the [performance report](https://typesol.com/report/
|
|
|
212
212
|
|
|
213
213
|
The steps this port followed, in order:
|
|
214
214
|
|
|
215
|
-
1. Generate the skeleton from the Anchor IDL: `npx typesol port target/idl/escrow.json --out programs/escrow.ts`. It
|
|
215
|
+
1. Generate the skeleton from the Anchor IDL: `npx @typesol/cli port target/idl/escrow.json --out programs/escrow.ts`. It
|
|
216
216
|
keeps instruction names, discriminators, account order and error codes.
|
|
217
217
|
2. Turn each `#[account(...)]` into the parameter's type, using the table above and
|
|
218
218
|
[Accounts and constraints](migrate-from-anchor.md#accounts-and-constraints). Keep the account order: it is the
|
|
@@ -10,7 +10,7 @@ rebuild.
|
|
|
10
10
|
deployed executable's hash (`6877a5b732b3494b828a324ec846d526d962223959534dbaf4209e0da3b2d6a9`); OtterSec's
|
|
11
11
|
verification registry lists the program as verified from that commit. The repository was under BUSL 1.1 at c16694d;
|
|
12
12
|
on 2026-05-11 Ellipsis Labs relicensed it under the MIT License (5a34f7f) with the program's sources unchanged since
|
|
13
|
-
c16694d, so the port follows c16694d under MIT ([`test/programs/SOURCES.md`](
|
|
13
|
+
c16694d, so the port follows c16694d under MIT ([`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)).
|
|
14
14
|
|
|
15
15
|
Phoenix is a native program built with solana-program 1.14: a u8 tag, the instruction's Borsh arguments after it,
|
|
16
16
|
accounts by position. A market is one account: a 576-byte header, then a `FIFOMarket` whose bids, asks and traders are
|
|
@@ -22,11 +22,11 @@ Rust panics in solana-program 1.14's format, at the original's source locations.
|
|
|
22
22
|
|
|
23
23
|
| File | Holds |
|
|
24
24
|
| --- | --- |
|
|
25
|
-
| [`phoenix.ts`](
|
|
26
|
-
| [`state.ts`](
|
|
27
|
-
| [`checkers.ts`](
|
|
28
|
-
| [`recorder.ts`](
|
|
29
|
-
| [`matching.ts`](
|
|
25
|
+
| [`phoenix.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/phoenix.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`): the four accounts every instruction starts with, the event recorder, dispatch to the 28 tags |
|
|
26
|
+
| [`state.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/state.ts), [`errors.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/errors.ts) | MarketHeader, the FIFOMarket prefix, the tree keys and values, Seat, PhoenixMarketEvent, the instruction arguments, PhoenixError from code 0 |
|
|
27
|
+
| [`checkers.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/checkers.ts), [`util.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/util.ts) | the account checks in the original's order, the market loader with its twelve sizes; PDAs, the quantity operators with their panics, the token CPIs |
|
|
28
|
+
| [`recorder.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/recorder.ts) | the event recorder: batches of events sent in Log self-CPIs whenever the next event would not fit |
|
|
29
|
+
| [`matching.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/matching.ts), [`book.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/book.ts) | the FIFOMarket: place_order_inner, match_order, check_for_cross, eviction; reduce_order_inner and the cancels built on it |
|
|
30
30
|
| `orders.ts`, `cancel.ts`, `initialize.ts`, `governance.ts`, `seats.ts`, `funds.ts`, `fees.ts` | the instructions by subject |
|
|
31
31
|
|
|
32
32
|
## What is ported
|
|
@@ -82,7 +82,7 @@ compile to the same C as before:
|
|
|
82
82
|
## How it is checked
|
|
83
83
|
|
|
84
84
|
The mainnet binary and the port run in two LiteSVMs under the same program id and the same Clock
|
|
85
|
-
([`phoenix-helpers.ts`](
|
|
85
|
+
([`phoenix-helpers.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/phoenix-helpers.ts)). Every account is made the same way in both, and every
|
|
86
86
|
transaction must give:
|
|
87
87
|
|
|
88
88
|
- the same outcome;
|
|
@@ -110,7 +110,7 @@ file fails unless it compares exactly its own count):
|
|
|
110
110
|
one instruction, the out-of-memory abort at the 513th, books of up to 8,000 orders, the overflow and division panics.
|
|
111
111
|
- **The original's own tests** (`phoenix-upstream.test.ts`; 1,082): each of the 50 test functions at c16694d (the
|
|
112
112
|
integration tests, the matching engine's unit tests, the packet decoder's) is mapped to a case
|
|
113
|
-
([the mapping](
|
|
113
|
+
([the mapping](https://github.com/typesol-lang/typesol/blob/main/showcase/test/phoenix-upstream.md)): 11 were covered already, 37 are added there and run whole,
|
|
114
114
|
2 are not applicable (compile-time type checks of the quantity macros). Each refusal the upstream test expects is
|
|
115
115
|
pinned to the original's error and message, and the upstream test's own assertions (balances, the book, free lots,
|
|
116
116
|
the sequence number, fees) are made on chain.
|
|
@@ -180,7 +180,7 @@ What the port does not reproduce, and how a transaction would reach it:
|
|
|
180
180
|
original out of its compute budget can complete in the port; the tests give both enough.
|
|
181
181
|
- **Memory, counted.** Phoenix allocates on solana-program 1.14.9's bump heap: 32 KiB from the top down, never freed,
|
|
182
182
|
and an allocation past it aborts with "Error: memory allocation failed, out of memory". The port keeps its own lists
|
|
183
|
-
fixed and counts Phoenix's heap instead ([`heap.ts`](
|
|
183
|
+
fixed and counts Phoenix's heap instead ([`heap.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/heap.ts)), charge by charge as the
|
|
184
184
|
Rust allocates: the entrypoint's 48 bytes per account entry and 72 per distinct account, the discriminant lines, the
|
|
185
185
|
event recorder, the status checks' messages (built even when they pass), each batch line, each SPL Token transfer's
|
|
186
186
|
instruction, the cancels' boxed tree iterators with their stacks and the ids they collect, CancelMultipleOrdersById's
|
|
@@ -188,7 +188,7 @@ What the port does not reproduce, and how a transaction would reach it:
|
|
|
188
188
|
runs) and the "Insufficient funds" lines of the orders it skips, the placed order ids and their Borsh bytes. So a
|
|
189
189
|
transaction that fills the heap (with up to 255 account entries, which Phoenix ignores past the ones it reads, or with
|
|
190
190
|
a CPI's larger instruction data) aborts in the port at the same allocation, after the same log lines and batches.
|
|
191
|
-
[`phoenix-limits.test.ts`](
|
|
191
|
+
[`phoenix-limits.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/phoenix-limits.test.ts) finds the original's boundary and compares both
|
|
192
192
|
sides of it (one account entry fewer succeeds, the next aborts) for CancelAllOrders and its free-funds form (257 to
|
|
193
193
|
512 orders, bids and asks, 4 to 20 accounts of their own, top-level and through a CPI), CancelUpTo with a count and
|
|
194
194
|
with a search limit, ForceCancelOrders, CancelMultipleOrdersById through a CPI (230 and 340 entries; 341 always runs
|
|
@@ -11,9 +11,9 @@ its own errors. The port keeps all of that.
|
|
|
11
11
|
|
|
12
12
|
| File | Holds |
|
|
13
13
|
| --- | --- |
|
|
14
|
-
| [`raydium_amm.ts`](
|
|
15
|
-
| [`state.ts`](
|
|
16
|
-
| [`math.ts`](
|
|
14
|
+
| [`raydium_amm.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-amm/raydium_amm.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`), every instruction, the token and system CPIs, the P&L calculation |
|
|
15
|
+
| [`state.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-amm/state.ts) | AmmInfo (752 bytes), TargetOrders, AmmConfig, Fees, the ray_log records, the 61 errors (codes 0–60) |
|
|
16
|
+
| [`math.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-amm/math.ts) | decimal normalization, the constant-product amounts, the exchange rates, with the original's panics at their places |
|
|
17
17
|
|
|
18
18
|
## What is ported
|
|
19
19
|
|
|
@@ -10,7 +10,7 @@ deployed code carries a fee-cap message main only gained later. The tag `program
|
|
|
10
10
|
branch) rebuilt with `solana-verify build --library-name spl_stake_pool --base-image
|
|
11
11
|
solanafoundation/solana-verifiable-build:3.1.14` gives the deployed executable's hash
|
|
12
12
|
(`8df58bc9f9428c02bf34fa845ae2961274156e7ff07a8dc1be0018dd765baeff`). The port follows that tag
|
|
13
|
-
([`test/programs/SOURCES.md`](
|
|
13
|
+
([`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)).
|
|
14
14
|
|
|
15
15
|
Stake Pool is a native program: one entrypoint decodes a Borsh instruction (a tag byte, then the variant's fields,
|
|
16
16
|
every byte consumed), the processor takes its accounts by position, the pool account is plain Borsh with Options and
|
|
@@ -19,9 +19,9 @@ data enums, the validator list is a header and a `BigVec` of 73-byte entries ove
|
|
|
19
19
|
|
|
20
20
|
| File | Holds |
|
|
21
21
|
| --- | --- |
|
|
22
|
-
| [`stake_pool.ts`](
|
|
23
|
-
| [`state.ts`](
|
|
24
|
-
| [`util.ts`](
|
|
22
|
+
| [`stake_pool.ts`](https://github.com/typesol-lang/typesol/blob/main/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`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/spl-stake-pool/state.ts), [`errors.ts`](https://github.com/typesol-lang/typesol/blob/main/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`](https://github.com/typesol-lang/typesol/blob/main/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
25
|
| `admin.ts`, `validators.ts`, `update.ts`, `sol.ts`, `stake_deposit.ts`, `stake_withdraw.ts`, `rebalance.ts`, `metadata.ts` | the instructions by subject |
|
|
26
26
|
|
|
27
27
|
## What is ported
|
|
@@ -66,7 +66,7 @@ bytes in every account it names. There are 2,107 such transactions in six files:
|
|
|
66
66
|
authorities, read-only and repeated accounts (the original's RefCell panics included), pools of 50 to 60 validators,
|
|
67
67
|
warmup and cooldown over several epochs.
|
|
68
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](
|
|
69
|
+
`program/tests` at the tag is mapped to a case ([the mapping](https://github.com/typesol-lang/typesol/blob/main/showcase/test/spl-stake-pool-upstream.md)): 143
|
|
70
70
|
were covered already, 78 are added there, none is left out. huge_pool.rs runs at 3,000 and 20,000 validators.
|
|
71
71
|
- **A random walk over epochs** (`spl-stake-pool-fuzz.test.ts`): validators added and removed, users depositing and
|
|
72
72
|
withdrawing SOL and stake, rebalancing, updates in random chunks, fee and authority changes, rewards, slow warmup,
|
package/docs/cli.md
CHANGED
|
@@ -6,24 +6,33 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
|
|
|
6
6
|
|
|
7
7
|
| Command | What it does |
|
|
8
8
|
| --- | --- |
|
|
9
|
-
| `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 `.
|
|
9
|
+
| `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), `.gitignore`, the rules for AI coding agents (`AGENTS.md`, `CLAUDE.md` importing it, `.cursor/rules/typesol.mdc`) and the MCP server configuration (`.mcp.json`, `.cursor/mcp.json`; see [ai.md](ai.md)). `<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. |
|
|
10
10
|
| `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. |
|
|
11
|
-
| `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. |
|
|
12
|
-
| `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
|
|
13
|
-
| `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. |
|
|
14
|
-
| `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 }] }
|
|
11
|
+
| `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools (and a `toolchain` row: the tested ones, or untested with both versions), 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. |
|
|
12
|
+
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--toolchain-strict] [--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 TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. 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. |
|
|
13
|
+
| `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
|
|
14
|
+
| `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 }] }`, always (a missing file or unreadable `--files` input is a diagnostic too, exit 1 or 2); `--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). |
|
|
15
15
|
| `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. |
|
|
16
16
|
| `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
|
|
17
|
-
| `typesol
|
|
18
|
-
| `typesol
|
|
17
|
+
| `typesol mcp` | Serve the Model Context Protocol on stdio for AI coding agents: tools to check a program (errors with hints), read its IDL, search the docs and read the rules a TypeSOL program follows. The `.mcp.json` / `.cursor/mcp.json` that `init` writes start it as `npx --no-install typesol mcp` (the project's own copy); see [ai.md](ai.md). |
|
|
18
|
+
| `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …] [--toolchain-strict]` | Build (`--toolchain-strict` as for `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. It needs a cluster, `--url` or `json_rpc_url` in the Solana CLI config: it never falls back to the CLI's default. Before sending anything it prints the cluster's host and the payer, 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. |
|
|
19
|
+
| `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`); it prints the cluster's host and the payer before sending. |
|
|
19
20
|
| `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. |
|
|
20
21
|
| `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`). |
|
|
21
22
|
| `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). |
|
|
22
|
-
| `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. |
|
|
23
|
+
| `typesol verify <program\|file.ts> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <cli config>] [--sbpf …] [--manifest <name.build.json>]` | 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. On a mismatch it prints the rebuild's toolchain (clang, platform-tools, host, TypeSOL) and the deployed build's when a build manifest's binary hash is the deployed bytes' (`--manifest`, `<deployed>.build.json` next to a given `.so`, or the local build's), and what differs; otherwise it says the deployed side's toolchain is unknown (a program on chain records none). |
|
|
23
24
|
| `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). |
|
|
24
25
|
| `typesol help <command>` | Same as `typesol <command> --help`. |
|
|
25
26
|
| `typesol --version` | Print the version. |
|
|
26
27
|
|
|
28
|
+
`clone`, `client --address`, `verify` and `idl publish` give up on an RPC request after 30 seconds
|
|
29
|
+
(`TYPESOL_RPC_TIMEOUT=<seconds>` changes it) and, like `doctor` and `deploy`, name only the RPC's host and the cause
|
|
30
|
+
when one fails (an RPC URL can carry an API key). A `--config` file that does not exist is a usage error everywhere.
|
|
31
|
+
|
|
32
|
+
Builds (`build`, `deploy`, `verify`, `typesol/testing`) compare the active clang with the one the release is tested
|
|
33
|
+
with (`TESTED_TOOLCHAIN` in `typesol/compiler`: Agave 3.1.10, platform-tools v1.52): another one gets one warning per
|
|
34
|
+
process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `warn` is the default.
|
|
35
|
+
|
|
27
36
|
## typesol.json
|
|
28
37
|
|
|
29
38
|
```json
|
package/docs/client.md
CHANGED
|
@@ -79,6 +79,11 @@ integers and floats are `number`, `Pubkey` is kit's `Address`, `string` and `Fix
|
|
|
79
79
|
as in the program. Names are camelCase. For Anchor IDLs, data enums use `__kind`, as Codama-generated clients do. The
|
|
80
80
|
file uses no TypeScript-only syntax (no `enum`), so it also runs under Node's type stripping.
|
|
81
81
|
|
|
82
|
+
Anchor IDLs can also hold types a TypeSOL program does not: `u256`/`i256` are `bigint` (32 bytes, little-endian), and
|
|
83
|
+
`Option<Option<T>>` is `Option<T> | null` with kit's `Option` inside, so the three values stay apart: `null` is None,
|
|
84
|
+
`none()` is Some(None) and `some(x)` (or `x`) is Some(Some(x)). A type that holds itself through a Vec or an Option
|
|
85
|
+
(`enum Shape { Dot, Rec { kids: Vec<Shape> } }`) is encoded and decoded to any depth.
|
|
86
|
+
|
|
82
87
|
## Safety
|
|
83
88
|
|
|
84
89
|
An IDL can come from anywhere, so `typesol client` refuses one whose names are not identifiers, whose discriminators or
|
|
@@ -92,9 +97,12 @@ Anchor IDLs are refused with a hint to convert them (`anchor idl convert`).
|
|
|
92
97
|
`Program data:` line only while this program is the innermost one running, and `eventsOf` reads only the `emitCpi`
|
|
93
98
|
inner instructions that call this program (it needs `tx.transaction`'s account keys for that). `parseCpiEvents(data)`
|
|
94
99
|
on its own does not check the program: give it this program's inner instructions only.
|
|
95
|
-
- **Not filled in
|
|
96
|
-
PDAs whose program is another account's field, and a PDA seeded from
|
|
97
|
-
helper from the values). `typesol client` prints a note for each.
|
|
100
|
+
- **Not filled in by the builder** (pass them): PDAs seeded from a field of another account's data (`state.owner`;
|
|
101
|
+
`resolve` reads the account and derives them), PDAs whose program is another account's field, and a PDA seeded from
|
|
102
|
+
its own fields (derive it with its `pdas` helper from the values). `typesol client` prints a note for each. PDAs
|
|
103
|
+
seeded from a field of a struct argument, at any depth (`params.inner.id`), are filled in.
|
|
104
|
+
- **Left out, with a note**: instructions, accounts and types using `Option<Option<Option<T>>>` or deeper, and types
|
|
105
|
+
the client cannot express (listed by `typesol client`).
|
|
98
106
|
- **Anchor IDLs**: zero-copy (`bytemuck`) accounts decode and encode at their `#[repr(C)]` offsets as the program sees
|
|
99
107
|
them on SBF (padding included; `packed` and `align` honored; 128-bit integers align to 8). Generic types become one
|
|
100
108
|
type per use with concrete arguments (`Pair<u64, 2>` is `PairU64N2`). Left out, with a note: zero-copy types with
|
package/docs/errors.md
CHANGED
|
@@ -20,7 +20,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
|
|
|
20
20
|
| 2016 / 2017 / 2018 | mint authority / freeze authority / decimals mismatch (2018: an existing mint `createIfNeeded` found) |
|
|
21
21
|
| 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
|
|
22
22
|
| 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…) |
|
|
23
|
-
| 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
|
|
23
|
+
| 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount); also `close(a, b)` in a helper given one account for both |
|
|
24
24
|
| 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` |
|
|
25
25
|
| 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
|
|
26
26
|
| 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
|
|
@@ -34,7 +34,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
|
|
|
34
34
|
| 3010 | account must sign (AccountNotSigner; also a new keypair account a `create(payer, null, …)` makes) |
|
|
35
35
|
| 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
|
|
36
36
|
| 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) |
|
|
37
|
-
| 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
|
|
37
|
+
| 3016 | account would grow more than 10 KiB in one instruction (counted from its length when the instruction started), or grow without a payer (AccountReallocExceedsLimit) |
|
|
38
38
|
| 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
|
|
39
39
|
| 4102 | cast overflow (InvalidNumericConversion) |
|
|
40
40
|
| 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
|
package/docs/language.md
CHANGED
|
@@ -8,7 +8,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| 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) |
|
|
10
10
|
| Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
|
|
11
|
-
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
|
|
11
|
+
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits; the amount, also in `<<=` / `>>=`, may be any integer type). `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), `min` / `max`, `switch` and as a list index (5104 past u64); a shift amount or an exponent is a u128 or smaller (compile error); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
|
|
12
12
|
| Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
|
|
13
13
|
| Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
|
|
14
14
|
| Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+ (`/** @code 6200 */` before a member jumps to that code, Anchor's `Name = 200`; `Name = ""` has no message in the IDL); `require(cond, "message")` makes an error of its own (`RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL); `require(cond, AnchorError.RequireKeysEqViolated)` fails with one of Anchor's own codes (2502 here; any anchor-lang `ErrorCode` can be raised this way); `require(cond, code)` with a `u32` value fails with that code as computed at run time (a helper returning its error: `require(r.err === 0n, r.err)`). See [errors.md](errors.md) |
|
|
@@ -26,7 +26,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
26
26
|
| Events | `emit<Deposited>({ owner: owner.key, amount })` — Anchor-format `Program data:` logs, listed under `events` in the IDL; event structs may hold `string`, `Option`, `FixedVec<T, N>` (its fixed layout, as in account data), `Vec<T>` (Borsh: from a Vec argument or a list in account data) and `Option<Vec<T>>`; a nested struct given as a literal is Borsh too |
|
|
27
27
|
| Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
|
|
28
28
|
| 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 |
|
|
29
|
-
| 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 |
|
|
29
|
+
| 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, also when it was made through another parameter that may be the same account: a `Dup<…>` pair, a read-only and a writable account of one type, a struct loaded with `loadAccount` / `loadAccountMut`). 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 |
|
|
30
30
|
| 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 |
|
|
31
31
|
| 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) |
|
|
32
32
|
| 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 |
|
|
@@ -51,17 +51,17 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
51
51
|
| Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58; an `Option` of an integer, boolean, Pubkey or Hash as its value, or `null` when empty, as JS prints it: after `x !== null` that is the value) — built on the 32 KiB heap (5110 when full): a template is joined in one allocation, text known at compile time (literals, string and Pubkey constants) is folded in, and `s += …` grows the newest heap string in place |
|
|
52
52
|
| `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
|
|
53
53
|
| Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash` (a PDA seed too: its 32 bytes, as Marginfi seeds an order with the hash of its bank keys); `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump, or both from one search with `const [address, bump] = findProgramAddressWithBump(seeds, program)` (Rust's `let (address, bump) = …`; each separate search costs about 450 CU per bump tried); `programId()` → this program's address; `a.compare(b)` orders Pubkeys and Hashes as Rust orders their 32 bytes (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
|
|
54
|
-
| Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted) (mainnet program unless `SwitchboardFeed<"devnet">`) |
|
|
54
|
+
| Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted; staleness counts slots from the feed's `result.slot`; the 18-decimal result is scaled to `decimals` rounding toward zero) (mainnet program unless `SwitchboardFeed<"devnet">`). Neither reader checks the price's sign or zero, the confidence (Pyth's `conf`, Switchboard's spread of samples), or a publish time or result slot in the future (it counts as fresh): check what your program relies on |
|
|
55
55
|
| Randomness | A chain has no secret randomness of its own: slot hashes and timestamps are known to, or chosen by, the block producer. `SwitchboardRandomness` (Switchboard On-Demand's RandomnessAccountData; owner, discriminator and size checked) gives verifiable randomness by commit and reveal: commit while `r.seedSlot === currentSlot() - 1n` and store `r.key` and `r.seedSlot`; settle in a later transaction after checking both, with `r.value()` (32 bytes) or `r.valueU64()`, which fail (5111) unless the value was revealed in this slot. See test/fixtures/coinflip.ts |
|
|
56
56
|
| Multiple files | `import { Side, min } from "./math"` — structs, enums, constants and helpers can live in other files; only the entry file's exported functions are instructions; names are program-wide, so imports from TypeSOL files cannot be renamed; error codes number imported files first |
|
|
57
57
|
| Loops | `for (let i = 0n; i < n; i++)` (or two counters, `for (let i = 0n, j = n; i < j; i++, j--)`: several declarations, and comma-separated updates run in order after each pass, `continue` included), `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
|
|
58
|
-
| Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
|
|
58
|
+
| Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place. Pubkey, Option, string and u256 parameters are passed by pointer too (the SBF target passes a C struct as a pointer to the caller's object and does not copy it); a helper that can write (it takes accounts, remaining accounts or `Inout<T>` places) gets a copy taken at the call, unless the argument is a local, a temporary, an instruction argument, a constant, an account's key, the program id or a parameter of the calling helper, which nothing it is given reaches; a helper that writes nothing reads the caller's value in place. Text a string argument views in account data or in an `Inout<T>` place is copied for such a helper too; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
|
|
59
59
|
| `Inout<T>` parameters | `function addEvent(rec: Inout<Recorder>, e: Event): void { rec.count += 1n; … }` is Rust's `rec: &mut Recorder`: the helper gets the caller's place itself (a pointer, no copy: about the compute units of the same code written inline) and the caller sees its writes after the call, as JS shares an object passed to a function. `T` is a fixed-size struct, a `FixedArray<T, N>` or a `FixedVec<T, N>` (its `push`, `pop` and `clear` included). The argument is a writable place: a local struct or list, a `loadBorsh` local, a field path of a local, of a `loadRawMut` view or of a `Mut<T>` account, a list element (`book.levels.get(i)`, a narrowed Option's value), another `Inout` parameter (passed on), or a literal (a fresh value nobody else sees); a read-only one (a field of an `Account<T>`, a `loadRaw` view, an instruction argument, a read-only parameter) is a compile error naming what to change. At each call, so that the helper's parameter is the only way to the place while it runs: no other argument may share storage with an Inout one (one place inside the other; two elements of one list, whatever their indexes, a BigVec slice's elements included; an account and a place inside it; a read-only struct argument inside it: pass a copy); an element of a `Vec` or `BigVec` is refused when the call may resize or filter that list (the helper takes writable or remaining accounts), since its elements would move; and a reference into the place (`const e = p.items.get(0n)`) that is read after the call is refused, since the helper may replace what it points at (copy the fields first, or read them through the place). Places that differ in the source but may be one account at run time (two `Dup<…>` accounts, a writable and a read-only account, two native views under `NATIVE_ACCOUNT_WRITES`: `loadRawMut`, `loadRawMutAt`, `rawArrayMutAt` elements, `rbTreeMutAt` nodes, a helper's own account parameters) are compared before the call: 2040 when they overlap. The comparison covers an Inout argument against every other argument passed in place (another Inout one, a read-only struct, array or list, an account), so a read-only argument cannot change under the helper while it writes; one copied for the call (a helper that takes accounts gets a copy of account data) shares nothing and is not compared. One pair is left to run time: a place in a `loadRawMut` view passed with the `RemainingAccount` it was loaded from (without `NATIVE_ACCOUNT_WRITES` a second `loadRawMut` of it in the helper fails, 2040; with the flag the helper can load and write the same bytes, the flag's trade-off). Integers, Pubkeys, strings and Options are values, which JS copies into a function too: return the new value (`x = f(x)`) or keep it in a struct and take `Inout<ThatStruct>`. `Vec<T>`, `BigVec<T>`, accounts and data enums are refused with what to write instead, and so is `Inout<T>` anywhere but a helper's parameter. Closures (and helpers expanded because they were given one) take `Inout<T>` the same way; their struct parameters were references already |
|
|
60
60
|
| Arrow functions and closures | `const fee = (x: u64): u64 => x / 100n` (or `const f = function (…) {…}`) at the top level or inside a function. One that reads or writes the enclosing function's variables (a closure: `let total = 0n; const add = (v: u64): void => { total += v; }`) is expanded where it is called: its names mean what they meant where it was declared, struct parameters are references, `return` leaves the closure; it cannot call itself. One that captures nothing becomes a helper. Parameter types may be left out on closures (taken from the arguments). Functions are values where they can be expanded: `const h = g` names the same function, and a function that returns one (`function adder(n: u64): (x: u64) => u64 { return (x) => x + n; }`) makes a closure where it is called (`const add5 = adder(5n)`, or `adder(5n)(x)`). A function can be chosen at run time between named ones, `const g = k === 1n ? dbl : inc` (the condition is read once, there; a call runs only the chosen one), and a list of named functions can be run in turn, `for (const f of [dbl, inc]) total += f(x)` (unrolled; `continue` and `break` work) |
|
|
61
61
|
| Functions as arguments | a helper may take a function parameter (`function applyTwice(f: (x: u64) => u64, v: u64): u64`): it is compiled once per named function passed (a helper or a local function that captures nothing). An arrow written at the call works too (`applyTwice((x) => x * 3n, v)`: its types come from the parameter) when it reads none of the function's variables. Given a closure (one that reads them), the helper is expanded where it is called instead, like a closure, so it runs where the closure can (its type parameters bound from the call, its accounts the caller's) |
|
|
62
62
|
| List callbacks | on a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument: `forEach`, `some`, `every`, `find` (an Option of the element; scalar elements; on struct elements read a field with `xs.find(f)!.qty`, which aborts with 5108 when nothing matched, or `xs.find(f)?.qty`, an Option), `findIndex` (i64, -1 when absent), `reduce(fn, initial)`, `includes(value)`, `indexOf(value)` (i64), `map` and `filter`. The arrow written at the call is expanded into a loop (elements as `list.get(i)` gives them, structs by reference) and may read and write the function's variables. A `map` / `filter` chain used right away (`xs.filter(f).map(g).reduce(h, 0n)`, `.length`, `for … of`) is one loop that stores nothing; callbacks after a filter get the index among the elements it let through. Stored (`const ys = xs.filter(f)`), it is a FixedVec on the stack as big as the list it starts from; from a `Vec`, give the size: `const ys: FixedVec<u64, 16> = …` (at most 2 KiB; one element more aborts with 5104). `map` gives integers, booleans, Pubkeys or enums; stored with a `FixedVec<Struct, N>` or `FixedVec<FixedString<N>, M>` annotation it gives structs (`(o) => ({ qty: o.qty })`) or text, and inside a chain it gives structs when the callback names its struct, `xs.map((o): Scored => ({ … })).filter(…).reduce(…)` (one struct per element, nothing stored) |
|
|
63
63
|
| 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) |
|
|
64
|
-
| 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()`) |
|
|
64
|
+
| 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()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list callback writing it) |
|
|
65
65
|
| `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
|
|
66
66
|
| 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) |
|
|
67
67
|
| 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) |
|
|
@@ -97,7 +97,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
97
97
|
| `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 { … }` |
|
|
98
98
|
| `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 |
|
|
99
99
|
| `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 |
|
|
100
|
-
| `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) |
|
|
100
|
+
| `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 (as Token-2022 does: extensions adding up to a Multisig's 355 bytes give a 357-byte mint) and initializes each before InitializeMint2; a `null` authority is sent as Token-2022's empty COption. 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) |
|
|
101
101
|
| `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) |
|
|
102
102
|
| `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` |
|
|
103
103
|
| `Mint` / `Mut<Mint>` | owned by SPL Token or Token-2022, initialized; `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
|
|
@@ -120,7 +120,9 @@ Two writable parameters can never be the same account: aliasing is refused with
|
|
|
120
120
|
account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
|
|
121
121
|
(Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not created, closed
|
|
122
122
|
or `@layout borsh`; a close destination may be one, the rent reaching it through either): a write through either is
|
|
123
|
-
seen through the other, so read what you need before writing. A
|
|
123
|
+
seen through the other, so read what you need before writing. A reference into one of them (`const e = a.entries.get(i)`)
|
|
124
|
+
cannot be used after a push, pop or clear through the other moved that data, as with one name (compile error); copy
|
|
125
|
+
the fields first. A remaining account
|
|
124
126
|
can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
|
|
125
127
|
with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
|
|
126
128
|
`AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
|
|
@@ -142,7 +144,9 @@ of a position, as Raydium CLMM's tick arrays).
|
|
|
142
144
|
come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
|
|
143
145
|
`freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
|
|
144
146
|
`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
|
|
145
|
-
- `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
|
|
147
|
+
- `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts (the destination
|
|
148
|
+
is another writable account; the account is not used after it in the function, except its `key`: compile errors, or
|
|
149
|
+
2040 at run time in a helper given one account twice)
|
|
146
150
|
- `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
|
|
147
151
|
stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
|
|
148
152
|
among up to 256 addresses for the same seeds
|
|
@@ -187,7 +191,10 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
|
|
|
187
191
|
lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
|
|
188
192
|
- A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
|
|
189
193
|
wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
|
|
190
|
-
signer([…, bump])`.
|
|
194
|
+
signer([…, bump])`. A named list, and one given to a helper, holds its seeds as they were when it was written (JS
|
|
195
|
+
evaluates the array then): a field or local changed afterwards does not change what it signs for. A list written in
|
|
196
|
+
a call (`transfer(…, signer([…]))`, `create(payer, [...], space)`) holds them as they were when the list was read,
|
|
197
|
+
even when a later argument changes a seed.
|
|
191
198
|
- `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
|
|
192
199
|
- After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
|
|
193
200
|
A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
|