@typesol/cli 0.45.0 → 0.47.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.
Files changed (72) hide show
  1. package/CHANGELOG.md +250 -0
  2. package/README.md +63 -17
  3. package/SECURITY.md +9 -7
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +9 -0
  6. package/dist/cli.js +33 -15
  7. package/dist/compiler/analyze.js +57 -6
  8. package/dist/compiler/diagnostics.d.ts +4 -3
  9. package/dist/compiler/diagnostics.js +10 -6
  10. package/dist/compiler/emit/base.d.ts +1 -1
  11. package/dist/compiler/emit/calls.js +18 -5
  12. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  13. package/dist/compiler/emit/cpi-core.js +8 -4
  14. package/dist/compiler/emit/expressions.d.ts +14 -0
  15. package/dist/compiler/emit/expressions.js +52 -4
  16. package/dist/compiler/emit/shared.d.ts +8 -1
  17. package/dist/compiler/emit/shared.js +8 -1
  18. package/dist/compiler/emit/statements.d.ts +8 -3
  19. package/dist/compiler/emit/statements.js +68 -3
  20. package/dist/compiler/emit/storage.js +5 -1
  21. package/dist/compiler/hints.d.ts +7 -0
  22. package/dist/compiler/hints.js +58 -9
  23. package/dist/compiler/index.d.ts +5 -0
  24. package/dist/compiler/index.js +10 -1
  25. package/dist/compiler/model.js +3 -2
  26. package/dist/compiler/toolchain.d.ts +50 -2
  27. package/dist/compiler/toolchain.js +96 -11
  28. package/dist/idl-coder.d.ts +110 -0
  29. package/dist/idl-coder.js +529 -0
  30. package/dist/node-version.d.ts +4 -0
  31. package/dist/node-version.js +12 -0
  32. package/dist/testing.d.ts +44 -7
  33. package/dist/testing.js +30 -19
  34. package/dist/tools/doctor.d.ts +41 -0
  35. package/dist/tools/doctor.js +96 -14
  36. package/dist/workspace.d.ts +9 -2
  37. package/dist/workspace.js +13 -4
  38. package/docker/deps/0.46.0.lock.json +1206 -0
  39. package/docker/deps/0.47.0.lock.json +1206 -0
  40. package/docs/ai.md +2 -1
  41. package/docs/architecture.md +7 -3
  42. package/docs/audit.md +6 -6
  43. package/docs/case-study-phoenix.md +1 -1
  44. package/docs/case-study-raydium-amm.md +1 -1
  45. package/docs/case-study-spl-stake-pool.md +1 -1
  46. package/docs/cli.md +42 -4
  47. package/docs/errors.md +22 -8
  48. package/docs/glossary.md +210 -0
  49. package/docs/language-accounts.md +499 -0
  50. package/docs/language-basics.md +389 -0
  51. package/docs/language-builtins.md +411 -0
  52. package/docs/language-chain.md +198 -0
  53. package/docs/language-cpi.md +470 -0
  54. package/docs/language-errors-events.md +184 -0
  55. package/docs/language-native.md +493 -0
  56. package/docs/language-pdas.md +198 -0
  57. package/docs/language-statements.md +620 -0
  58. package/docs/language-types.md +601 -0
  59. package/docs/language.md +190 -467
  60. package/docs/mainnet.md +18 -3
  61. package/docs/migrate-from-anchor.md +7 -6
  62. package/docs/security-model.md +3 -3
  63. package/docs/stability.md +3 -1
  64. package/docs/test-your-program.md +54 -15
  65. package/docs/troubleshooting.md +222 -100
  66. package/lib/typesol.d.ts +67 -22
  67. package/llms-full.txt +4920 -638
  68. package/llms.txt +12 -1
  69. package/package.json +2 -6
  70. package/releases/0.45.0.json +732 -0
  71. package/releases/0.46.0.json +817 -0
  72. package/ts-plugin/index.js +16 -5
