@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,601 @@
|
|
|
1
|
+
# Types
|
|
2
|
+
|
|
3
|
+
Every value in a TypeSOL program has a type whose layout is known when the program compiles: a fixed size for most,
|
|
4
|
+
a length followed by its elements or bytes for `string` and `Vec` (see the table). This page goes
|
|
5
|
+
through them: what each one is, how to write it, its bytes in account data and in instruction arguments, its limits,
|
|
6
|
+
and the error code when a limit is hit at run time. Part of the [language guide](language.md).
|
|
7
|
+
|
|
8
|
+
| Type | In account data | As an argument (Borsh) |
|
|
9
|
+
| --- | --- | --- |
|
|
10
|
+
| `u8` `u16` `u32` `u64` `u128`, `i8` … `i128` | 1, 2, 4, 8, 16 bytes, little-endian | the same |
|
|
11
|
+
| `u256` | not allowed | not allowed |
|
|
12
|
+
| `boolean` | 1 byte, 0 or 1 | the same, checked (102) |
|
|
13
|
+
| `Pubkey`, `Hash` | 32 bytes | the same |
|
|
14
|
+
| `string` | not allowed: use `FixedString<N>` | u32 length + UTF-8 bytes |
|
|
15
|
+
| `FixedString<N>` | u32 length + N bytes | not a parameter type (take a `string`); in a struct argument, a Borsh String of at most N bytes (102 when longer) |
|
|
16
|
+
| unit `enum` | 1 byte, the variant's index | the same, checked (102) |
|
|
17
|
+
| data enum | 1 tag byte + the largest variant | a Borsh enum: the tag, then the variant |
|
|
18
|
+
| struct (`interface`) | its fields back to back | the same |
|
|
19
|
+
| `Option<T>` | 1 byte + size(T), always | 1 byte when empty, else 1 + T |
|
|
20
|
+
| `FixedArray<T, N>` | N × size(T) | the same |
|
|
21
|
+
| `FixedVec<T, N>` | u32 length + N × size(T), always | a Borsh Vec of at most N elements |
|
|
22
|
+
| `Vec<T>` | u32 length + elements, stored after the fixed fields; the account grows | a Borsh Vec, read in place |
|
|
23
|
+
|
|
24
|
+
## Integers
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { type Mut, type i64, type u8, type u64 } from "typesol";
|
|
28
|
+
|
|
29
|
+
export interface Stats {
|
|
30
|
+
count: u64;
|
|
31
|
+
delta: i64;
|
|
32
|
+
level: u8;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function record(stats: Mut<Stats>, by: u64, change: i64): void {
|
|
36
|
+
stats.count += by;
|
|
37
|
+
stats.delta = stats.delta + change;
|
|
38
|
+
stats.level = 3n;
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
- The types are `u8`, `u16`, `u32`, `u64`, `u128` (unsigned) and `i8`, `i16`, `i32`, `i64`, `i128` (two's
|
|
43
|
+
complement). To TypeScript they are all `bigint`; TypeSOL tracks the declared width.
|
|
44
|
+
- **Literals are bigints**: `1n`, `0n`, `-5n`. Unlike JavaScript, there are no `number`s: `1` is refused
|
|
45
|
+
(`Type 'number' is not assignable to type 'bigint'`, with a hint to write `1n`), and so are `number` parameters and
|
|
46
|
+
fields. A literal takes the type of the place it is used in and must fit there (`300 does not fit in u8`). A local
|
|
47
|
+
declared from a bare literal, `const x = 5n`, is a `u64`; an untyped top-level constant takes the type of each place
|
|
48
|
+
it is used in, as a literal does ([constants](language-basics.md#constants)).
|
|
49
|
+
- **Both operands have one type.** `a + b` with a `u64` and a `u8` is refused: `operands have different types: u64 and
|
|
50
|
+
u8; convert with u64(...) etc.` Comparisons (`<`, `<=`, `===`, …) need equal types too.
|
|
51
|
+
- **Every operation is checked.** `+ - * / % **` and their assignments (`+=` … `**=`) fail the instruction on
|
|
52
|
+
overflow (5100) or division by zero (5101); `**` with a negative exponent fails as well (JavaScript throws there).
|
|
53
|
+
Unlike JavaScript there are no silent wraps and no `Infinity`.
|
|
54
|
+
- **Bitwise operators.** `& | ^` work on equal types; `~` flips the bits within the type's width (`~1n` as a `u8` is
|
|
55
|
+
254). Both shifts fail (5100) when the amount is negative or not below the width (`x >> 64n` on a `u64`), and `<<`
|
|
56
|
+
also when bits would be lost; `>>` is arithmetic on signed types. Unlike JavaScript, where a bigint shift never
|
|
57
|
+
fails, `1n << 64n` is not a bigger number and `x >> 200n` is not 0. The shift amount, also in `<<=` and `>>=`, may be
|
|
58
|
+
any integer type up to `u128`.
|
|
59
|
+
- `++` and `--` are checked like `+= 1n`. Unary `-` needs a signed type (`unary minus needs a signed integer (i8 …
|
|
60
|
+
i128)`).
|
|
61
|
+
|
|
62
|
+
`const PANIC_ON_OVERFLOW = true` makes overflow and division by zero panic as Rust's `checked_*().unwrap()` does,
|
|
63
|
+
instead of failing with 5100 / 5101 ([native
|
|
64
|
+
programs](language-native.md#errors-and-panics-as-the-original-reports-them)).
|
|
65
|
+
|
|
66
|
+
### Casts
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { type Mut, type u64, u8, i64 } from "typesol";
|
|
70
|
+
|
|
71
|
+
export interface Small {
|
|
72
|
+
level: u8;
|
|
73
|
+
delta: i64;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function store(small: Mut<Small>, value: u64): void {
|
|
77
|
+
small.level = u8(value);
|
|
78
|
+
small.delta = i64(value);
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- `u8(x)`, `u16(x)`, … `i128(x)` convert an integer to another width. They fail with 4102 (InvalidNumericConversion)
|
|
83
|
+
when the value does not fit: `u8(300n)` and `u64(-1n)` fail, they never truncate.
|
|
84
|
+
- A cast is a value as well as a type: import `u8`, not `type u8`, and the one import serves for both uses (importing
|
|
85
|
+
both is a duplicate identifier).
|
|
86
|
+
- `as` does not convert. `x as u64` with `x: u8` is refused: `this is a u8, not a u64: \`as\` does not convert (use
|
|
87
|
+
u64(x) and the like for integers)`. In generic helpers `as T` names a type the value already has.
|
|
88
|
+
|
|
89
|
+
### Integer helpers
|
|
90
|
+
|
|
91
|
+
| Function | What it computes |
|
|
92
|
+
| --- | --- |
|
|
93
|
+
| `mulDiv(a, b, c)` | `a * b / c` rounded down, without overflow in the product: u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-bit one. Fails with 5101 when `c` is zero and 5100 when the result does not fit |
|
|
94
|
+
| `mulDivCeil(a, b, c)` | the same, rounded up |
|
|
95
|
+
| `isqrt(x)` | the integer square root of an unsigned integer (`u8` … `u256`) |
|
|
96
|
+
| `min(a, b)`, `max(a, b)` | the smaller or larger of two integers of one type |
|
|
97
|
+
|
|
98
|
+
`Math` is not available (`Math works on numbers; use min(a, b) and max(a, b) from "typesol", which take bigints`), nor
|
|
99
|
+
`BigInt(…)` (`unsupported call: BigInt; use u64(x) or another integer cast`).
|
|
100
|
+
|
|
101
|
+
### u256
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import { type Mut, u128, u256 } from "typesol";
|
|
105
|
+
|
|
106
|
+
export interface Pool {
|
|
107
|
+
liquidity: u128;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function scale(pool: Mut<Pool>, a: u128, b: u128): void {
|
|
111
|
+
const product = u256(a) * u256(b);
|
|
112
|
+
pool.liquidity = u128(product >> 64n);
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, with the same checked
|
|
117
|
+
operators and comparisons, `min` / `max`, `mulDiv`, `isqrt`, `switch`, and as a list index (5104 past u64).
|
|
118
|
+
|
|
119
|
+
- `u256(x)` converts from any integer (a negative one fails with 4102); `u128(x)` and `u64(x)` convert back (4102
|
|
120
|
+
when it does not fit).
|
|
121
|
+
- A shift amount or an exponent is a `u128` or smaller (`a shift amount is a u128 or smaller integer`; `the exponent of
|
|
122
|
+
** is a u128 or smaller integer`).
|
|
123
|
+
- Never in account data, arguments, events, return data or CPI data: the IDL has no 256-bit integer (`A.v: u256 is for
|
|
124
|
+
computation; store a u128 (or two u128s)`).
|
|
125
|
+
- `log(x)` prints it only when it fits in 128 bits; a larger value fails with 5100.
|
|
126
|
+
|
|
127
|
+
## Booleans
|
|
128
|
+
|
|
129
|
+
`boolean`, with `true` and `false`, `&&`, `||`, `!`, `===` and `!==`. One byte in account data and arguments; an
|
|
130
|
+
argument byte other than 0 or 1 fails with 102. Unlike JavaScript there is no truthiness: a condition must be a
|
|
131
|
+
`boolean`, so `if (count)` with an integer is refused (`expected boolean, got u64`); write `if (count > 0n)`.
|
|
132
|
+
|
|
133
|
+
## Pubkey and Hash
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { type Account, type Pubkey, type Signer, pubkey, require } from "typesol";
|
|
137
|
+
|
|
138
|
+
const ADMIN = pubkey("4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T");
|
|
139
|
+
|
|
140
|
+
export interface Config {
|
|
141
|
+
owner: Pubkey;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function check(config: Account<Config>, caller: Signer): void {
|
|
145
|
+
require(config.owner === caller.key || caller.key.equals(ADMIN), "not allowed");
|
|
146
|
+
require(config.owner.compare(ADMIN) !== 0n, "owner is the admin");
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- `Pubkey` is a 32-byte address. Compare with `===`, `!==` or `.equals(other)`; `<` and `>` are refused (`< needs
|
|
151
|
+
integer operands`): `a.compare(b)` orders two keys as Rust orders their bytes (-1, 0 or 1).
|
|
152
|
+
- `pubkey("…")` is a constant address, checked as base58 when the program compiles, at the top level or inline.
|
|
153
|
+
- `Hash` is 32 bytes too: what `sha256` and `keccak256` return ([hashing](language-chain.md#hashing)), with `===` and
|
|
154
|
+
`.compare`.
|
|
155
|
+
- In a template string or `log`, a `Pubkey` or `Hash` prints as base58.
|
|
156
|
+
|
|
157
|
+
## Strings
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
import { type FixedString, type Mut, byteLength, log, require } from "typesol";
|
|
161
|
+
|
|
162
|
+
export interface Profile {
|
|
163
|
+
name: FixedString<32>;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function rename(profile: Mut<Profile>, name: string): void {
|
|
167
|
+
require(byteLength(name) <= 32n, "name too long");
|
|
168
|
+
profile.name = name;
|
|
169
|
+
if (profile.name === "admin") log("renamed to admin");
|
|
170
|
+
profile.name += "!";
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
- **`string`** is an argument or literal: a Borsh String (u32 length, then UTF-8 bytes) in arguments, checked as UTF-8
|
|
175
|
+
on entry (102). It cannot be account data (`A has a variable-length string field and cannot be account data; use
|
|
176
|
+
FixedString<N>`).
|
|
177
|
+
- **`FixedString<N>`** is a string field with room for N bytes, N from 1 to 10240: a u32 length then N bytes, always
|
|
178
|
+
4 + N bytes. Assigning a longer string fails with 5105.
|
|
179
|
+
- What strings support: `===` and `!==`, `byteLength(s)` (UTF-8 bytes, a `u64`), `log(s)`, `+=` on a `FixedString`
|
|
180
|
+
field, and use as a PDA seed (its bytes). A local bound to account text keeps its own copy.
|
|
181
|
+
- Unlike JavaScript, `.length` is refused (it would be a JS number of UTF-16 units: `use byteLength(s) for strings`),
|
|
182
|
+
and so are indexing and string methods (`s.slice`, `s.charAt`, …).
|
|
183
|
+
|
|
184
|
+
### Strings built at run time
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import { type Pubkey, type u64, type Option, log } from "typesol";
|
|
188
|
+
|
|
189
|
+
export function report(owner: Pubkey, amount: u64, limit: Option<u64>): void {
|
|
190
|
+
const line = `owner ${owner} paid ${amount}, limit ${limit}`;
|
|
191
|
+
log(line);
|
|
192
|
+
let tag = "id-";
|
|
193
|
+
tag += "7";
|
|
194
|
+
log("tag " + tag);
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`"a" + name`, `` `#${n}` `` and `s += …` build strings on the heap (32 KiB; 5110 when full). In a template, a `Pubkey`
|
|
199
|
+
or `Hash` prints as base58 and an `Option` of an integer, boolean, `Pubkey` or `Hash` as its value or `null`, as
|
|
200
|
+
JavaScript prints it (after `x !== null`, the value). A template is joined in one allocation; text known when the
|
|
201
|
+
program compiles (literals, string and `Pubkey` constants) is folded in; `s += …` grows the newest heap string in
|
|
202
|
+
place. Tagged templates (`` String.raw`…` ``) are refused.
|
|
203
|
+
|
|
204
|
+
## Enums
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
import { type Mut, type u64 } from "typesol";
|
|
208
|
+
|
|
209
|
+
export enum Status {
|
|
210
|
+
Pending,
|
|
211
|
+
Approved,
|
|
212
|
+
Rejected,
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface Request {
|
|
216
|
+
status: Status;
|
|
217
|
+
amount: u64;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function approve(request: Mut<Request>): void {
|
|
221
|
+
if (request.status === Status.Pending) request.status = Status.Approved;
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
`approve` shows the enum only: as written, anyone approves any request.
|
|
226
|
+
|
|
227
|
+
- A unit enum's members are numbered 0, 1, 2… in order; initializers are refused (`value enum members are numbered 0,
|
|
228
|
+
1, 2… in order; leave out initializers`). Stored as one byte, the Borsh u8 index; an argument byte past the last
|
|
229
|
+
member fails with 102.
|
|
230
|
+
- Compare with `===` / `!==`, or `switch`. An enum is not an integer: `u8(status)` is a type error.
|
|
231
|
+
- An enum whose members are strings is an error enum ([errors](language-errors-events.md#error-enums)).
|
|
232
|
+
|
|
233
|
+
## Data enums
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
import { type Mut, type u64 } from "typesol";
|
|
237
|
+
|
|
238
|
+
export type Action = { kind: "Deposit"; amount: u64 } | { kind: "Withdraw"; amount: u64 } | { kind: "Pause" };
|
|
239
|
+
|
|
240
|
+
export interface Vault {
|
|
241
|
+
balance: u64;
|
|
242
|
+
paused: boolean;
|
|
243
|
+
last: Action;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function apply(vault: Mut<Vault>, action: Action): void {
|
|
247
|
+
switch (action.kind) {
|
|
248
|
+
case "Deposit":
|
|
249
|
+
vault.balance += action.amount;
|
|
250
|
+
break;
|
|
251
|
+
case "Withdraw":
|
|
252
|
+
vault.balance -= action.amount;
|
|
253
|
+
break;
|
|
254
|
+
case "Pause":
|
|
255
|
+
vault.paused = true;
|
|
256
|
+
}
|
|
257
|
+
vault.last = action;
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
`apply` shows the data enum only: as written, anyone applies any action to any vault.
|
|
262
|
+
|
|
263
|
+
- A data enum is a union of object types, each with a `kind` string literal: Rust's enum with fields, Borsh-encoded as
|
|
264
|
+
Anchor encodes one. `a.kind === "Deposit"` or `switch (a.kind)`, and TypeScript narrowing picks the variant.
|
|
265
|
+
- Reading a variant's field is checked again at run time: when the value is not that variant, 5112.
|
|
266
|
+
- In account data: 1 tag byte then room for the largest variant. In arguments and events: the tag, then that
|
|
267
|
+
variant's fields.
|
|
268
|
+
- A variant may hold a `string` (`{ kind: "Say"; text: string }`): such an enum works in arguments, events and
|
|
269
|
+
locals, but not in account data.
|
|
270
|
+
- Write a variant as a literal: `vault.last = { kind: "Pause" }`.
|
|
271
|
+
- A union of named types (`type Event = Fill | Place`) is not a data enum: write the variants as object types.
|
|
272
|
+
|
|
273
|
+
## Structs
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { type Mut, type u64 } from "typesol";
|
|
277
|
+
|
|
278
|
+
export interface Point {
|
|
279
|
+
x: u64;
|
|
280
|
+
y: u64;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export interface Player {
|
|
284
|
+
home: Point;
|
|
285
|
+
score: u64;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function moved(p: Point, dx: u64): Point {
|
|
289
|
+
return { x: p.x + dx, y: p.y };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function step(player: Mut<Player>, dx: u64): void {
|
|
293
|
+
const next: Point = moved(player.home, dx);
|
|
294
|
+
next.y += 1n;
|
|
295
|
+
player.home = next;
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
- An `interface` with fixed-size fields is a struct; exported ones are in the IDL. Fields are stored in declaration
|
|
300
|
+
order, back to back, with no padding.
|
|
301
|
+
- A struct literal names every field (`{ x, y: 2n }`); a missing or unknown field is an error. An object literal needs
|
|
302
|
+
a known struct type: a typed local (`const p: Point = { … }`), a field, a helper parameter, `emit<T>(…)`.
|
|
303
|
+
- `a.home = b.home` copies the whole struct, as Rust and Anchor do; how `const` binds one is in
|
|
304
|
+
[copies and references](language-statements.md#copies-and-references).
|
|
305
|
+
- A struct cannot contain itself.
|
|
306
|
+
|
|
307
|
+
### File-local structs
|
|
308
|
+
|
|
309
|
+
`interface Pair { a: u64; b: u64 }` without `export` is the file's own struct, for its helpers (parameters, results,
|
|
310
|
+
`Inout<Pair>`), locals and other such structs; it is left out of the IDL. What the IDL describes (account data,
|
|
311
|
+
instruction arguments and results, events, an exported struct's field, a data enum's variant) cannot hold one: each
|
|
312
|
+
such use is an error saying to export it.
|
|
313
|
+
|
|
314
|
+
## Option
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import { type Mut, type Option, type u64 } from "typesol";
|
|
318
|
+
|
|
319
|
+
export interface Auction {
|
|
320
|
+
best: Option<u64>;
|
|
321
|
+
floor: u64;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function bid(auction: Mut<Auction>, amount: u64, cap: Option<u64>): void {
|
|
325
|
+
if (auction.best === null || amount > auction.best) auction.best = amount;
|
|
326
|
+
const limit = cap ?? auction.floor;
|
|
327
|
+
if (amount > limit) auction.best = null;
|
|
328
|
+
auction.floor = auction.best!;
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
- `Option<T>` (or `T | null`) is a value or `null`. Compare with `=== null` / `!== null`; TypeScript narrows it.
|
|
333
|
+
- Using an empty option where a value is needed fails with 5108; `x!` is the value, or 5108.
|
|
334
|
+
- `a ?? b` takes `b` only when `a` is empty, and evaluates `b` only then; the result is an Option when `b` can be null.
|
|
335
|
+
- `===` between options, or with a value, follows JavaScript: `null === null`, and an empty option never equals a
|
|
336
|
+
value.
|
|
337
|
+
- `x.home?.field` on an `Option<struct>` gives an Option (empty when the option is). `?.` on anything else is refused:
|
|
338
|
+
`?. works on optional accounts and Option<struct> values (other values are never null)`.
|
|
339
|
+
- **Bytes.** In account data: always 1 + size(T) bytes, `{ is_some, value }`. In arguments and events: Borsh, one
|
|
340
|
+
byte when empty.
|
|
341
|
+
- `Option<Point>` in account data: `=== null`, `p.home.x` after narrowing, `p.home = null` or `= { x, y }`. Once
|
|
342
|
+
narrowed, `p.home` (or an `Option<FixedArray>`) passes to a helper that takes the struct (or array).
|
|
343
|
+
- `Option<FixedArray<T, N>>` fields (Anchor's `Option<[u16; 3]>`): one tag byte then N elements in fixed layouts,
|
|
344
|
+
Borsh in arguments and events.
|
|
345
|
+
|
|
346
|
+
## Lists
|
|
347
|
+
|
|
348
|
+
There are three list types. All of them have `.length` (a `u64`), `get(i)` and `set(i, v)` with bounds checks (5104),
|
|
349
|
+
`for … of`, and the [list methods](#list-methods). Unlike JavaScript arrays, indexing with `[ ]` is refused (`indexing
|
|
350
|
+
with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n)`), and indexes are bigints.
|
|
351
|
+
|
|
352
|
+
| | Size | Grows | Where |
|
|
353
|
+
| --- | --- | --- | --- |
|
|
354
|
+
| `FixedArray<T, N>` | N elements, always | no | account data, arguments, locals |
|
|
355
|
+
| `FixedVec<T, N>` | u32 length + room for N | up to N | account data, arguments, locals, events, return data |
|
|
356
|
+
| `Vec<T>` | u32 length + its elements | the account is resized | account data, arguments (read-only), events |
|
|
357
|
+
|
|
358
|
+
Which one to use in account data:
|
|
359
|
+
|
|
360
|
+
- **`FixedArray<T, N>`** when there are always N elements (a board, a fixed set of slots). The account's rent covers
|
|
361
|
+
all N from creation.
|
|
362
|
+
- **`FixedVec<T, N>`** when the count varies up to a known maximum (owners of a multisig, at most N). The account is
|
|
363
|
+
created at its full size, so its creator pays the rent for N elements up front and nothing grows later; a `push`
|
|
364
|
+
past N fails with 5104. It also works in locals, nested structs and return data.
|
|
365
|
+
- **`Vec<T>`** when the count has no useful maximum. The account starts small and each `push(v, payer)` resizes it,
|
|
366
|
+
`payer` paying the extra rent, so the instruction needs a `SystemProgram`; it grows at most 10 KiB per instruction
|
|
367
|
+
(3016) and 10 MiB in all. A struct with a `Vec` is account data only, not a local or a nested struct.
|
|
368
|
+
|
|
369
|
+
### FixedArray
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
import { type FixedArray, type Mut, type u64, fixedArray } from "typesol";
|
|
373
|
+
|
|
374
|
+
export interface Board {
|
|
375
|
+
scores: FixedArray<u64, 8>;
|
|
376
|
+
best: u64;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function submit(board: Mut<Board>, slot: u64, score: u64): void {
|
|
380
|
+
board.scores.set(slot, score);
|
|
381
|
+
for (const s of board.scores) if (s > board.best) board.best = s;
|
|
382
|
+
const recent = fixedArray<u64, 4>(0n);
|
|
383
|
+
recent.set(0n, score);
|
|
384
|
+
board.best += recent.get(0n) - score;
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
- `FixedArray<T, N>` has N elements, N a literal from 1 to 1000000; elements can be integers, booleans, Pubkeys,
|
|
389
|
+
enums, `FixedString<N>` or structs of fixed size. In account data it is N × size(T) bytes.
|
|
390
|
+
- `fixedArray<T, N>(fill)` makes a local array on the stack, up to 256 elements (`fixedArray<T, N>: N must be a literal
|
|
391
|
+
1..256 (locals live on the 4KB stack)`), filled with `fill`. Elements may be structs (the fill built once and copied
|
|
392
|
+
into each slot) or `FixedString<N>`. It may be a struct literal's field value (`{ prices: fixedArray<u64, 16>(0n),
|
|
393
|
+
… }`), filled in place, and written inline it feeds a chain, a list method or `for … of`
|
|
394
|
+
(`fixedArray<u64, 3>(2n).map((x) => x * 5n).reduce(…)`).
|
|
395
|
+
|
|
396
|
+
### FixedVec
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
import { type FixedVec, type Mut, type Pubkey, fixedVec, require } from "typesol";
|
|
400
|
+
|
|
401
|
+
export interface Multisig {
|
|
402
|
+
owners: FixedVec<Pubkey, 8>;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export function setOwners(ms: Mut<Multisig>, owners: FixedVec<Pubkey, 8>): void {
|
|
406
|
+
ms.owners = owners;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function addOwner(ms: Mut<Multisig>, owner: Pubkey): void {
|
|
410
|
+
require(!ms.owners.includes(owner), "already an owner");
|
|
411
|
+
ms.owners.push(owner);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function reset(ms: Mut<Multisig>, first: Pubkey): void {
|
|
415
|
+
ms.owners = fixedVec([first]);
|
|
416
|
+
const scratch: FixedVec<Pubkey, 8> = fixedVec([]);
|
|
417
|
+
scratch.pushAll(ms.owners);
|
|
418
|
+
scratch.pop();
|
|
419
|
+
}
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
These show the list operations only: as written, anyone can replace or add to any multisig's owners. The showcase
|
|
423
|
+
multisig ([`showcase/mainnet/multisig/multisig.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/multisig/multisig.ts))
|
|
424
|
+
gives its `setOwners` a `multisigSigner: Seeds<Signer, ["@multisig"], "@multisig.nonce">` parameter: the multisig's
|
|
425
|
+
own PDA must sign, which only its `executeTransaction` does, for a transaction enough owners approved.
|
|
426
|
+
|
|
427
|
+
- `FixedVec<T, N>` is a list with room for N elements: a u32 length and the room, always 4 + N × size(T) bytes. Any
|
|
428
|
+
field, any number of them, nested structs too. Elements as for FixedArray.
|
|
429
|
+
- `get`, `set`, `push(v)`, `pop()`, `clear()`, `.length`, `for … of`. `push` on a full one fails with 5104.
|
|
430
|
+
- `xs.pushAll(items)` appends a whole list of the same elements in one copy: another FixedVec, a FixedArray or Vec, a
|
|
431
|
+
Vec argument, the instruction data or a slice of it. It is a memcpy (about 0.01 CU a byte for 1000 bytes, against 11
|
|
432
|
+
for a `push` loop), and fails with 5104, appending nothing, when it does not fit. (`Vec` declares `pushAll` so a Vec
|
|
433
|
+
passes for a FixedVec, but a Vec grows one `push` at a time.)
|
|
434
|
+
- `acct.owners = fixedVec([a, b])` writes a whole one (the unused slots zeroed); `acct.owners = owners` copies a `Vec`
|
|
435
|
+
argument or another list of the same elements into it, as Anchor's `multisig.owners = owners` (more than N: 5104).
|
|
436
|
+
- As an argument, `ids: FixedVec<u64, 8>` is a Borsh Vec of at most N elements, read like a `Vec` argument (more fail
|
|
437
|
+
with 102).
|
|
438
|
+
- In account data, returned structs and events it has its fixed layout.
|
|
439
|
+
- **Local lists.** A FixedVec or FixedArray of integers, booleans, Pubkeys, enums, `FixedString<N>` or fixed-size
|
|
440
|
+
structs can be a local, on the stack: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey: k, isSigner: false,
|
|
441
|
+
isWritable: false }])`, `const buf: FixedVec<u8, 600> = fixedVec([])`, `const pair: FixedArray<Meta, 2> =
|
|
442
|
+
fixedArray(meta)`.
|
|
443
|
+
- Given another list (`const y: FixedVec<Pubkey, 4> = xs`) it is a copy, as a struct local is.
|
|
444
|
+
- Setting one up costs about the same at any size: `fixedVec([])` of 1280 bytes is about 10 CU (the free slots are
|
|
445
|
+
zeroed by the memset syscall, the elements written in place, also as a struct literal's field).
|
|
446
|
+
- **Size limit.** One list holds at most 2 KiB of elements (the FixedVec's u32 length aside: `FixedVec<u32, 512>`
|
|
447
|
+
fits). The 4 KiB stack frame is shared with the rest of the function, and a frame that overflows is reported with
|
|
448
|
+
its biggest locals; a bigger list is a compile error naming its size. [`@heap`](#heap-values) moves one to the heap.
|
|
449
|
+
- A `FixedVec<u8, N>` is also a byte buffer: `pushLE`, `pushKey`, `pushBorsh`, `setLE`, `truncate`
|
|
450
|
+
([byte builders](language-native.md#byte-strings-built-by-hand)).
|
|
451
|
+
|
|
452
|
+
### Vec
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
import { type Mut, type Pubkey, type Signer, type SystemProgram, type u64, type Vec } from "typesol";
|
|
456
|
+
|
|
457
|
+
export interface Entry {
|
|
458
|
+
who: Pubkey;
|
|
459
|
+
amount: u64;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export interface Book {
|
|
463
|
+
total: u64;
|
|
464
|
+
entries: Vec<Entry>;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export function add(payer: Mut<Signer>, book: Mut<Book>, systemProgram: SystemProgram, amount: u64): void {
|
|
468
|
+
book.entries.push({ who: payer.key, amount }, payer);
|
|
469
|
+
book.total += amount;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export function sum(book: Mut<Book>, amounts: Vec<u64>): void {
|
|
473
|
+
for (const a of amounts) book.total += a;
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
- **In account data**, `entries: Vec<Entry>` holds any number of elements. An account may have any number of Vecs,
|
|
478
|
+
declared anywhere: they are stored after the fixed-size fields, in the order declared, so every other field keeps
|
|
479
|
+
its offset (the IDL lists that order).
|
|
480
|
+
- `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`. `push` resizes the account (realloc) and `payer` tops
|
|
481
|
+
up the rent, so the instruction needs a `SystemProgram` parameter (`instructions that grow a Vec (push) need a
|
|
482
|
+
SystemProgram parameter to top up rent`). An account grows at most 10 KiB per instruction (3016). `pop()` of a Vec
|
|
483
|
+
of structs works as a statement.
|
|
484
|
+
- A push, pop or clear moves the Vecs stored after it. A reference into one of those cannot be used across it (a
|
|
485
|
+
compile error), also when the reference was made through another parameter that may be the same account: a
|
|
486
|
+
`Dup<…>` pair, a read-only and a writable account of one type, a struct loaded with `loadAccount` /
|
|
487
|
+
`loadAccountMut`.
|
|
488
|
+
- A `Vec` is not a local type (`local type must be an integer, boolean, Pubkey, enum, option or string`): use a
|
|
489
|
+
FixedVec.
|
|
490
|
+
- **As an argument**, `amounts: Vec<u64>` is a read-only view of the instruction data (`Vec arguments are read-only`).
|
|
491
|
+
`Vec<string>` arguments (Anchor's `Vec<String>`) are views too, each element checked as UTF-8 on entry (102), and go
|
|
492
|
+
back out as Borsh through `invoke`.
|
|
493
|
+
- In a `@layout borsh` struct a Vec is Anchor's: anywhere among the fields, held on the heap while the instruction runs
|
|
494
|
+
([`@layout borsh`](language-accounts.md#anchors-account-bytes-layout-borsh)).
|
|
495
|
+
- A struct with a Vec is account data only, never nested in another struct (`Inner has a growable Vec and can only be
|
|
496
|
+
account data, not nested`); nest a FixedVec.
|
|
497
|
+
|
|
498
|
+
### List methods
|
|
499
|
+
|
|
500
|
+
On a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument:
|
|
501
|
+
|
|
502
|
+
```ts
|
|
503
|
+
import { type FixedArray, type FixedVec, type Mut, type u64, type i64 } from "typesol";
|
|
504
|
+
|
|
505
|
+
export interface Orders {
|
|
506
|
+
qty: FixedArray<u64, 8>;
|
|
507
|
+
total: u64;
|
|
508
|
+
firstBig: i64;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function summarize(o: Mut<Orders>): void {
|
|
512
|
+
o.total = o.qty.filter((q) => q > 0n).map((q) => q * 2n).reduce((s, q) => s + q, 0n);
|
|
513
|
+
o.firstBig = o.qty.findIndex((q) => q > 100n);
|
|
514
|
+
if (o.qty.some((q) => q === 0n)) o.total += 1n;
|
|
515
|
+
const big: FixedVec<u64, 8> = o.qty.filter((q) => q > 10n);
|
|
516
|
+
o.total += big.length;
|
|
517
|
+
}
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
- `forEach`, `some`, `every`, `find`, `findIndex` (an `i64`, -1 when absent), `reduce(fn, initial)`, `includes(value)`,
|
|
521
|
+
`indexOf(value)` (an `i64`), `map` and `filter`.
|
|
522
|
+
- `find` gives an Option of the element, for scalar elements. On struct elements read a field: `xs.find(f)!.qty`
|
|
523
|
+
(5108 when nothing matched) or `xs.find(f)?.qty` (an Option).
|
|
524
|
+
- The arrow written at the call is expanded into a loop (elements as `list.get(i)` gives them, structs by reference)
|
|
525
|
+
and may read and write the function's variables.
|
|
526
|
+
- A `map` / `filter` chain used right away (`xs.filter(f).map(g).reduce(h, 0n)`, `.length`, `for … of`) is one loop
|
|
527
|
+
that stores nothing; callbacks after a filter get the index among the elements it let through.
|
|
528
|
+
- Stored (`const ys = xs.filter(f)`), it is a FixedVec on the stack as big as the list it starts from. From a `Vec`,
|
|
529
|
+
give the size: `const ys: FixedVec<u64, 16> = …` (at most 2 KiB; one element more aborts with 5104).
|
|
530
|
+
- `map` gives integers, booleans, Pubkeys or enums. Stored with a `FixedVec<Struct, N>` or `FixedVec<FixedString<N>, M>`
|
|
531
|
+
annotation it gives structs (`(o) => ({ qty: o.qty })`) or text, and inside a chain it gives structs when the
|
|
532
|
+
callback names its struct: `xs.map((o): Scored => ({ … })).filter(…).reduce(…)` (one struct per element, nothing
|
|
533
|
+
stored). A fused `map` to strings is not supported: store it, annotated.
|
|
534
|
+
|
|
535
|
+
## Struct arguments
|
|
536
|
+
|
|
537
|
+
Advanced: what an Anchor port meets when its instructions take structs, lists and Options as arguments.
|
|
538
|
+
|
|
539
|
+
`order: Order`, `ids: FixedArray<u8, 4>`, `orders: Vec<Order>` as instruction arguments are fixed layouts,
|
|
540
|
+
Borsh-identical, validated on entry (booleans, enum tags, option tags, string lengths: 102) and read-only.
|
|
541
|
+
|
|
542
|
+
- A struct holding a `FixedVec` that is only ever an argument is read as Anchor sends it (its FixedVec a Borsh Vec, as
|
|
543
|
+
under [`@layout borsh`](language-accounts.md#anchors-account-bytes-layout-borsh)).
|
|
544
|
+
- A struct holding `Option`s (at any depth, as Anchor's `BankConfigOpt`) that is not account data is Borsh on the wire,
|
|
545
|
+
an empty Option one byte. Read its values after narrowing (`if (c.rate !== null && c.rate.zero_util !== null) …`),
|
|
546
|
+
an `Option<FixedArray<T, N>>` too (`.get(i)`, or copied whole into a `FixedArray` field).
|
|
547
|
+
- An argument may be an `Option<S>` of such a struct (Anchor's `Option<WrappedI80F48>`): a tag byte, then the struct
|
|
548
|
+
when present; read its fields after `x !== null`. Helpers take the struct, not the Option.
|
|
549
|
+
- Likewise `Option<Vec<T>>` (or `Vec<T> | null`, or of a FixedVec; Anchor's `Option<Vec<u8>>`): a tag byte, then the
|
|
550
|
+
Vec. Check `x !== null` before reading it as a list or passing it to a helper that takes the list.
|
|
551
|
+
- A `Vec<u8>` is `bytes` in the IDL, as Anchor writes it (clients pass a Buffer).
|
|
552
|
+
|
|
553
|
+
## f64
|
|
554
|
+
|
|
555
|
+
Advanced: for ports whose events or accounts carry a float.
|
|
556
|
+
|
|
557
|
+
`f64` holds a 64-bit float as its IEEE bits (Borsh writes those 8 bytes; the IDL says `f64`). There is no float
|
|
558
|
+
arithmetic: `f64FromBits(bits)` makes one from bits the program computed with integers (Marginfi's events report
|
|
559
|
+
I80F48 amounts this way), and `f64Bits(x)` reads them back. Float literals (`1.5`) are refused.
|
|
560
|
+
|
|
561
|
+
Every operator with an `f64` operand is refused, since the integer operator would compute on the bits: arithmetic,
|
|
562
|
+
bitwise, shifts, unary `-` and `~`, the ordering comparisons, compound assignments, `++` / `--`, and `min`, `max`,
|
|
563
|
+
`isqrt` and `mulDiv` (`+ on an f64 is not supported: an f64 is held as its IEEE 754 bits and there is no float
|
|
564
|
+
arithmetic …`). Compute in integers and convert at the end. Equality is refused too (`===`, `!==`, `==`, `!=` and
|
|
565
|
+
`switch`): equal bits are not equal numbers, as NaN is not equal to itself and `0` equals `-0`. To compare the bits,
|
|
566
|
+
say so: `f64Bits(a) === f64Bits(b)`. Copying an `f64` (to a local, a field, an event) keeps its bits.
|
|
567
|
+
|
|
568
|
+
An `f64` is not an integer, and an integer is not an `f64`: neither becomes the other by an assignment, an argument,
|
|
569
|
+
a return, an index, an integer cast (`u64(x)`, `u8(x)`, `as u64`) or `??` (`an f64 is not an integer, so it is not
|
|
570
|
+
converted to u64: …`), and an `f64` is not written as text (a template string, `log`), whose digits would be its bits.
|
|
571
|
+
`f64Bits(x)` and `f64FromBits(bits)` are the conversions. As a seed an `f64` gives its 8 bytes, as Rust's
|
|
572
|
+
`to_le_bytes` does (`bigEndian(x)`: `to_be_bytes`).
|
|
573
|
+
|
|
574
|
+
## Heap values
|
|
575
|
+
|
|
576
|
+
Advanced: where memory comes from when the stack is not enough.
|
|
577
|
+
|
|
578
|
+
Locals live on the stack. These live on the heap (32 KiB by default;
|
|
579
|
+
[`HEAP_SIZE_KIB`](language-basics.md#memory-stack-and-heap) raises it), which is never freed during an instruction:
|
|
580
|
+
|
|
581
|
+
- strings built at run time (5110 when the heap is full);
|
|
582
|
+
- a `@layout borsh` struct's `Vec` fields while the instruction runs;
|
|
583
|
+
- the CPI scratch lists of a program that declares `MAX_ACCOUNTS`;
|
|
584
|
+
- a list or struct local marked `/** @heap */`:
|
|
585
|
+
|
|
586
|
+
```ts
|
|
587
|
+
import { type FixedVec, type u8, fixedVec, log } from "typesol";
|
|
588
|
+
|
|
589
|
+
export function collect(n: u8): void {
|
|
590
|
+
/** @heap */
|
|
591
|
+
const ids: FixedVec<u8, 3000> = fixedVec([]);
|
|
592
|
+
ids.push(n);
|
|
593
|
+
log(ids.length);
|
|
594
|
+
}
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
`/** @heap */` on an instruction's list or struct local keeps it on the heap instead of the stack: one allocation per
|
|
598
|
+
declaration, reused when a loop declares it again, up to the heap's size, for about 18 CU. Not in helpers, which may
|
|
599
|
+
run many times while the heap is never freed.
|
|
600
|
+
|
|
601
|
+
**Next:** [Statements and functions](language-statements.md): which TypeScript is TypeSOL.
|