@typesol/cli 0.45.0 → 0.46.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 +227 -0
- package/README.md +64 -17
- package/SECURITY.md +9 -7
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/cli.js +33 -15
- package/dist/compiler/analyze.js +57 -6
- package/dist/compiler/diagnostics.d.ts +4 -3
- package/dist/compiler/diagnostics.js +10 -6
- package/dist/compiler/emit/base.d.ts +1 -1
- package/dist/compiler/emit/calls.js +18 -5
- package/dist/compiler/emit/cpi-core.d.ts +3 -1
- package/dist/compiler/emit/cpi-core.js +8 -4
- package/dist/compiler/emit/expressions.d.ts +14 -0
- package/dist/compiler/emit/expressions.js +52 -4
- package/dist/compiler/emit/shared.d.ts +8 -1
- package/dist/compiler/emit/shared.js +8 -1
- package/dist/compiler/emit/statements.d.ts +8 -3
- package/dist/compiler/emit/statements.js +68 -3
- package/dist/compiler/emit/storage.js +5 -1
- package/dist/compiler/hints.d.ts +7 -0
- package/dist/compiler/hints.js +58 -9
- package/dist/compiler/index.d.ts +5 -0
- package/dist/compiler/index.js +10 -1
- package/dist/compiler/model.js +3 -2
- package/dist/compiler/toolchain.d.ts +50 -2
- package/dist/compiler/toolchain.js +96 -11
- package/dist/node-version.d.ts +4 -0
- package/dist/node-version.js +12 -0
- package/dist/tools/doctor.d.ts +41 -0
- package/dist/tools/doctor.js +96 -14
- package/dist/workspace.d.ts +9 -2
- package/dist/workspace.js +13 -3
- package/docker/deps/0.46.0.lock.json +1206 -0
- package/docs/ai.md +2 -1
- package/docs/architecture.md +7 -3
- package/docs/audit.md +6 -6
- package/docs/case-study-phoenix.md +1 -1
- package/docs/case-study-raydium-amm.md +1 -1
- package/docs/case-study-spl-stake-pool.md +1 -1
- package/docs/cli.md +42 -4
- package/docs/errors.md +22 -8
- package/docs/glossary.md +210 -0
- package/docs/language-accounts.md +499 -0
- package/docs/language-basics.md +389 -0
- package/docs/language-builtins.md +411 -0
- package/docs/language-chain.md +198 -0
- package/docs/language-cpi.md +470 -0
- package/docs/language-errors-events.md +184 -0
- package/docs/language-native.md +493 -0
- package/docs/language-pdas.md +198 -0
- package/docs/language-statements.md +620 -0
- package/docs/language-types.md +601 -0
- package/docs/language.md +190 -467
- package/docs/mainnet.md +18 -3
- package/docs/migrate-from-anchor.md +7 -6
- package/docs/security-model.md +3 -3
- package/docs/stability.md +3 -1
- package/docs/test-your-program.md +52 -15
- package/docs/troubleshooting.md +222 -100
- package/lib/typesol.d.ts +67 -22
- package/llms-full.txt +4915 -634
- package/llms.txt +12 -1
- package/package.json +2 -2
- package/releases/0.45.0.json +732 -0
- package/ts-plugin/index.js +16 -5
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
# Accounts
|
|
2
|
+
|
|
3
|
+
An instruction's account parameters are typed, and each type says what is checked before the body runs: the owner,
|
|
4
|
+
the discriminator, the size, signatures, writability, constraints between accounts. This page lists the account types,
|
|
5
|
+
the constraint types and the account built-ins, with what each generates and the error codes. Part of the
|
|
6
|
+
[language guide](language.md). For deriving and signing for PDAs, see [PDAs](language-pdas.md); for the order in which
|
|
7
|
+
the checks run, [which error a transaction gets](errors.md#which-error-a-transaction-gets).
|
|
8
|
+
|
|
9
|
+
## Account parameters and the checks they emit
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { type Account, type Init, type Mut, type Pubkey, type Signer, type SystemProgram, type u64 } from "typesol";
|
|
13
|
+
|
|
14
|
+
export interface Note {
|
|
15
|
+
author: Pubkey;
|
|
16
|
+
likes: u64;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function write(author: Mut<Signer>, note: Init<Note>, systemProgram: SystemProgram): void {
|
|
20
|
+
note.create(author, null);
|
|
21
|
+
note.author = author.key;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function like(fan: Signer, note: Mut<Note>, original: Account<Note>): void {
|
|
25
|
+
note.likes += original.likes > 0n ? 1n : 2n;
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
| Parameter type | Checked before your code runs |
|
|
30
|
+
| --- | --- |
|
|
31
|
+
| `Signer` / `Mut<Signer>` | signed (3010) and, for `Mut`, writable (2000) |
|
|
32
|
+
| `Account<T>` / `Mut<T>` | in this order: initialized (3012 for an empty system account), owned by this program (3007), data large enough (3003, discriminator included), 8-byte discriminator matches (3002); for `Mut`, writable (2000), checked before them. A [zero-copy](glossary.md#zero-copy) type is checked as Anchor's `AccountLoader` checks it ([below](#zero-copy-types-as-anchors-idl-describes-them)) |
|
|
33
|
+
| `Init<T>` | writable; the body creates it ([below](#creating-accounts)) |
|
|
34
|
+
| `InitIfNeeded<T>` | writable; the body creates it when it does not exist, else checks it |
|
|
35
|
+
| `Zeroed<T>` | allocated by the client, not yet initialized, writable ([below](#zeroed-accounts)) |
|
|
36
|
+
| `TokenAccount` / `Mut<TokenAccount>` | an initialized token account of SPL Token or Token-2022 (extensions allowed, multisig accounts refused): 3012 for an empty system account (never created, or closed), 3007 for an account of another program, 3003 for a token program's account that is not an initialized token account (or mint) of its length |
|
|
37
|
+
| `Mint` / `Mut<Mint>` | an initialized mint of SPL Token or Token-2022: the same codes as a token account |
|
|
38
|
+
| `SystemAccount` / `Mut<SystemAccount>` | owned by the System Program, e.g. a wallet (Anchor's `SystemAccount`, 3011) |
|
|
39
|
+
| `AccountInfo` / `Mut<AccountInfo>` | nothing (writable for `Mut`): check what you rely on yourself |
|
|
40
|
+
| `SystemProgram`, `TokenProgram`, `Token2022Program` | the exact program address (3008) |
|
|
41
|
+
| `TokenInterface` | either token program |
|
|
42
|
+
| `AssociatedTokenProgram`, `MemoProgram`, `TokenMetadataProgram`, `StakeProgram`, `MplCoreProgram`, `BubblegumProgram` | that program's address (3008); their methods are CPIs ([calling other programs](language-cpi.md)) |
|
|
43
|
+
| `Program<"Address…">` | the exact program address (3008) and executable (3009) |
|
|
44
|
+
| `UncheckedProgram` | executable only: check `.key` yourself |
|
|
45
|
+
| `ProgramData` | this program's ProgramData ([below](#programdata)) |
|
|
46
|
+
| `InstructionsSysvar` | the exact address (3008) ([introspection](language-chain.md#instruction-introspection)) |
|
|
47
|
+
| `PythPriceUpdate`, `SwitchboardFeed`, `SwitchboardRandomness` | owner program and discriminator ([oracles](language-chain.md#oracles)) |
|
|
48
|
+
| `SlotHashesSysvar`, `StakeHistorySysvar` | the sysvar's address (3008) and data (5103: SlotHashes with no entries, StakeHistory too short) ([sysvars](language-chain.md#sysvars)) |
|
|
49
|
+
| `EventAuthority`, `SelfProgram` | Anchor's `["__event_authority"]` PDA, and this program's own address, for [`emitCpi`](language-errors-events.md#events-through-cpi) |
|
|
50
|
+
| `A \| null` / `Optional<A>` | an [optional account](#optional-accounts) |
|
|
51
|
+
| `Dup<Mut<T>>` | may be the same account as another writable parameter ([below](#two-parameters-one-account)) |
|
|
52
|
+
|
|
53
|
+
Every account exposes `key`, `lamports`, `dataLen`, `isSigner` and `isWritable`; `AccountInfo` adds `owner` and
|
|
54
|
+
`executable`. A struct account's fields are read as `acct.field`, and written on a `Mut<T>`. A field named like an
|
|
55
|
+
account member (`key`, `lamports`, …) is refused: name it `key_` (it is `key` in the IDL).
|
|
56
|
+
|
|
57
|
+
Unlike Anchor, there is no `Context` and no `#[derive(Accounts)]` struct: the parameters are the accounts, in the order
|
|
58
|
+
the client passes them. Writing to an account that is not `Mut<…>` is a TypeScript error (the field is read-only).
|
|
59
|
+
|
|
60
|
+
## Creating accounts
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { type Init, type InitIfNeeded, type Mut, type Pubkey, type Signer, type SystemProgram, type u8 } from "typesol";
|
|
64
|
+
|
|
65
|
+
export interface Profile {
|
|
66
|
+
owner: Pubkey;
|
|
67
|
+
bump: u8;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface Settings {
|
|
71
|
+
admin: Pubkey;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function register(user: Mut<Signer>, profile: Init<Profile>, systemProgram: SystemProgram): void {
|
|
75
|
+
profile.bump = profile.create(user, ["profile", user.key]);
|
|
76
|
+
profile.owner = user.key;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function configure(admin: Mut<Signer>, settings: InitIfNeeded<Settings>, systemProgram: SystemProgram): void {
|
|
80
|
+
const created = settings.createIfNeeded(admin, ["settings"]);
|
|
81
|
+
if (created) settings.admin = admin.key;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function scratch(payer: Mut<Signer>, extra: Init<Settings>, systemProgram: SystemProgram): void {
|
|
85
|
+
extra.create(payer, null, 8n + 32n + 64n);
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
In `configure` above the first caller becomes the admin; gate such a setup on the upgrade authority
|
|
90
|
+
([ProgramData](#programdata)).
|
|
91
|
+
|
|
92
|
+
- **`Init<T>`**: `acct.create(payer, seeds)` derives the PDA, verifies that the account is that address (2006), funds
|
|
93
|
+
the rent from `payer`, allocates the struct's size (up to 10 KiB), assigns it to this program and writes the
|
|
94
|
+
discriminator; it returns the bump. `create(payer, null)` creates a [keypair account](glossary.md#keypair-account)
|
|
95
|
+
instead: the account must sign the transaction (3010; it is a signer in the IDL). A third argument is Anchor's
|
|
96
|
+
`space = …` (the discriminator included, at least 8 + the struct's size). The new account's fields start at zero.
|
|
97
|
+
- A payer that is the account being created fails with 4101; an address already in use fails in the System Program
|
|
98
|
+
(0, AccountAlreadyInUse), as under Anchor's `init`. `create` also handles an address someone pre-funded: it tops up
|
|
99
|
+
the rent, then allocates and assigns instead of `create_account` (which would fail).
|
|
100
|
+
- The creates a body starts with (after its `constraint(…)` lines) run before the other accounts' constraints, as
|
|
101
|
+
Anchor creates `init` accounts first; a create after other statements, or in an instruction with an [account
|
|
102
|
+
group](#account-groups), runs where it is, after the constraints.
|
|
103
|
+
- `create` and `createIfNeeded` are top-level statements of the instruction (`const bump = acct.create(…)` included),
|
|
104
|
+
not inside an `if`, a loop, a helper or a `return` (`… must be a top-level statement of the instruction`), and an
|
|
105
|
+
`Init<T>` the body never creates is an error.
|
|
106
|
+
- **`InitIfNeeded<T>`**: `const created = acct.createIfNeeded(payer, seeds)` creates the account once; afterwards it
|
|
107
|
+
re-derives the PDA and checks the owner, discriminator and size (Anchor's `init_if_needed`). `acct.pdaBump` is the
|
|
108
|
+
bump after it. An existing account is used as it is: check the fields you rely on.
|
|
109
|
+
- Seeds, bumps and `create` under another program are on the [PDAs](language-pdas.md) page; mints, token accounts
|
|
110
|
+
and associated token accounts are created the same way ([tokens](language-cpi.md#creating-mints-and-token-accounts)).
|
|
111
|
+
|
|
112
|
+
### Accounts created by hand
|
|
113
|
+
|
|
114
|
+
`systemProgram.createAccount(…)`, or `systemProgram.allocate(account, space, seeds?)` + `systemProgram.assign(account,
|
|
115
|
+
owner, seeds?)` for an address someone pre-funded, then `const data = initAccount<T>(account)` (Anchor's `load_init`:
|
|
116
|
+
owned by this program 3007, writable 3006, large enough 3003, no discriminator yet 3000) gives the struct to fill. This
|
|
117
|
+
is for accounts whose address is decided at run time (a PDA or a signing keypair), as Raydium's pools are. `Init<T>`
|
|
118
|
+
covers the usual case. `systemProgram.createPda(…)` is [on the PDA page](language-pdas.md#createpda).
|
|
119
|
+
|
|
120
|
+
### Zeroed accounts
|
|
121
|
+
|
|
122
|
+
`Zeroed<T>` is Anchor's `zero`: an account (up to 10 MiB) the client allocated with System `CreateAccount`. Its
|
|
123
|
+
discriminator must still be zero (2013, checked first as under Anchor), and it must be owned by this program (3007),
|
|
124
|
+
big enough for the struct (3003), writable (2000) and rent-exempt (2005); then the discriminator is written and the
|
|
125
|
+
body initializes the fields. A `@layout borsh` struct starts empty and is written as Borsh when
|
|
126
|
+
the instruction returns. `Signed<Zeroed<Multisig>>` also requires it to sign, for an account the client creates with a
|
|
127
|
+
fresh keypair.
|
|
128
|
+
|
|
129
|
+
### Migrating an account
|
|
130
|
+
|
|
131
|
+
Upgrading a program leaves its accounts as they are: each keeps its bytes, and the new code reads them with the new
|
|
132
|
+
struct. The discriminator comes from the struct's name, so it still matches; only the size is checked, and only that
|
|
133
|
+
the account is at least as long as the struct (8 + its size; fixed-layout structs):
|
|
134
|
+
|
|
135
|
+
- A field added makes the struct longer. An account exactly the old size fails with 3003. One created with spare
|
|
136
|
+
space (`create(payer, seeds, space)`) or grown since passes when the new struct fits: a field appended at the end
|
|
137
|
+
reads the spare bytes (zero unless something wrote them), and a field inserted earlier makes the fields after it
|
|
138
|
+
read other fields' bytes, with no error.
|
|
139
|
+
- A field removed from the end leaves bytes the new struct ignores. A field removed from the middle, or fields
|
|
140
|
+
reordered, make the fields after it read other fields' bytes, with no error.
|
|
141
|
+
- A renamed struct has another discriminator: existing accounts fail with 3002.
|
|
142
|
+
|
|
143
|
+
So rewrite each account as the new struct with `Migrate<From, To>`, which resizes it and tops up its rent:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import { type Migrate, type Mut, type Pubkey, type Signer, type SystemProgram, type u64 } from "typesol";
|
|
147
|
+
|
|
148
|
+
/** @discriminator account:Counter */
|
|
149
|
+
export interface CounterV1 {
|
|
150
|
+
count: u64;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface CounterV2 {
|
|
154
|
+
count: u64;
|
|
155
|
+
owner: Pubkey;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function upgrade(payer: Mut<Signer>, counter: Migrate<CounterV1, CounterV2>, systemProgram: SystemProgram): void {
|
|
159
|
+
counter.migrate(payer, { count: counter.from.count, owner: payer.key });
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
As written, anyone can migrate a counter and become its `owner`. With no constraints on `Migrate`, check the caller in
|
|
164
|
+
the body before `migrate`, for example against the upgrade authority of a [`ProgramData`](#programdata) parameter.
|
|
165
|
+
|
|
166
|
+
Anchor 1.0's `Migration`: an existing `From` account (owner, discriminator, size checked) is rewritten as `To` by
|
|
167
|
+
`acct.migrate(payer, value)`, a top-level statement the instruction must reach.
|
|
168
|
+
|
|
169
|
+
- `acct.from` (read-only) is readable before it and `acct.to` after it; the value is built in full before the rewrite,
|
|
170
|
+
so it may read `acct.from`.
|
|
171
|
+
- The account is resized to `To` (the payer tops up the rent when it grows, at most 10 KiB; shrinking keeps the
|
|
172
|
+
lamports; growing needs `SystemProgram`).
|
|
173
|
+
- The account then carries `To`'s discriminator, so an account already migrated fails with 3002. Keep the old struct
|
|
174
|
+
under a new name with its old discriminator, `/** @discriminator account:Counter */ interface CounterV1 { … }`, and
|
|
175
|
+
give the new one a name of its own (two structs with one discriminator are refused).
|
|
176
|
+
- Limits: fixed-layout structs without growable Vecs, no constraints yet, and the account cannot be passed to a helper
|
|
177
|
+
(use `acct.to` fields in the instruction).
|
|
178
|
+
- `resizeAccount` on a `Mut<AccountInfo>` ([closing and resizing](#closing-and-resizing)) is the manual way: grow the
|
|
179
|
+
account with the new field appended at the end, which reads as zero.
|
|
180
|
+
|
|
181
|
+
## Closing and resizing
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
import { type HasOne, type Mut, type Pubkey, type Signer, type SystemProgram, type u64, close, realloc } from "typesol";
|
|
185
|
+
|
|
186
|
+
export interface Log {
|
|
187
|
+
owner: Pubkey;
|
|
188
|
+
entries: u64;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function grow(payer: Mut<Signer>, log: Mut<Log>, systemProgram: SystemProgram, size: u64): void {
|
|
192
|
+
realloc(log, size, payer);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function remove(owner: Mut<Signer>, log: HasOne<Mut<Log>, "owner">): void {
|
|
196
|
+
close(log, owner);
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable
|
|
201
|
+
account) and its data is zeroed. The account is not used after it in the function, except its `key` (compile
|
|
202
|
+
errors, or 2040 at run time in a helper given one account twice). `CloseTo<A, "dest">` does the same when the
|
|
203
|
+
instruction succeeds ([constraints](#constraints)).
|
|
204
|
+
- Who may call them: the lamports of a closed account are value, so `HasOne` above lets only the log's owner close it.
|
|
205
|
+
`grow` moves no value out of the account (growing charges the payer, shrinking keeps the lamports in it), so it is
|
|
206
|
+
left open here; restrict it too if the extra bytes, or their absence, matter to your program.
|
|
207
|
+
- `realloc(account, newSize, payer)` on a `Mut<Struct>`: growing charges the payer the extra rent (at most 10 KiB per
|
|
208
|
+
instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a
|
|
209
|
+
growable `Vec` (its push / pop / clear size the account).
|
|
210
|
+
- `resizeAccount(account, newSize)` on a `Mut<AccountInfo>` of this program is Rust's `AccountInfo::resize`: the
|
|
211
|
+
length only, new bytes zeroed, no rent moved (fund it first: `rentExempt(newSize)`), at most 10 KiB of growth
|
|
212
|
+
(3016).
|
|
213
|
+
- An account grows at most 10 KiB per instruction, counted from its length when the instruction started (Solana's
|
|
214
|
+
limit): realloc again in the next instruction.
|
|
215
|
+
- `account.lamports` can be read on any account and written on a `Mut` one.
|
|
216
|
+
|
|
217
|
+
## Constraints
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { type CloseTo, type HasOne, type Mut, type Pubkey, type Seeds, type Signer, type u64, type u8, constraint } from "typesol";
|
|
221
|
+
|
|
222
|
+
export enum VaultError {
|
|
223
|
+
NotOwner = "Only the owner",
|
|
224
|
+
TooMuch = "Amount above the limit",
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export interface Vault {
|
|
228
|
+
owner: Pubkey;
|
|
229
|
+
limit: u64;
|
|
230
|
+
balance: u64;
|
|
231
|
+
bump: u8;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function spend(owner: Signer, vault: HasOne<Seeds<Mut<Vault>, ["vault", "@owner"], "bump">, "owner", VaultError.NotOwner>, amount: u64): void {
|
|
235
|
+
constraint(vault, amount <= vault.limit, VaultError.TooMuch);
|
|
236
|
+
vault.balance -= amount;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function shut(owner: Mut<Signer>, vault: CloseTo<HasOne<Mut<Vault>, "owner">, "owner">): void {
|
|
240
|
+
vault.balance = 0n;
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Constraints are types wrapped around an account type, as Anchor's `#[account(…)]` attributes. They are checked before
|
|
245
|
+
the body, in Anchor's order, and recorded in the IDL (`relations`, `pda`, `address`).
|
|
246
|
+
|
|
247
|
+
| Constraint | Checks | Error |
|
|
248
|
+
| --- | --- | --- |
|
|
249
|
+
| `HasOne<A, "owner">` | the struct's `owner` field equals the parameter named `owner` (Anchor's `has_one`) | 2001 |
|
|
250
|
+
| `Seeds<A, ["vault", "@owner"], "bump">` | the account is that PDA ([PDAs](language-pdas.md#seeds-constraints)) | 2006 |
|
|
251
|
+
| `CloseTo<A, "owner">` | closes the account into `owner` when the instruction succeeds (Anchor's `close`) | |
|
|
252
|
+
| `Address<A, "4Nd1…">` | the exact address (`address` in the IDL) | 2012 |
|
|
253
|
+
| `Owner<A, "Tokenkeg…">` | the owner program | 2004 |
|
|
254
|
+
| `Executable<A>` | executable | 2007 |
|
|
255
|
+
| `Signed<A>` | the account signed (Anchor's `signer` constraint); the IDL marks it a signer | 2002 |
|
|
256
|
+
| `Ata<TokenAccount, "owner", "mint">` | the associated token account of those parameters ([tokens](language-cpi.md#token-accounts-and-mints-as-parameters)) | 2009 |
|
|
257
|
+
| `TokenOf<…>`, `MintOf<…>` | a token account's mint, authority and token program; a mint's authorities | 2014–2017, 2021, 2022 |
|
|
258
|
+
| `constraint(acct, condition, error?)` | any condition, in the body's first statements | 2003, or your error |
|
|
259
|
+
|
|
260
|
+
- **Your own errors.** `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`,
|
|
261
|
+
`Signed<A, E.X>` and `Mut<T, E.X>` fail with a member of one of the program's error enums instead of Anchor's code, as
|
|
262
|
+
Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the
|
|
263
|
+
constraints Anchor lets you name an error for). For several `HasOne` fields with different errors, nest them:
|
|
264
|
+
`HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>`.
|
|
265
|
+
- **`constraint(acct, condition, error?)`** is Anchor's `constraint = condition @ error` on `acct`: statements at the
|
|
266
|
+
very start of the body, run with that account's checks (after its `has_one`, before the next account; with the other
|
|
267
|
+
constraints after the creates the body starts with), so a transaction breaking several checks gets Anchor's code.
|
|
268
|
+
They read accounts and arguments. The default error is ConstraintRaw (2003).
|
|
269
|
+
- **`Owner` on a struct account**: `Owner<Account<T>, "…">` is another program's account (Anchor's `Account` /
|
|
270
|
+
`AccountLoader` of a `declare_program!` type): loaded with that program as its owner (3007) and Anchor's
|
|
271
|
+
discriminator for `T`'s name, its fields read and `HasOne` checked as for this program's own. The IDL lists `T`
|
|
272
|
+
among its types, not its accounts (an error named on such an `Owner` is not used: the load fails with 3007). Such a
|
|
273
|
+
struct may carry a shorter discriminator, `/** @discriminator 0x01 */` (1 to 8 bytes, as Anchor's
|
|
274
|
+
`discriminator = &[1]`; Solend's reserve), its fields then starting right after it; this program's own accounts
|
|
275
|
+
keep 8.
|
|
276
|
+
- `Address<InstructionsSysvar, "Sysvar1nstructions1111111111111111111111111">` checks the address as Anchor's
|
|
277
|
+
`address = sysvar::instructions::ID` on an `UncheckedAccount` does (2012, with the constraints).
|
|
278
|
+
|
|
279
|
+
## Two parameters, one account
|
|
280
|
+
|
|
281
|
+
Two writable parameters can never be the same account: aliasing is refused with error 2040 (also when a [remaining
|
|
282
|
+
account](glossary.md#remaining-accounts) written through `.lamports` or `loadAccountMut` is another account of the
|
|
283
|
+
instruction).
|
|
284
|
+
|
|
285
|
+
`Dup<Mut<T>>` (Anchor's `dup`) lifts that for one parameter when both accounts are read and written in place (not
|
|
286
|
+
created, closed or `@layout borsh`; a close destination may be one, the rent reaching it through either). A write
|
|
287
|
+
through either is seen through the other, so read what you need before writing. A reference into one of them
|
|
288
|
+
(`const e = a.entries.get(i)`) cannot be used after a push, pop or clear through the other moved that data, as with one
|
|
289
|
+
name (a compile error): copy the fields first.
|
|
290
|
+
|
|
291
|
+
A remaining account can be loaded with `loadAccountMut` once per instruction: loading the same one again
|
|
292
|
+
(`rest.get(i)` and `rest.get(j)` with `i == j`) is refused with 2040 too, since the two views would alias. So is a
|
|
293
|
+
second `loadAccountMut` of one `AccountInfo` parameter. Two `Dup<…>` parameters that are one account may each be
|
|
294
|
+
loaded (one array holding both ticks of a position, as Raydium CLMM's tick arrays).
|
|
295
|
+
|
|
296
|
+
A helper's `Inout<T>` argument ([Inout parameters](language-statements.md#inout-parameters)) must not share storage
|
|
297
|
+
with another argument during the call. Places in accounts that only the transaction can tell apart (in two `Dup<…>`
|
|
298
|
+
accounts, in a writable and a read-only account, in a helper's own account parameters) are compared before the call,
|
|
299
|
+
which fails with 2040 when they overlap. The comparison covers an Inout argument against every other argument passed
|
|
300
|
+
in place (another Inout one, a read-only struct, array or list, an account), so a read-only argument cannot change
|
|
301
|
+
under the helper while it writes; an argument copied for the call shares nothing and is not compared. Native views
|
|
302
|
+
are compared too ([native programs](language-native.md#inout-places-that-may-be-one-account)).
|
|
303
|
+
|
|
304
|
+
## How many accounts
|
|
305
|
+
|
|
306
|
+
At most 32 accounts per instruction; more is refused with 5113. `export const MAX_ACCOUNTS = 128n` (up to 255; Anchor
|
|
307
|
+
takes what the runtime allows) raises it for programs that take many remaining accounts. The CPI scratch lists are
|
|
308
|
+
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before.
|
|
309
|
+
|
|
310
|
+
## Optional accounts
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
import { type Account, type Mut, type Pubkey, type u64 } from "typesol";
|
|
314
|
+
|
|
315
|
+
export interface Bank {
|
|
316
|
+
owner: Pubkey;
|
|
317
|
+
total: u64;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function deposit(bank: Mut<Bank>, referrer: Account<Bank> | null, amount: u64): void {
|
|
321
|
+
bank.total += amount;
|
|
322
|
+
if (referrer !== null) bank.total += referrer.total > 0n ? 1n : 0n;
|
|
323
|
+
const bonus = referrer?.total ?? 0n;
|
|
324
|
+
bank.total += bonus > 1000n ? 1n : 0n;
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
`A | null` or `Optional<A>` is Anchor's `Option<Account>`: the client passes this program's id to leave it out, and the
|
|
329
|
+
IDL marks it `optional`.
|
|
330
|
+
|
|
331
|
+
- Its checks and constraints run only when it is present. A `constraint(other, …)` that mentions it runs as written
|
|
332
|
+
(`x === null` is checked when it is missing).
|
|
333
|
+
- Check `x !== null` before use, or assert it was passed with `x!` / `x!.field` (5115 when it was left out).
|
|
334
|
+
`acct?.field` gives an Option (empty when the account was left out).
|
|
335
|
+
- Passed to `invoke` as it is (`readonly(x)` / `writable(x)` without `!`), it is left out of the CPI's list when it
|
|
336
|
+
was not passed ([calling other programs](language-cpi.md#accounts)).
|
|
337
|
+
|
|
338
|
+
## Account groups
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
import { type HasOne, type Mut, type Pubkey, type Signer, type TokenAccount, type u64 } from "typesol";
|
|
342
|
+
|
|
343
|
+
export interface Pool {
|
|
344
|
+
vault: Pubkey;
|
|
345
|
+
reserve: u64;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export interface PoolAccounts {
|
|
349
|
+
pool: HasOne<Mut<Pool>, "vault">;
|
|
350
|
+
vault: Mut<TokenAccount>;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export function record(user: Signer, p: PoolAccounts, amount: u64): void {
|
|
354
|
+
p.pool.reserve += amount;
|
|
355
|
+
}
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an exported interface whose fields
|
|
359
|
+
are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes
|
|
360
|
+
`p.vault` to CPIs and helpers, and creates `p.pool.create(…)`.
|
|
361
|
+
|
|
362
|
+
- Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`,
|
|
363
|
+
`TokenOf<…, "mint", "pool">`), then the instruction's.
|
|
364
|
+
- The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten
|
|
365
|
+
them (`pPool`, `pVault`).
|
|
366
|
+
- A field may be optional (`A | null`) or another group (`p.fees.vault`; the IDL nests it too, the client flattens it
|
|
367
|
+
to `pFeesVault`). A group may not be optional or a helper parameter. Groups must be exported (`account groups must
|
|
368
|
+
be exported: export interface …`).
|
|
369
|
+
- An instruction with a group checks in Anchor's order: its arguments first (102), then each account in order, a
|
|
370
|
+
group's constraints right after the group's accounts (as a composite's `try_accounts` does), the other constraints
|
|
371
|
+
last.
|
|
372
|
+
|
|
373
|
+
## ProgramData
|
|
374
|
+
|
|
375
|
+
`programData: ProgramData` is this program's ProgramData account: its address is derived from the program id, and the
|
|
376
|
+
upgradeable loader owner and state are checked. It exposes `upgradeAuthority` and `deploySlot`. Gate admin setup on
|
|
377
|
+
`programData.upgradeAuthority === admin.key`.
|
|
378
|
+
|
|
379
|
+
## Remaining accounts
|
|
380
|
+
|
|
381
|
+
```ts
|
|
382
|
+
import { type Mut, type RemainingAccount, type u64, remainingAccounts } from "typesol";
|
|
383
|
+
|
|
384
|
+
export interface Tally {
|
|
385
|
+
sum: u64;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function weight(acct: RemainingAccount): u64 {
|
|
389
|
+
return acct.isWritable ? acct.lamports : 0n;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function count(tally: Mut<Tally>): void {
|
|
393
|
+
const rest = remainingAccounts();
|
|
394
|
+
for (let i = 0n; i < rest.length; i++) tally.sum += weight(rest.get(i));
|
|
395
|
+
}
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
`remainingAccounts()` gives the accounts passed after the declared ones, in order.
|
|
399
|
+
|
|
400
|
+
- `.length`, `.get(i)` (5104 past the end) → `key`, `owner`, `lamports` (writes check writability, 3006), `isSigner`,
|
|
401
|
+
`isWritable`, the data length and data.
|
|
402
|
+
- `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)` give checked struct views (owner, discriminator and size, as
|
|
403
|
+
`Account<T>` / `Mut<T>`), also of an `AccountInfo` parameter (Anchor's `AccountLoader::try_from` on an
|
|
404
|
+
`UncheckedAccount`).
|
|
405
|
+
- The view is also its account: `.key`, `.lamports`, and it passes to a helper taking `Account<T>` / `Mut<T>`.
|
|
406
|
+
- A second `loadAccountMut` of one account is refused (2040), but a view declared in a loop body ends with its
|
|
407
|
+
iteration.
|
|
408
|
+
- `loadAccountMut<Dup<T>>` in a loop also accepts an account passed more than once, one view at a time, as a route
|
|
409
|
+
back through one pool needs.
|
|
410
|
+
- Pass one to a helper that takes a `RemainingAccount` parameter (it reads the key, owner, lamports, data length and
|
|
411
|
+
data, and loads structs from it; a `loadAccountMut` there claims the account for the rest of the instruction, so a
|
|
412
|
+
second one fails with 2040), or all of them to one that takes `RemainingAccounts` (`.length`, `.get(i)`, passed on to
|
|
413
|
+
other helpers; spreading them into a CPI stays in the instruction).
|
|
414
|
+
- Pass them to `invoke`, one at a time or spread: `...remainingAccounts()` (each with the flags it was passed with),
|
|
415
|
+
`...readonly(rest)` / `...writable(rest)` (all with that role), `rest.slice(a, b)` for part of them. A CPI lists at
|
|
416
|
+
most as many accounts as an instruction takes (5113).
|
|
417
|
+
- Typed CPIs take remaining accounts too ([remaining accounts in
|
|
418
|
+
CPIs](language-cpi.md#programs-and-sysvars-passed-as-remaining-accounts)).
|
|
419
|
+
|
|
420
|
+
## Other programs' accounts
|
|
421
|
+
|
|
422
|
+
- `const pool = loadForeign<Pool>(account, AMM_PROGRAM)` loads another Anchor program's account: owner, the
|
|
423
|
+
`account:Pool` discriminator and size checked (3007 / 3002 / 3003).
|
|
424
|
+
- `readData<u64>(account, offset)` reads a raw little-endian value (bounds-checked, 3003).
|
|
425
|
+
- `writeData<u64>(account, offset, value)` writes one into a `Mut<AccountInfo>` of this program (bounds-checked, 3003):
|
|
426
|
+
raw layouts such as Marginfi's monitor archive.
|
|
427
|
+
- Native programs' accounts without a discriminator (`loadRaw`, `loadBorsh`) are on the
|
|
428
|
+
[native programs](language-native.md#accounts-without-a-discriminator) page.
|
|
429
|
+
|
|
430
|
+
## Account data layouts
|
|
431
|
+
|
|
432
|
+
By default an account struct is stored in a fixed layout: the 8-byte discriminator, then each field at a fixed offset
|
|
433
|
+
(each type's bytes are in [types](language-types.md)), with `Vec` fields after the fixed ones. Annotations change how a
|
|
434
|
+
struct is stored or how the IDL describes it.
|
|
435
|
+
|
|
436
|
+
### Anchor's account bytes: @layout borsh
|
|
437
|
+
|
|
438
|
+
`/** @layout borsh */` on an account struct stores it as Anchor does: Borsh, so a `FixedString<N>` is a String, a
|
|
439
|
+
`FixedVec<T, N>` or `Vec<T>` a Vec, an `Option` one byte when empty, and the fields after them move. A TypeSOL program
|
|
440
|
+
can then take over accounts an Anchor program wrote, and the IDL lists Anchor's own types.
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
import { type FixedString, type Mut, type Option, type u64 } from "typesol";
|
|
444
|
+
|
|
445
|
+
/** @layout borsh */
|
|
446
|
+
export interface Profile {
|
|
447
|
+
name: FixedString<32>;
|
|
448
|
+
score: Option<u64>;
|
|
449
|
+
level: u64;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export function rename(profile: Mut<Profile>, name: string): void {
|
|
453
|
+
profile.name = name;
|
|
454
|
+
profile.level += 1n;
|
|
455
|
+
}
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
- The instruction unpacks the account into the usual fixed layout when it starts (bad bytes fail with 3003) and packs
|
|
459
|
+
it back when it returns (3004 when the account is too small for the new value), so everything else works on it
|
|
460
|
+
unchanged.
|
|
461
|
+
- A `Vec<T>` field (any position; integers, booleans, Pubkeys, unit enums or fixed-size structs) is Anchor's own: held
|
|
462
|
+
on the heap while the instruction runs, growing as Rust's Vec does, bounded only by the account when it is written
|
|
463
|
+
back (3004). Its elements move when it grows, so a reference into one cannot outlive a `push` or an assignment.
|
|
464
|
+
- `Init` of such a struct takes its space: `create(payer, seeds, space)`.
|
|
465
|
+
- Programs invoked from the body (CPIs) see the account's bytes as they were when the instruction started.
|
|
466
|
+
- It costs more compute than the fixed layout: the whole account is read and written each time.
|
|
467
|
+
- Nested structs and list elements must be fixed-size (FixedString elements allowed).
|
|
468
|
+
- The same struct is Borsh as a whole instruction argument (checked like Borsh deserialization, UTF-8 included), as
|
|
469
|
+
return data and as an event. As those (not as account data) it may also hold `string` fields and data enums carrying
|
|
470
|
+
strings, Anchor's `String` and enums in argument structs (account data takes data enums without strings). Not inside
|
|
471
|
+
list or enum arguments or `loadAccount`, and a struct holding a `Vec<T>` is account data or a whole argument, not
|
|
472
|
+
return data or an event.
|
|
473
|
+
- A struct holding a FixedVec cannot be both an argument and account data (its bytes differ there, and the IDL
|
|
474
|
+
describes a type one way): declare one for each.
|
|
475
|
+
|
|
476
|
+
### Zero-copy types as Anchor's IDL describes them
|
|
477
|
+
|
|
478
|
+
`/** @repr c */` (`@repr c packed`, `@repr c align 8`, `@repr rust` on an enum) and `/** @serialization bytemuck */`
|
|
479
|
+
on a struct or enum put the IDL's `repr` and `serialization` there, as Anchor's `#[account(zero_copy)]` / `#[repr(C)]`
|
|
480
|
+
types have them.
|
|
481
|
+
|
|
482
|
+
- TypeSOL stores fields back to back, so an unpacked `@repr c` struct must have its fields where C puts them: a field
|
|
483
|
+
off its alignment, or a size that is not a multiple of the struct's, is a compile error naming the padding to add
|
|
484
|
+
(Anchor zero-copy types spell their padding out as `_pad` fields, so a port matches).
|
|
485
|
+
- A 16-byte integer's alignment differs between targets: hold it as `@bytes` (below) or mark the struct packed.
|
|
486
|
+
- A zero-copy (`@serialization bytemuck`) account is checked as Anchor's `AccountLoader` checks it: the owner first
|
|
487
|
+
(3007, also for an account never created), then a discriminator to read (3001) and match (3002), then the size.
|
|
488
|
+
|
|
489
|
+
### Field names and bytes for the IDL
|
|
490
|
+
|
|
491
|
+
- `/** @bytes */` on an integer field: stored as the integer (little-endian), shown in the IDL as `[u8; N]`
|
|
492
|
+
(Marginfi's `WrappedI80F48 { value: [u8; 16] }`, read and written as an `i128`). On a FixedArray of integers, each
|
|
493
|
+
element as its bytes (`[[u8; 8]; 16]` for a `FixedArray<u64, 16>`).
|
|
494
|
+
- `/** @idlName _pad0 */`: the field's IDL name where the source cannot use it (a leading `_`).
|
|
495
|
+
- A field named like an account member plus `_` (`key_`, `lamports_`) is `key` / `lamports` in the IDL.
|
|
496
|
+
- `/** @discriminator account:Old */` (or `0x` and 8 bytes) replaces an account struct's discriminator.
|
|
497
|
+
- JSDoc on structs and fields becomes `docs` in the IDL.
|
|
498
|
+
|
|
499
|
+
**Next:** [PDAs](language-pdas.md): seeds, bumps and signing as a PDA.
|