@@ -0,0 +1,620 @@
1
+ # Statements and functions
2
+
3
+ TypeSOL uses TypeScript's syntax and accepts a subset of its statements and expressions. This page lists exactly which:
4
+ declarations, assignment, control flow, functions and closures, and, at the end, [what is refused](#what-is-refused)
5
+ with the message each refusal gives. Part of the [language guide](language.md).
6
+
7
+ In short, a function body may contain:
8
+
9
+ | Accepted | Notes |
10
+ | --- | --- |
11
+ | `const`, `let` | one name each, with an initializer ([declarations](#declarations)) |
12
+ | assignment, `+=` … `>>=`, `++`, `--` | checked arithmetic ([types](language-types.md#integers)) |
13
+ | `if` / `else`, `? :`, `&&`, `\|\|`, `!` | conditions are `boolean` |
14
+ | `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops) |
15
+ | `switch` | on integers, enums and a data enum's `kind` |
16
+ | `return` | |
17
+ | calls | helpers, closures, built-ins, account methods |
18
+ | `const { a, b } = x` | [destructuring](#destructuring), one level |
19
+ | arrow functions and `function` expressions | [closures](#arrow-functions-and-closures) |
20
+ | template strings, `+` on strings | [strings](language-types.md#strings-built-at-run-time) |
21
+ | `??`, `?.`, `x!` | on options and optional accounts |
22
+
23
+ Everything else is refused at compile time with a message saying what to write instead. Nothing is half-supported.
24
+
25
+ ## Declarations
26
+
27
+ ```ts
28
+ import { type Mut, type u64, type u8 } from "typesol";
29
+
30
+ export interface Counter {
31
+ count: u64;
32
+ step: u8;
33
+ }
34
+
35
+ export function add(counter: Mut<Counter>, times: u64): void {
36
+ const step: u64 = 2n;
37
+ let total = 0n;
38
+ for (let i = 0n; i < times; i++) total += step;
39
+ {
40
+ const total = 1n; // a new name in this block
41
+ counter.step = 1n;
42
+ counter.count += total;
43
+ }
44
+ counter.count += total;
45
+ }
46
+ ```
47
+
48
+ - `const` and `let` declare one plain name with an initializer. `let x: u64;` without one is refused (`declare one
49
+ plain name with an initializer`), and so is `var` (`use const or let, not var`).
50
+ - The type comes from the annotation or the initializer. A local declared from a bare literal (`let total = 0n`) is a
51
+ `u64`; an annotation states the type (`const step: u64 = 2n` above) or picks another width (`const b: u8 = 2n`).
52
+ - A local can be an integer, `boolean`, `Pubkey`, `Hash`, enum, `Option`, `string`, a struct or a `FixedArray` /
53
+ `FixedVec`. A `Vec` cannot be a local: use a `FixedVec`.
54
+ - Block scoping is JavaScript's: a name declared in a block is gone after it, and may shadow an outer one.
55
+ - `const` cannot be reassigned (TypeScript's own error). Unlike JavaScript, parameters cannot be reassigned either
56
+ (`"n" is const or an argument and cannot be reassigned`): copy one into a `let`.
57
+ - Struct field names that are C keywords or names the generated C uses (`default`, `signed`, `int`, `char`, `NULL`,
58
+ `SUCCESS`, …), or that start with `_` or contain `__`, are refused (`"default" is reserved in the generated C; pick
59
+ another name`).
60
+
61
+ ## Assignment
62
+
63
+ You can assign to a local, a field of a writable account (`Mut<T>`), a field of a local struct, a list element through
64
+ `.set(i, v)`, and `.lamports` of a writable account. Instruction arguments are read-only (`instruction arguments are
65
+ read-only; copy the value into a local first`), and so are helper parameters (see [Inout](#inout-parameters)).
66
+
67
+ Compound assignments (`+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`) and `++` / `--` are
68
+ checked like the operators they stand for.
69
+
70
+ ### Copies and references
71
+
72
+ ```ts
73
+ import { type Mut, type u64 } from "typesol";
74
+
75
+ export interface Point {
76
+ x: u64;
77
+ y: u64;
78
+ }
79
+
80
+ export interface Shape {
81
+ a: Point;
82
+ b: Point;
83
+ sum: u64;
84
+ }
85
+
86
+ export function edit(shape: Mut<Shape>): void {
87
+ shape.b = shape.a; // assignment copies the whole struct
88
+ const copy: Point = shape.a; // an annotated binding is a copy
89
+ copy.x += 1n; // shape.a is unchanged
90
+ const ref = shape.a; // an unannotated const binding is a reference
91
+ ref.y += 1n; // changes shape.a.y
92
+ shape.sum = copy.x + ref.y;
93
+ }
94
+ ```
95
+
96
+ - **Assignment copies.** `a.home = b.home` and `a.trail.set(0n, a.home)` copy a whole struct or array of the same type,
97
+ as Rust and Anchor do.
98
+ - **Binding with `const` references.** `const r = acct.home` names the same storage, like a JavaScript object
99
+ reference: writes through `r` change `acct.home`. Struct references are bound with `const`; `let r = acct.home` is
100
+ refused (`bind struct references with const`).
101
+ - **An annotation makes a copy.** `const p: Point = acct.home` (or `= { x, y }`) is a local struct of its own. Lists
102
+ likewise: `const ys: FixedVec<u64, 4> = acct.xs` is a copy.
103
+ - **A reference cannot outlive what it names.** Replacing the referenced place (`book.bids.set(i, …)`, `pop()`,
104
+ `clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JavaScript would
105
+ keep the old object: `"q" still refers to a.home; replacing it here would change what "q" reads (in JS it keeps the
106
+ old value). Copy the fields you need into locals first`.
107
+ - A ternary can pick a reference: `const o = side === Side.Bid ? book.bids.get(i) : book.asks.get(i)` aliases one of
108
+ them, no copy.
109
+ - Scalars (integers, booleans, `Pubkey`) are always copied.
110
+
111
+ ## Expressions
112
+
113
+ - **Operators**: arithmetic and bitwise operators on integers ([integers](language-types.md#integers)), comparisons,
114
+ `&&`, `||`, `!`, `===`, `!==`, and `? :`. `instanceof`, `in`, `typeof`, `delete`, `void` and the comma operator are
115
+ refused.
116
+ - **Evaluation order**: operands and arguments are read left to right, as in JavaScript, even when a later one changes
117
+ account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list
118
+ callback writing it).
119
+ - **Ternaries** run only the chosen branch: `const fee = vip ? 0n : 30n`. Between accounts too:
120
+ `const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or
121
+ `RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a
122
+ remaining account does (typed CPIs, `readData`, `loadRaw` / `loadRawMut`, `loadBorsh`, helpers taking a
123
+ `RemainingAccount`).
124
+ - **`??`, `?.` and `!`** work on options and optional accounts ([Option](language-types.md#option),
125
+ [optional accounts](language-accounts.md#optional-accounts)). `?.` and `!` on anything else, and a method call
126
+ through `?.`, are refused (a `find` on struct elements excepted: `xs.find(f)!.qty`).
127
+ - **Object literals** need a known struct type ([structs](language-types.md#structs)); array literals are only
128
+ written inline, as seeds, CPI account lists, a `fixedVec([…])` or a list of functions in `for … of`.
129
+
130
+ ## Conditions
131
+
132
+ ```ts
133
+ import { type Mut, type u64 } from "typesol";
134
+
135
+ export interface Tier {
136
+ level: u64;
137
+ }
138
+
139
+ export function classify(tier: Mut<Tier>, amount: u64, vip: boolean): void {
140
+ if (vip && amount > 0n) tier.level = 3n;
141
+ else if (amount >= 1000n) tier.level = 2n;
142
+ else tier.level = amount < 10n ? 0n : 1n;
143
+ }
144
+ ```
145
+
146
+ A condition (in `if`, `while`, `for`, `? :`, `&&`, `||`, `!`) must be a `boolean`. Unlike JavaScript, there is no
147
+ truthiness: `if (amount)` is refused (`expected boolean, got u64`).
148
+
149
+ `==` and `!=` compile like `===` and `!==`: both operands have the same type (`operands have different types` otherwise),
150
+ so there is no coercion for the loose forms to do.
151
+
152
+ ## Loops
153
+
154
+ ```ts
155
+ import { type FixedArray, type Mut, type u64, type Vec } from "typesol";
156
+
157
+ export interface Book {
158
+ levels: FixedArray<u64, 8>;
159
+ total: u64;
160
+ }
161
+
162
+ export function tally(book: Mut<Book>, extra: Vec<u64>, n: u64): void {
163
+ for (let i = 0n; i < n; i++) book.total += 1n;
164
+ for (let i = 0n, j = n; i < j; i++, j--) book.total += 1n;
165
+ for (const level of book.levels) {
166
+ if (level === 0n) continue;
167
+ book.total += level;
168
+ }
169
+ for (const x of extra) {
170
+ if (x > 100n) break;
171
+ book.total += x;
172
+ }
173
+ let k = 0n;
174
+ while (k < 3n) k++;
175
+ do {
176
+ k--;
177
+ } while (k > 0n);
178
+ }
179
+ ```
180
+
181
+ - `for (init; condition; update)` with one counter or several (`for (let i = 0n, j = n; i < j; i++, j--)`): several
182
+ declarations, and comma-separated updates run in order after each pass, `continue` included.
183
+ - `for (const x of list)` over a `Vec`, `FixedArray`, `FixedVec`, a `Vec` argument, the instruction data, a stored
184
+ `map` / `filter` result or a chain. Each `x` is what `list.get(i)` gives: a value, or a reference into account data
185
+ for structs. The length is read again every step, as in JavaScript.
186
+ - `for (const f of [dbl, inc])` runs a list of named functions in turn ([functions](#arrow-functions-and-closures)).
187
+ - `while`, `do … while`, `break` and `continue`. Inside a `switch`, `break` leaves the switch and `continue` the
188
+ enclosing loop, as in JavaScript.
189
+ - Labels (`outer: for …`) and `for … in` are refused.
190
+ - There is no iteration limit: loops are bounded by the transaction's compute budget.
191
+ - Remaining accounts are iterated by index: `for (let i = 0n; i < rest.length; i++) rest.get(i)`.
192
+
193
+ ## switch
194
+
195
+ ```ts
196
+ import { type Mut, type u128, type u64 } from "typesol";
197
+
198
+ export enum Side {
199
+ Bid,
200
+ Ask,
201
+ }
202
+
203
+ export interface Book {
204
+ bids: u64;
205
+ asks: u64;
206
+ }
207
+
208
+ const LARGE = 1000n;
209
+
210
+ export function place(book: Mut<Book>, side: Side, size: u128): void {
211
+ switch (side) {
212
+ case Side.Bid:
213
+ book.bids += 1n;
214
+ break;
215
+ case Side.Ask:
216
+ book.asks += 1n;
217
+ }
218
+ switch (size) {
219
+ case 0n:
220
+ case 1n:
221
+ book.bids += 0n;
222
+ break;
223
+ case LARGE:
224
+ book.asks += 0n;
225
+ break;
226
+ default:
227
+ book.bids += 0n;
228
+ }
229
+ }
230
+ ```
231
+
232
+ `switch` works on integers (128-bit ones too), enums and a data enum's `.kind`, with JavaScript's `break` and
233
+ fallthrough. Case labels are literals, constants or enum members (`case labels must be literals, constants or enum
234
+ members`). A `switch` on a string is refused (`switch works on integers and enums`).
235
+
236
+ ## Destructuring
237
+
238
+ ```ts
239
+ import { type Account, type Mut, type Pubkey, type u64 } from "typesol";
240
+
241
+ export interface Point {
242
+ x: u64;
243
+ y: u64;
244
+ }
245
+
246
+ export interface Player {
247
+ owner: Pubkey;
248
+ pos: Point;
249
+ score: u64;
250
+ }
251
+
252
+ export function read(player: Account<Player>, out: Mut<Player>): void {
253
+ const { owner, pos: p } = player;
254
+ let { score } = player;
255
+ score += p.x;
256
+ out.owner = owner;
257
+ out.score = score;
258
+ }
259
+ ```
260
+
261
+ `const { owner, pos: p } = acct` (or `let` for scalars you change) from a name or a field path: one declaration per
262
+ name, read as `acct.owner` would be. Scalars are copies, nested structs are references. There is no rest
263
+ (`...rest is not supported in destructuring`), no defaults, and no nesting (`nested destructuring is not supported;
264
+ destructure in two steps`). Array destructuring is only for `const [address, bump] =
265
+ findProgramAddressWithBump(seeds, program)` ([PDAs](language-pdas.md#deriving-addresses-in-the-body)).
266
+
267
+ ## Helpers
268
+
269
+ ```ts
270
+ import { type Mut, type u64 } from "typesol";
271
+
272
+ export interface Fee {
273
+ numerator: u64;
274
+ denominator: u64;
275
+ }
276
+
277
+ export interface Vault {
278
+ fees: u64;
279
+ rate: Fee;
280
+ }
281
+
282
+ function applyFee(fee: Fee, amount: u64): u64 {
283
+ return (amount * fee.numerator) / fee.denominator;
284
+ }
285
+
286
+ function at(numerator: u64): Fee {
287
+ return { numerator, denominator: 100n };
288
+ }
289
+
290
+ export function charge(vault: Mut<Vault>, amount: u64): void {
291
+ vault.fees += applyFee(vault.rate, amount);
292
+ vault.fees += applyFee({ numerator: 3n, denominator: 100n }, amount);
293
+ vault.rate = at(5n);
294
+ vault.fees += at(1n).numerator;
295
+ }
296
+ ```
297
+
298
+ A helper is a function that is not exported (and every function of an imported file).
299
+
300
+ - **Parameters**: values (integers, booleans, `Pubkey`, `Hash`, enums, `Option`, `string`, `u256`), structs, lists
301
+ (below), data enums, `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`), the
302
+ instruction data (`InstructionBytes`), functions ([below](#functions-as-arguments)) and accounts the instruction
303
+ already checked (`Signer`, `Account<T>`, `Mut<T>`, `AccountInfo`, token accounts, mints, programs). Helpers cannot
304
+ take `Init<…>` accounts or constraint types (`helpers take accounts that exist`; `constraints belong on instruction
305
+ parameters`), and a read-only account cannot be passed where a helper takes `Mut<T>`.
306
+ - **Results**: `void`, a scalar, a `string`, a function, or a fixed-size struct (`function at(numerator: u64): Fee`
307
+ above): the caller gets its own copy, to bind, store with `vault.rate = at(5n)` / `arr.set(i, at(…))` or read as
308
+ `at(1n).numerator`. The return type is required (`helper functions need
309
+ an explicit return type`), and a helper with a result must return on every path (TypeScript checks it; a path that
310
+ still ends without one fails with 5114).
311
+ - **Arguments written in place**: a struct, data-enum or `fixedArray<T, N>(fill)` argument may be a literal
312
+ (`applyFee({ numerator: 3n, denominator: 100n }, amount)`, nested literals and a ternary with a literal branch too),
313
+ built in a local of its own as `const fee: Fee = { … }` would be.
314
+ - **No recursion**: a helper cannot call itself, directly or through others (`recursion is not supported: a -> b ->
315
+ a`). Nor can a closure.
316
+ - Helpers are not `async` or generators, and are declared at the top level: a `function` declaration inside a
317
+ function is refused (declare a `const` arrow there instead).
318
+
319
+ ### How arguments are passed
320
+
321
+ TypeSOL keeps JavaScript's meaning (a callee cannot change the caller's values unless it is given the place to change)
322
+ while passing large values by pointer:
323
+
324
+ - Struct, list and data-enum parameters are read-only, passed by pointer. Writing to one is refused: `helper parameters
325
+ are read-only: declare p as Inout<T> to change the caller's value in place, or copy it into a local first`.
326
+ - When the helper also takes accounts, an argument that is account data (a field of a view or of a loaded account) is
327
+ copied at the call, since the helper's writes could change it. A struct the caller owns (a local, a helper's result,
328
+ an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed
329
+ in place.
330
+ - `Pubkey`, `Option`, `string` and `u256` parameters are passed by pointer too (the SBF target passes a C struct as a
331
+ pointer to the caller's object):
332
+ - a helper that writes nothing reads the caller's value in place;
333
+ - a helper that can write (it takes accounts, remaining accounts or `Inout<T>` places) gets a copy taken at the
334
+ call, and so does text a string argument views in account data or in an `Inout<T>` place;
335
+ - except when the argument is one nothing the helper is given reaches: a local, a temporary, an instruction
336
+ argument, a constant, an account's key, the program id or a parameter of the calling helper, passed in place.
337
+ - **List parameters.** A `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's
338
+ FixedVec of the same elements (a local, a field of a local struct or of account data) with at most N elements of
339
+ room. It is read-only and passed as a view of its elements, by pointer; a list in account data is copied first when
340
+ the helper also takes accounts, as a struct is.
341
+ - A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at
342
+ instruction entry is passed along).
343
+
344
+ ### Inline and @noinline
345
+
346
+ clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame.
347
+ `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with
348
+ large locals of its own (Phoenix's order ids, built after its event recorder's last CPI):
349
+
350
+ ```ts
351
+ import { type Mut, type u64, fixedArray } from "typesol";
352
+
353
+ export interface Out {
354
+ v: u64;
355
+ }
356
+
357
+ /** @noinline */
358
+ function third(seed: u64): u64 {
359
+ const xs = fixedArray<u64, 200>(seed);
360
+ return xs.get(3n);
361
+ }
362
+
363
+ export function run(out: Mut<Out>): void {
364
+ out.v = third(out.v);
365
+ }
366
+ ```
367
+
368
+ ### Inout parameters
369
+
370
+ ```ts
371
+ import { type FixedVec, type Inout, type Mut, type u64 } from "typesol";
372
+
373
+ export interface Recorder {
374
+ count: u64;
375
+ last: u64;
376
+ }
377
+
378
+ export interface Log {
379
+ rec: Recorder;
380
+ ids: FixedVec<u64, 4>;
381
+ }
382
+
383
+ function addEvent(rec: Inout<Recorder>, value: u64): void {
384
+ rec.count += 1n;
385
+ rec.last = value;
386
+ }
387
+
388
+ function remember(ids: Inout<FixedVec<u64, 4>>, id: u64): void {
389
+ if (ids.length === 4n) ids.clear();
390
+ ids.push(id);
391
+ }
392
+
393
+ export function record(log: Mut<Log>, value: u64): void {
394
+ addEvent(log.rec, value);
395
+ remember(log.ids, value);
396
+ const scratch: Recorder = { count: 0n, last: 0n };
397
+ addEvent(scratch, value);
398
+ }
399
+ ```
400
+
401
+ `rec: Inout<Recorder>` is Rust's `rec: &mut Recorder`: the helper gets the caller's place itself (a pointer, no copy:
402
+ about the compute units of the same code written inline) and the caller sees its writes after the call, as JavaScript
403
+ shares an object passed to a function.
404
+
405
+ - `T` is a fixed-size struct, a `FixedArray<T, N>` or a `FixedVec<T, N>` (its `push`, `pop` and `clear` included).
406
+ - **The argument is a writable place**: a local struct or list, a `loadBorsh` local, a field path of a local, of a
407
+ `loadRawMut` view or of a `Mut<T>` account, a list element (`book.levels.get(i)`, a narrowed Option's value),
408
+ another `Inout` parameter (passed on), or a literal (a fresh value nobody else sees). A read-only one (a field of an
409
+ `Account<T>`, a `loadRaw` view, an instruction argument, a read-only parameter) is a compile error naming what to
410
+ change (`bump() changes p (Inout): "a" is read-only; declare it Mut<...>`).
411
+ - **Nothing else may reach the place during the call.** No other argument may share storage with an Inout one (one
412
+ place inside the other; two elements of one list, whatever their indexes, a BigVec slice's elements included; an
413
+ account and a place inside it; a read-only struct argument inside it: pass a copy). An element of a `Vec` or
414
+ `BigVec` is refused when the call may resize or filter that list (the helper takes writable or remaining accounts),
415
+ since its elements would move. A reference into the place (`const e = p.items.get(0n)`) that is read after the call
416
+ is refused, since the helper may replace what it points at (copy the fields first, or read them through the place).
417
+ - **Places that may be one account at run time** (two `Dup<…>` accounts, a writable and a read-only account, native
418
+ views) are compared before the call: 2040 when they overlap ([which
419
+ places](language-accounts.md#two-parameters-one-account); native views and the one pair left to run time:
420
+ [native programs](language-native.md#inout-places-that-may-be-one-account)).
421
+ - **Values are not places.** Integers, Pubkeys, strings and Options are values, which JavaScript copies into a function
422
+ too: return the new value (`x = f(x)`) or keep it in a struct and take `Inout<ThatStruct>` (`Inout<u64>: a u64 is a
423
+ value, which JS copies into a function too, …`). `Vec<T>`, `BigVec<T>`, accounts and data enums are refused with
424
+ what to write instead, and so is `Inout<T>` anywhere but a helper's parameter.
425
+ - Closures, and helpers expanded because they were given one, take `Inout<T>` the same way; their struct parameters
426
+ were references already.
427
+
428
+ ## Arrow functions and closures
429
+
430
+ ```ts
431
+ import { type Mut, type u64 } from "typesol";
432
+
433
+ export interface Sum {
434
+ total: u64;
435
+ }
436
+
437
+ const fee = (x: u64): u64 => x / 100n;
438
+
439
+ export function collect(sum: Mut<Sum>, a: u64, b: u64): void {
440
+ let total = 0n;
441
+ const add = (v: u64): void => {
442
+ total += v - fee(v);
443
+ };
444
+ add(a);
445
+ add(b);
446
+ const double = function (x: u64): u64 {
447
+ return x * 2n;
448
+ };
449
+ sum.total = double(total);
450
+ }
451
+ ```
452
+
453
+ - `const f = (x: u64): u64 => …` or `const f = function (…) {…}`, at the top level or inside a function.
454
+ - One that captures nothing becomes a helper.
455
+ - One that reads or writes the enclosing function's variables (a closure) is expanded where it is called: its names
456
+ mean what they meant where it was declared, struct parameters are references, `return` leaves the closure. It cannot
457
+ call itself.
458
+ - Parameter types are required where the function is declared (TypeScript's `noImplicitAny`); an arrow written at a
459
+ call takes them from the parameter it is passed to.
460
+ - Functions are values where they can be expanded: `const h = g` names the same function, and a function that returns
461
+ one (`function adder(n: u64): (x: u64) => u64 { return (x) => x + n; }`) makes a closure where it is called
462
+ (`const add5 = adder(5n)`, or `adder(5n)(x)`).
463
+ - A function can be chosen at run time between named ones, `const g = k === 1n ? dbl : inc` (the condition is read
464
+ once, there; a call runs only the chosen one), and a list of named functions can be run in turn,
465
+ `for (const f of [dbl, inc]) total += f(x)` (unrolled; `continue` and `break` work).
466
+ - Functions cannot be stored in a struct, chosen from a list by index, or returned from an instruction.
467
+
468
+ ### Functions as arguments
469
+
470
+ ```ts
471
+ import { type Mut, type u64 } from "typesol";
472
+
473
+ export interface Out {
474
+ v: u64;
475
+ }
476
+
477
+ function applyTwice(f: (x: u64) => u64, v: u64): u64 {
478
+ return f(f(v));
479
+ }
480
+
481
+ function dbl(x: u64): u64 {
482
+ return x * 2n;
483
+ }
484
+
485
+ export function run(out: Mut<Out>, k: u64): void {
486
+ out.v = applyTwice(dbl, out.v);
487
+ out.v = applyTwice((x) => x * 3n, out.v);
488
+ out.v = applyTwice((x) => x + k, out.v);
489
+ }
490
+ ```
491
+
492
+ A helper may take a function parameter. It is compiled once per named function passed (a helper, or a local function
493
+ that captures nothing). An arrow written at the call works too (`applyTwice((x) => x * 3n, v)`: its types come from the
494
+ parameter) when it reads none of the caller's variables. Given a closure (one that reads them, as `(x) => x + k`), the
495
+ helper is expanded where it is called instead, like a closure, so it runs where the closure can (its type parameters
496
+ bound from the call, its accounts the caller's).
497
+
498
+ ### Generic helpers
499
+
500
+ ```ts
501
+ import { type Mut, type u8, u64 } from "typesol";
502
+
503
+ export interface Point {
504
+ x: u64;
505
+ y: u64;
506
+ }
507
+
508
+ export interface Out {
509
+ v: u64;
510
+ p: Point;
511
+ }
512
+
513
+ function bigger<T extends bigint>(a: T, b: T): T {
514
+ return a > b ? a : b;
515
+ }
516
+
517
+ function pick<T>(first: boolean, a: T, b: T): T {
518
+ return first ? a : b;
519
+ }
520
+
521
+ export function run(out: Mut<Out>, x: u8, y: u8, first: boolean): void {
522
+ out.v = bigger(out.v, 3n) + u64(bigger(x, y));
523
+ const home: Point = { x: 1n, y: 2n };
524
+ out.p = pick<Point>(first, home, out.p);
525
+ }
526
+ ```
527
+
528
+ `function bigger<T extends bigint>(a: T, b: T): T` is compiled once per set of types it is called with
529
+ (`bigger(out.v, 3n)` with a `u64`, `bigger(x, y)` with `u8` arguments, or `bigger<u128>(1n, 2n)` when only literals
530
+ tell). A type parameter stands for an integer, boolean,
531
+ `Pubkey`, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct
532
+ value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still
533
+ type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: write `return (a + b) as T` (`as` names a type the
534
+ value already has; it never converts). Local functions and arrows passed inside a generic helper are refused: declare
535
+ them at the top level.
536
+
537
+ ## What is refused
538
+
539
+ Each row was compiled; the message is the compiler's, today, or TypeScript's where TypeScript refuses first. Messages
540
+ may gain a hint line.
541
+
542
+ | Construct | Example | Message |
543
+ | --- | --- | --- |
544
+ | classes | `class Counter { n = 0n; }` | classes are not supported: describe account data with an interface and logic with functions |
545
+ | `async` | `export async function f(): Promise<void> {}` | instructions cannot be async or generators |
546
+ | `async` helpers | `async function h(): Promise<void> {}` | helper functions cannot be async |
547
+ | generators | `function* ids(): Generator<u64> { yield 1n; }` | helper functions cannot be generators |
548
+ | `await` | `const y = await n;` | 'await' expressions are only allowed within async functions and at the top levels of modules. |
549
+ | `throw` | `throw new Error("bad");` | throw is not supported: fail the instruction with require(false, ErrorCode.X) or require(cond, "message") |
550
+ | `try` / `catch` / `finally` | `try { b.value = 1n; } catch { b.value = 2n; }` | try/catch is not supported: a failed check or CPI aborts the whole instruction, so check first with require(…) |
551
+ | `number` literals | `b.value = 1;` | Type 'number' is not assignable to type 'bigint'. hint: integers (u64, u32, i64 …) are bigint in TypeSOL: write 1n, not 1, and take u64, not number |
552
+ | floats | `b.value = 1.5;` | Type 'number' is not assignable to type 'bigint'. |
553
+ | `number` in a loop | `for (let i = 0; i < 3; i++) {}` | use a bigint literal (0n): TypeSOL integers are bigints |
554
+ | `number`, `any`, `unknown`, `T[]`, tuples | `export function f(x: number): void {}` | parameter type must be an integer, boolean, Pubkey, string, or an account type (…) |
555
+ | `any` locals | `const y: any = n;` | local type must be an integer, boolean, Pubkey, enum, option or string |
556
+ | `var` | `var y = n;` | use const or let, not var |
557
+ | `let` without a value | `let x: u64;` | declare one plain name with an initializer |
558
+ | top-level `let` and `var` | `let total = 0n;` (top level) | top-level variables must be const literals |
559
+ | top-level statements | `log("start");` (top level) | this kind of statement (ExpressionStatement) is not supported at the top level of a TypeSOL file |
560
+ | reassigning a parameter | `n = 3n;` | "n" is const or an argument and cannot be reassigned |
561
+ | writing an argument | `p.x = 3n;` (`p: Point` argument) | instruction arguments are read-only; copy the value into a local first |
562
+ | `for … in` | `for (const k in b) {}` | for … in is not supported: use for (init; cond; step), for (const x of list), while or do … while |
563
+ | labels | `outer: for (…) { break outer; }` | LabeledStatement is not supported in TypeSOL |
564
+ | truthiness | `if (n) log("x");` | expected boolean, got u64 |
565
+ | indexing with `[ ]` | `b.value = b.xs[0];` | indexing with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n) |
566
+ | array literals as values | `const a = [1n, 2n];` | arrays are only allowed inline as seeds/CPI lists; declare local arrays with fixedArray<T, N>(fill) |
567
+ | untyped object literals, spread | `const o = { a: 1n };` | an object literal needs a struct type here: give it one (const p: Point = { … }), … |
568
+ | `new` | `const m = new Map<u64, u64>();` | this syntax (NewExpression) is not supported in TypeSOL expressions |
569
+ | `typeof` | `const t = typeof n;` | typeof is not supported at run time: the types are known when the program compiles |
570
+ | `delete` | `const k = delete b.value;` | The operand of a 'delete' operator must be optional. (TypeScript; on an operand TypeScript accepts: delete is not supported: account fields always exist; set the value instead) |
571
+ | `void` | `const v = void n;` | this syntax (VoidExpression) is not supported in TypeSOL expressions |
572
+ | `instanceof` | `if (b instanceof Object) {}` | operator instanceof is not supported |
573
+ | `in` | `if ("value" in b) {}` | operator in is not supported |
574
+ | the comma operator | `y = (b.value = 1n, 2n);` | operator , is not supported |
575
+ | regular expressions | `const r = /a/;` | this syntax (RegularExpressionLiteral) is not supported in TypeSOL expressions |
576
+ | tagged templates | ``const t = String.raw`x`;`` | this syntax (TaggedTemplateExpression) is not supported in TypeSOL expressions |
577
+ | `undefined` | `if (b.value === undefined) {}` | unknown name "undefined" |
578
+ | optional parameters | `export function f(x?: u64): void {}` | optional parameters are not supported; use x: Option<T> and pass null for none |
579
+ | default parameters | `export function f(x: u64 = 1n): void {}` | default values are not supported; the client passes every argument |
580
+ | rest parameters | `export function f(...x: u64[]): void {}` | ...rest parameters are not supported; take a Vec<T> argument, or remainingAccounts() for accounts |
581
+ | optional fields | `export interface O { v?: u64 }` | optional fields are not supported; use v: Option<T> (null for none) |
582
+ | methods in interfaces | `export interface G { v(): u64 }` | structs may only contain plain fields |
583
+ | enum initializers | `export enum E { A = 1, B = 2 }` | value enum members are numbered 0, 1, 2… in order; leave out initializers |
584
+ | nested `function` declarations | `function inner(x: u64): u64 { return x; }` (in a body) | FunctionDeclaration is not supported in TypeSOL |
585
+ | recursion | `function a(x: u64): u64 { return x === 0n ? 0n : a(x - 1n); }` | recursion is not supported: a -> a |
586
+ | helpers without a return type | `function h(x: u64) { return x; }` | helper functions need an explicit return type (void, an integer, boolean, Pubkey or a struct) |
587
+ | namespaces | `namespace N { export const x = 1n; }` | namespaces are not supported: use separate files and import from them |
588
+ | npm and Node.js imports | `import { x } from "lodash";` | only imports from "typesol" and relative TypeSOL files ("./math") are allowed, got "lodash" |
589
+ | default and namespace imports | `import * as ts from "typesol";` | use named imports: import { ... } from "typesol" |
590
+ | `console` | `console.log("x");` | 'console' does not exist in a Solana program … hint: a program writes logs with log("…") from "typesol" |
591
+ | `Math` | `const m = Math.max(1, 2);` | unsupported call: Math.max; use max(a, b) |
592
+ | `BigInt` | `b.value = BigInt(5);` | unsupported call: BigInt; use u64(x) or another integer cast |
593
+ | `Date` | `const d = Date.now();` | unsupported call: Date.now; use now() (the Clock's unix timestamp) |
594
+ | `JSON` | `log(JSON.stringify(n));` | unsupported call: JSON.stringify; use log(…) with the values |
595
+ | string `.length` | `const l = t.length;` | use byteLength(s) for strings; .length is available on arrays, Vecs and remainingAccounts() |
596
+ | string methods | `const c = t.slice(0, 1);` | unsupported call: t.slice |
597
+ | `as` conversions | `b.value = x as u64;` (`x: u8`) | this is a u8, not a u64: \`as\` does not convert (use u64(x) and the like for integers) |
598
+ | mixed integer widths | `b.value = b.value + x;` (`x: u8`) | operands have different types: u64 and u8; convert with u64(...) etc. |
599
+ | unary minus on unsigned | `b.value = -n;` | unary minus needs a signed integer (i8 … i128) |
600
+ | operators on `f64` | `b.value = r.x + r.x;` (`r.x: f64`) | + on an f64 is not supported: an f64 is held as its IEEE 754 bits and there is no float arithmetic (this would compute on the bits); compute in integers and make the result with f64FromBits(bits), or take an f64's bits with f64Bits(x) |
601
+ | `===` on `f64` | `if (r.x === r.y) {}` (`f64` fields) | === on an f64 is not supported: an f64 is held as its IEEE 754 bits, and equal bits are not equal numbers (NaN would equal itself, 0 would not equal -0); to compare the bits, write f64Bits(a) === f64Bits(b) |
602
+ | an `f64` as an integer | `b.value = r.x;` (`r.x: f64`) | an f64 is not an integer, so it is not converted to u64: it is held as its IEEE 754 bits, and the integer would be those bits; to use the bits, write f64Bits(x) |
603
+ | an `f64` as text | ``log(`${r.x}`);`` (`r.x: f64`) | an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x) |
604
+ | `?.` on a non-optional value | `const v = b?.value;` | ?. works on optional accounts and Option<struct> values (other values are never null) |
605
+ | `let` struct references | `let q = b.home;` | bind struct references with const |
606
+ | nested destructuring | `const { home: { x } } = b;` | nested destructuring is not supported; destructure in two steps |
607
+ | rest in destructuring | `const { value, ...rest } = b;` | ...rest is not supported in destructuring |
608
+ | defaults in destructuring | `const { value = 3n } = b;` | default values are not supported in destructuring |
609
+ | array destructuring | `const [p, q] = [1n, 2n];` | array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program) |
610
+ | `switch` on strings | `switch (t) { case "a": break; }` | switch works on integers and enums |
611
+ | non-constant `case` labels | `case b.value:` | case labels must be literals, constants or enum members |
612
+ | writing a helper's parameter | `function h(p: Point): void { p.x = 1n; }` | helper parameters are read-only: declare p as Inout<T> to change the caller's value in place, or copy it into a local first |
613
+ | `Vec` locals | `const v: Vec<u64> = fixedVec([]);` | local type must be an integer, boolean, Pubkey, enum, option or string |
614
+ | an unused proof or signature check | `merkleVerify(leaf, proof, root);` | the result of merkleVerify is discarded, so nothing is checked: it returns whether the proof holds; write require(merkleVerify(…), error) |
615
+ | a proof check in an empty `if` | `if (merkleVerify(leaf, proof, root)) {}` | the result of merkleVerify is not acted on: the if around it has an empty body, so nothing is checked: it returns whether the proof holds; write require(merkleVerify(…), error) |
616
+ | a proof check kept in a local never read | `const ok = merkleVerify(leaf, proof, root);` (`ok` unused) | the result of merkleVerify is never read (ok is not used), so nothing is checked: it returns whether the proof holds; write require(merkleVerify(…), error) |
617
+ | a `@code` tag outside a doc comment | `export enum E { A = "a", /* @code 6100 */ B = "b" }` | this @code tag is not read: only a doc comment (/** … */) is, not a /* … */ comment; write /** @code … */ above B |
618
+ | a `@code` tag after other code on its line | `export enum E { A = "a", /** @code 6100 */ B = "b" }` | this @code tag is not read: other code comes before it on its line; put /** @code … */ on its own line above B |
619
+
620
+ **Next:** [Accounts](language-accounts.md): account parameters and the checks they emit.