@typesol/cli 0.49.0 → 0.51.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 +541 -0
- package/NOTICE +9 -0
- package/README.md +34 -15
- package/SECURITY.md +6 -3
- package/dist/cli.js +36 -5
- package/dist/compiler/analyze.d.ts +10 -1
- package/dist/compiler/analyze.js +234 -20
- package/dist/compiler/diagnostics.d.ts +4 -0
- package/dist/compiler/diagnostics.js +5 -1
- package/dist/compiler/emit/base.d.ts +35 -4
- package/dist/compiler/emit/base.js +46 -4
- package/dist/compiler/emit/borsh.js +8 -8
- package/dist/compiler/emit/calls.d.ts +6 -0
- package/dist/compiler/emit/calls.js +98 -18
- package/dist/compiler/emit/cpi-core.d.ts +3 -0
- package/dist/compiler/emit/cpi-core.js +11 -5
- package/dist/compiler/emit/cpi.js +6 -4
- package/dist/compiler/emit/create.js +9 -9
- package/dist/compiler/emit/expressions.d.ts +9 -1
- package/dist/compiler/emit/expressions.js +77 -0
- package/dist/compiler/emit/function.d.ts +2 -0
- package/dist/compiler/emit/function.js +71 -15
- package/dist/compiler/emit/outline.d.ts +35 -0
- package/dist/compiler/emit/outline.js +547 -0
- package/dist/compiler/emit/program.js +19 -4
- package/dist/compiler/emit/rbtree.js +1 -1
- package/dist/compiler/emit/shared.d.ts +69 -4
- package/dist/compiler/emit/shared.js +44 -9
- package/dist/compiler/emit/statements.d.ts +36 -2
- package/dist/compiler/emit/statements.js +332 -29
- package/dist/compiler/emit/storage.d.ts +16 -0
- package/dist/compiler/emit/storage.js +134 -13
- package/dist/compiler/emit/views.js +1 -1
- package/dist/compiler/hints.d.ts +1 -1
- package/dist/compiler/hints.js +9 -1
- package/dist/compiler/idl.js +1 -1
- package/dist/compiler/index.d.ts +30 -2
- package/dist/compiler/index.js +94 -16
- package/dist/compiler/model.d.ts +13 -1
- package/dist/compiler/stack.d.ts +71 -0
- package/dist/compiler/stack.js +309 -0
- package/dist/compiler/toolchain.d.ts +87 -5
- package/dist/compiler/toolchain.js +384 -19
- package/dist/keys.d.ts +12 -1
- package/dist/keys.js +57 -7
- package/dist/workspace.d.ts +9 -0
- package/dist/workspace.js +91 -16
- package/docker/deps/0.50.0.lock.json +1206 -0
- package/docker/deps/0.51.0.lock.json +1206 -0
- package/docs/architecture.md +1 -1
- package/docs/audit.md +16 -13
- package/docs/case-study-escrow.md +1 -1
- package/docs/case-study-jito-mev.md +14 -14
- package/docs/case-study-marginfi.md +127 -127
- package/docs/case-study-multisig.md +16 -4
- package/docs/case-study-raydium-clmm.md +44 -28
- package/docs/case-study-raydium-cp-swap.md +18 -18
- package/docs/cli.md +5 -4
- package/docs/glossary.md +2 -1
- package/docs/language-accounts.md +16 -10
- package/docs/language-basics.md +29 -2
- package/docs/language-builtins.md +4 -2
- package/docs/language-cpi.md +34 -0
- package/docs/language-native.md +50 -4
- package/docs/language-pdas.md +6 -2
- package/docs/language-statements.md +103 -12
- package/docs/language-types.md +93 -8
- package/docs/runtime.md +20 -3
- package/docs/security-model.md +6 -3
- package/docs/stability.md +10 -5
- package/docs/testing.md +6 -2
- package/docs/troubleshooting.md +45 -1
- package/lib/typesol.d.ts +25 -3
- package/llms-full.txt +403 -54
- package/package.json +1 -1
- package/releases/0.49.0.json +857 -0
- package/releases/0.50.0.json +874 -0
- package/runtime/typesol_builtins.c +47 -2
- package/runtime/typesol_rt.h +254 -54
package/docs/cli.md
CHANGED
|
@@ -7,10 +7,10 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
|
|
|
7
7
|
| Command | What it does |
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow] [--no-agent-files]` | Create a project ([below](#typesol-init)). |
|
|
10
|
-
| `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name. |
|
|
10
|
+
| `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name, and to write through a symbolic link inside the project (a linked `programs/` or `tests/`, or a link where a new file goes). |
|
|
11
11
|
| `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools (and a `toolchain` row: the tested ones, or untested with both versions), the Solana CLI, Docker (optional: only `--docker` builds need it; it says when they run emulated), its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. The last line says what is ready (building and testing, or also deploying) and what the warnings concern. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
|
|
12
|
-
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. `--docker` builds in the pinned container instead ([below](#build---docker-and-verify---docker)). |
|
|
13
|
-
| `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--docker …] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
|
|
12
|
+
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--stack-auto on\|off] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). Each source's sha256 is that of the bytes the compiler read, and the build fails without a manifest when a source or the runtime changes while it runs (an editor saving a file mid-build), so a manifest never pairs a binary with sources that did not make it. A program that does not fit the stack is laid out another way when it can ([Memory](language-basics.md#memory-stack-and-heap)): each step is printed as a `note:` and recorded in `<name>.build.json` under `stack` (`actions`, in order: `scope`, `noinline` or `heap`, with what each was for, and `frames`, the frames of the functions that did not fit before and after); a program that fits has no `stack` field. `--stack-auto off` makes such a build fail instead, as `const STACK_AUTO = false` in the program does (with `--docker`, write the constant). With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. First builds may run at once (several programs, or several processes): the keypair is created exclusively (a process that loses the race uses the winner's key) and `typesol.json` is updated one process at a time and replaced whole, so each address is kept. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. `--docker` builds in the pinned container instead ([below](#build---docker-and-verify---docker)). |
|
|
13
|
+
| `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--stack-auto on\|off] [--toolchain-strict] [--docker …] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
|
|
14
14
|
| `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`, always (a missing file or unreadable `--files` input is a diagnostic too, exit 1 or 2); `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
|
|
15
15
|
| `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
|
|
16
16
|
| `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
|
|
@@ -47,7 +47,8 @@ process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `war
|
|
|
47
47
|
`<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the
|
|
48
48
|
program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above
|
|
49
49
|
rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). `init` refuses to
|
|
50
|
-
overwrite files
|
|
50
|
+
overwrite files, and to write through a symbolic link inside `<dir>` (a linked `.cursor/`, say, whose files would
|
|
51
|
+
land wherever it points; `<dir>` itself may be a link). It warns, with the install commands, when the platform-tools that building needs are missing, and
|
|
51
52
|
says whether the Agave CLI is missing or only its platform-tools (on Linux arm64, where there is no Agave CLI, the
|
|
52
53
|
commands that set up the platform-tools' `linux-aarch64` package).
|
|
53
54
|
|
package/docs/glossary.md
CHANGED
|
@@ -57,7 +57,8 @@ bytes. See [seeds](language-pdas.md#seeds).
|
|
|
57
57
|
## Bump
|
|
58
58
|
|
|
59
59
|
The one byte added to a PDA's seeds so that the derived address has no private key. The canonical bump is the
|
|
60
|
-
highest that works; it is found by trying 255, 254, …
|
|
60
|
+
highest that works; it is found by trying 255, 254, … down to 1, as Solana's `find_program_address` does (bump 0 is
|
|
61
|
+
never tried), and is usually stored in the account. See [PDAs](language-pdas.md).
|
|
61
62
|
|
|
62
63
|
## Signer
|
|
63
64
|
|
|
@@ -197,18 +197,21 @@ export function remove(owner: Mut<Signer>, log: HasOne<Mut<Log>, "owner">): void
|
|
|
197
197
|
}
|
|
198
198
|
```
|
|
199
199
|
|
|
200
|
-
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
200
|
+
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable account)
|
|
201
|
+
and its data is zeroed (by the memset syscall when the account's type takes 64 bytes or more, by stores below). The
|
|
202
|
+
account is not used after it in the function, except its `key` (compile errors, or 2040 at run time in a helper
|
|
203
|
+
given one account twice). `CloseTo<A, "dest">` does the same when the instruction succeeds
|
|
204
|
+
([constraints](#constraints)).
|
|
204
205
|
- Who may call them: `HasOne` above lets only the log's owner close it (the lamports of a closed account are value)
|
|
205
206
|
or resize it. Without that check anyone could pay to grow, or shrink, another user's account.
|
|
206
207
|
- `realloc(account, newSize, payer)` on a `Mut<Struct>`: growing charges the payer the extra rent (at most 10 KiB per
|
|
207
|
-
instruction, 3016); shrinking keeps the lamports in the account; never below the struct.
|
|
208
|
-
|
|
208
|
+
instruction, 3016); shrinking keeps the lamports in the account; never below the struct (3016). For a `@layout borsh`
|
|
209
|
+
struct that is its discriminator and smallest Borsh form (an empty `FixedString<64>` takes 4 bytes, not 68), the size
|
|
210
|
+
its load accepts; the value written back when the instruction returns must still fit (3004). Refused on a struct
|
|
211
|
+
with a growable `Vec` (its push / pop / clear size the account).
|
|
209
212
|
- `resizeAccount(account, newSize)` on a `Mut<AccountInfo>` of this program is Rust's `AccountInfo::resize`: the
|
|
210
|
-
length only, new bytes zeroed
|
|
211
|
-
(3016).
|
|
213
|
+
length only, new bytes zeroed (64 or more by the memset syscall, as `realloc` zeroes them too), no rent moved (fund
|
|
214
|
+
it first: `rentExempt(newSize)`), at most 10 KiB of growth (3016).
|
|
212
215
|
- An account grows at most 10 KiB per instruction, counted from its length when the instruction started (Solana's
|
|
213
216
|
limit): realloc again in the next instruction.
|
|
214
217
|
- `account.lamports` can be read on any account and written on a `Mut` one.
|
|
@@ -271,7 +274,8 @@ the body, in Anchor's order, and recorded in the IDL (`relations`, `pda`, `addre
|
|
|
271
274
|
among its types, not its accounts (an error named on such an `Owner` is not used: the load fails with 3007). Such a
|
|
272
275
|
struct may carry a shorter discriminator, `/** @discriminator 0x01 */` (1 to 8 bytes, as Anchor's
|
|
273
276
|
`discriminator = &[1]`; Solend's reserve), its fields then starting right after it; this program's own accounts
|
|
274
|
-
keep 8.
|
|
277
|
+
keep 8. A `@layout borsh` struct's Borsh bytes start there too, and the account must hold the discriminator and the
|
|
278
|
+
struct's smallest Borsh form (3003).
|
|
275
279
|
- `Address<InstructionsSysvar, "Sysvar1nstructions1111111111111111111111111">` checks the address as Anchor's
|
|
276
280
|
`address = sysvar::instructions::ID` on an `UncheckedAccount` does (2012, with the constraints).
|
|
277
281
|
|
|
@@ -304,7 +308,9 @@ are compared too ([native programs](language-native.md#inout-places-that-may-be-
|
|
|
304
308
|
|
|
305
309
|
At most 32 accounts per instruction; more is refused with 5113. `export const MAX_ACCOUNTS = 128n` (up to 255; Anchor
|
|
306
310
|
takes what the runtime allows) raises it for programs that take many remaining accounts. The CPI scratch lists are
|
|
307
|
-
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before.
|
|
311
|
+
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before. 255 is also
|
|
312
|
+
the runtime's limit: an instruction naming more accounts (repeats count) fails with MaxAccountsExceeded before any
|
|
313
|
+
program runs.
|
|
308
314
|
|
|
309
315
|
## Optional accounts
|
|
310
316
|
|
package/docs/language-basics.md
CHANGED
|
@@ -271,9 +271,12 @@ export function setup(config: Mut<Config>): void {
|
|
|
271
271
|
- Constants are inlined where they are used, and may be seeds; when a seed is a constant, the IDL records its value.
|
|
272
272
|
- A constant with an integer type is computed in that type, every step checked: `const X: u64 = 1n - 2n + 5n` is an
|
|
273
273
|
error (`1n - 2n is -1, which does not fit in u64`), and `const M: u8 = ~1n` is 254 (`~` within the width).
|
|
274
|
-
Division by zero, a negative exponent or a shift past the width are compile errors
|
|
274
|
+
Division by zero, a negative exponent or a shift past the width are compile errors, and so is a signed type's
|
|
275
|
+
minimum divided by or reduced modulo -1 (`const X: i8 = -128n % -1n`: the quotient does not fit, and at run time
|
|
276
|
+
that remainder fails with 5100 too), where JavaScript's bigint gives 0.
|
|
275
277
|
- An untyped integer constant is inlined as its value and takes the type of the place it is used in, as a literal
|
|
276
278
|
does: `const FEE = 30n` stores into a `u16` field, and `const FEE = 300n` into a `u8` one is `300 does not fit in u8`.
|
|
279
|
+
It is computed as a JavaScript bigint, without a width: `const R = -128n % -1n` is 0.
|
|
277
280
|
- Top-level `let` and `var` are refused: `top-level variables must be const literals`. A program has no global state
|
|
278
281
|
other than its accounts.
|
|
279
282
|
- A few names configure the compiler: `HEAP_SIZE_KIB` ([below](#memory-stack-and-heap)), `MAX_ACCOUNTS`
|
|
@@ -353,10 +356,34 @@ From the source alone, a build writes:
|
|
|
353
356
|
## Memory: stack and heap
|
|
354
357
|
|
|
355
358
|
A program runs with a 4 KiB stack frame per function and a heap of 32 KiB. Locals live on the stack: a list local
|
|
356
|
-
holds at most 2 KiB, and a frame that overflows is a compile error that names its biggest locals.
|
|
359
|
+
holds at most 2 KiB, and a frame that overflows is a compile error that names its biggest locals. Under SBPF v1 and v2
|
|
360
|
+
(`--sbpf v1` / `v2`) each function's frame is sized to fit, so the 4 KiB limit is lifted, but one frame holds at most
|
|
361
|
+
32,767 bytes and all the frames of a call path share 256 KiB; the build refuses a program past either
|
|
362
|
+
([troubleshooting](troubleshooting.md#-needs-n-bytes-of-stack-sbpf-v1-allows-one-function-at-most-32767)). Strings built at run
|
|
357
363
|
time and a few other values live on the heap ([heap values](language-types.md#heap-values)), which is never freed
|
|
358
364
|
during an instruction.
|
|
359
365
|
|
|
366
|
+
A program that does not fit the stack as written is laid out another way by the build before it gives up. It does
|
|
367
|
+
nothing to a program that fits, which builds to the same bytes as before. In order, measuring with clang after each
|
|
368
|
+
step, until the program fits:
|
|
369
|
+
|
|
370
|
+
1. each statement of the function that does not fit, and of the helpers inlined into it, gets a C block of its own, so
|
|
371
|
+
clang can give the temporaries of different statements one slot (a struct literal's, a helper result's); nothing
|
|
372
|
+
else changes;
|
|
373
|
+
2. helpers inlined into it are kept out of line, as if each were [`@noinline`](language-statements.md#inline-and-noinline),
|
|
374
|
+
largest frame first (about 10 compute units per call), except a helper that takes a function or is marked
|
|
375
|
+
`/** @inline */`; nothing else changes;
|
|
376
|
+
3. in an instruction, its largest list and struct locals and the struct results of helpers it holds are kept on the
|
|
377
|
+
heap, as if each were [`@heap`](language-types.md#heap-values) (about 17 compute units each, and their bytes of
|
|
378
|
+
heap), as long as the instruction's heap locals together fit in the heap; never a local marked `/** @stack */`.
|
|
379
|
+
|
|
380
|
+
Each step is printed as a note (`note: instruction f did not fit the stack (4864 bytes; SBPF v0 allows 4096); now 64
|
|
381
|
+
bytes`, `note: helper settle() kept out of line, for instruction trade …`) and recorded in `<name>.build.json` as
|
|
382
|
+
`stack.actions` ([cli.md](cli.md)). The steps depend only on the sources and clang's measurements, so a
|
|
383
|
+
rebuild (`typesol verify`, `--docker`) takes the same ones and gives the same bytes. When none of them is enough, the
|
|
384
|
+
build fails with the error it would have given, and a line saying what it tried. `const STACK_AUTO = false` in the
|
|
385
|
+
program (or `typesol build --stack-auto off` for one build) turns this off: the program then fails to build instead.
|
|
386
|
+
|
|
360
387
|
`const HEAP_SIZE_KIB = 64n` (32 to 256) lets the program use a bigger heap; the client must then add a ComputeBudget
|
|
361
388
|
`requestHeapFrame` instruction with that size to the transaction.
|
|
362
389
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<!-- Generated by scripts/language-builtins.ts from lib/typesol.d.ts; do not edit by hand. -->
|
|
4
4
|
|
|
5
|
-
Every name `"typesol"` exports (
|
|
5
|
+
Every name `"typesol"` exports (222 names, 235 declarations), grouped, with its declaration and the first sentence of its doc
|
|
6
6
|
comment in `lib/typesol.d.ts`. Each group links to the part of the [language guide](language.md) that explains it;
|
|
7
7
|
your editor shows the full doc comment on hover. Methods of account and program types (`systemProgram.transfer`,
|
|
8
8
|
`acct.create`, …) are described with their types in the guide.
|
|
@@ -140,7 +140,7 @@ Explained in [Accounts: Closing and resizing](language-accounts.md#closing-and-r
|
|
|
140
140
|
| --- | --- | --- |
|
|
141
141
|
| `close` | `function close(account: AccountMeta, destination: AccountMeta): void` | Close a program-owned account: move all lamports to `destination` and wipe it. |
|
|
142
142
|
| `realloc` | `function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void` | Resize an account of this program (Anchor `realloc`, struct accounts only): growing charges `payer` the extra rent (never the account's own lamports, which may be deposits); shrinking keeps every lamport in the account — move freed rent out yourself if your program allows it. |
|
|
143
|
-
| `resizeAccount` | `function resizeAccount(account: RemainingAccount \| Mut<AccountInfo>, newSize: u64): void` | Resize a `Mut<AccountInfo>` or a remaining account of this program to `newSize` bytes (Rust's `AccountInfo::resize` / `realloc(newSize, true)`): the data length only, the new bytes zeroed. |
|
|
143
|
+
| `resizeAccount` | `function resizeAccount(account: RemainingAccount \| Mut<AccountInfo>, newSize: u64): void` | Resize a `Mut<AccountInfo>` or a remaining account of this program to `newSize` bytes (Rust's `AccountInfo::resize` / `realloc(newSize, true)`): the data length only, the new bytes zeroed (64 or more by the memset syscall). |
|
|
144
144
|
|
|
145
145
|
## Accounts created by hand
|
|
146
146
|
|
|
@@ -220,6 +220,7 @@ Explained in [Calling other programs: invoke](language-cpi.md#invoke).
|
|
|
220
220
|
| `sighash` | `function sighash(name: string): Bytes` | The 8-byte Anchor instruction discriminator for `name` (sha256("global:<snake_case name>")[..8]). |
|
|
221
221
|
| `hex` | `function hex(literal: string): Bytes` | Bytes from a hex string literal, e.g. hex("0a0b"). |
|
|
222
222
|
| `returnData` | `function returnData<T>(program: AccountMeta): T` | Read the return data the last invoke() left behind, checking it came from `program` and has exactly the size of T: `const n = returnData<u64>(counterProgram)`. |
|
|
223
|
+
| `getReturnData` | `function getReturnData(): [program: Pubkey, data: InstructionBytes]` | The return data as the runtime holds it, of any length and from any program (Rust's `get_return_data()`), for a port that checks it itself: `const [program, data] = getReturnData()`. |
|
|
223
224
|
| `invokeInstruction` | `function invokeInstruction(programId: Pubkey, accounts: IndexedList<InstructionAccountMeta>, data: IndexedList<u8>, infos: RemainingAccounts \| RemainingSlice, signerSeeds?: Seed[] \| SignerSeeds \| (Seed[] \| SignerSeeds)[]): void` | A CPI decided at run time, e.g. one stored in account data (Rust's `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`). |
|
|
224
225
|
| `InstructionAccountMeta` | `interface InstructionAccountMeta` | One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. |
|
|
225
226
|
| `programAt` | `function programAt<P>(account: RemainingAccount \| AccountInfo): P` | A remaining account (or an AccountInfo parameter) as a typed program: `const stake = programAt<StakeProgram>(rest.get(12n))`, then `stake.split(…)`, `token.mintTo(…)`, `system.transfer(…)` as on a declared program parameter, and passed to helpers that take that program type. |
|
|
@@ -404,6 +405,7 @@ Explained in [Porting a native program (advanced)](language-native.md).
|
|
|
404
405
|
| `closeRaw` | `function closeRaw(account: RemainingAccount \| Mut<AccountInfo>, receiver: RemainingAccount \| Mut<AccountInfo>): void` | Close an account of this program as a native program does it by hand (Phoenix's Tombstone), in this order: `receiver.lamports += account.lamports`, `account.lamports = 0`, the owner set to the System Program, the data length set to 0 (`realloc(0, false)`: the bytes are not zeroed, the runtime drops them with the length). |
|
|
405
406
|
| `assignOwner` | `function assignOwner(account: RemainingAccount \| Mut<AccountInfo>, owner: Pubkey): void` | Set an account's owner in place (Rust's `AccountInfo::assign`). |
|
|
406
407
|
| `zeroData` | `function zeroData(account: RemainingAccount \| Mut<AccountInfo>, offset: u64, length: u64): void` | Zero `length` bytes of an account's data from `offset`, as a native program's `for b in data[offset..offset + length].iter_mut() { *b = 0; }` (a memset): the memset syscall, about constant compute units whatever the length. |
|
|
408
|
+
| `copyData` | `function copyData(account: RemainingAccount \| Mut<AccountInfo>, from: u64, to: u64, length: u64): void` | Copy `length` bytes of an account's data from offset `from` to offset `to`, as a native program's `data.copy_within(from..from + length, to)` (or a struct copied out of the account and written back at another offset): the memmove syscall, about constant compute units whatever the length; the ranges may overlap. |
|
|
407
409
|
| `setReturnData` | `function setReturnData(bytes: IndexedList<u8>): void` | Set this instruction's return data to `bytes` as they are (Rust's `set_return_data(&bytes)`): a list of u8 such as a local `FixedVec<u8, N>`, a Vec or FixedVec in account data, or the instruction data or a slice of it. |
|
|
408
410
|
| `panic` | `function panic(message?: string \| null, location?: string): never` | Stop the program as a Rust `panic!` / `unwrap()` on `None` / `unreachable!()` does: the message is logged and the instruction fails with ProgramFailedToComplete (no error code). |
|
|
409
411
|
| `panicsAt` | `function panicsAt<T>(location: string, value: T): T` | `value`, with its checked arithmetic panicking as Rust's overflow checks do at `location` ("file:line:column", where the original's expression is): `panicsAt("src/quantities.rs:233:1", a + b)` logs "attempt to add with overflow" there (also "attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow", "attempt to shift left / right with overflow" for a shift amount past the width), as `panic` logs (see `PANIC_STYLE`), instead of failing with 5100 / 5101. |
|
package/docs/language-cpi.md
CHANGED
|
@@ -319,6 +319,40 @@ Pubkeys, unit enums and arrays is read as its bytes (booleans and enums checked)
|
|
|
319
319
|
Vecs is declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106. The
|
|
320
320
|
type argument is required.
|
|
321
321
|
|
|
322
|
+
Return data of any length, checked by the program itself (Rust's `get_return_data()`, as a native program reads a
|
|
323
|
+
reply of several records), is `getReturnData()`:
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
import { getReturnData, instructionData, invoke, log, remainingAccounts, require, u8 } from "typesol";
|
|
327
|
+
|
|
328
|
+
export enum MatchError {
|
|
329
|
+
/** @code 0 */
|
|
330
|
+
NoReply = "NoReply",
|
|
331
|
+
BadReply = "BadReply",
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** @fallback */
|
|
335
|
+
export function entry(): void {
|
|
336
|
+
const matcher = remainingAccounts().get(0n);
|
|
337
|
+
const data = instructionData();
|
|
338
|
+
const legs = data.readU64(0n);
|
|
339
|
+
invoke(matcher, [], [u8(1n), legs]);
|
|
340
|
+
const [from, reply] = getReturnData();
|
|
341
|
+
// Rust's None: no return data (the runtime keeps no empty return data); `from` is then all zeros.
|
|
342
|
+
require(reply.length > 0n, MatchError.NoReply);
|
|
343
|
+
require(from === matcher.key && reply.length === legs * 64n, MatchError.BadReply);
|
|
344
|
+
log(reply.readU64(8n));
|
|
345
|
+
}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
- `from` is the program that set the return data (a Pubkey); `reply` its bytes, up to the runtime's 1,024, with the
|
|
349
|
+
methods of instruction data (`length`, `get`, `readU8` … `readU128`, `readPubkey`, `slice`; 5104 past the end).
|
|
350
|
+
- Nothing is checked and nothing fails: the program, the length and the contents are the caller's to check, with its
|
|
351
|
+
own errors. It reads whatever the runtime holds: the last CPI's callee's return data, or what this instruction set
|
|
352
|
+
with `setReturnData` after it.
|
|
353
|
+
- Bound with `const [program, data] = …` where it is called (either name may be left out: `const [, data]`). The bytes
|
|
354
|
+
are copied into 1 KiB of the calling function's stack frame.
|
|
355
|
+
|
|
322
356
|
## invokeInstruction
|
|
323
357
|
|
|
324
358
|
A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
|
package/docs/language-native.md
CHANGED
|
@@ -215,6 +215,16 @@ A native account whose parts start where its header says (Phoenix's market at by
|
|
|
215
215
|
after a helper that may close or resize one it is given: its bounds were checked against the old length, so it is a
|
|
216
216
|
compile error saying to take the view again.
|
|
217
217
|
|
|
218
|
+
### Struct copies between views that overlap
|
|
219
|
+
|
|
220
|
+
Two views of one account at run-time offsets (`loadRawAt`, `loadRawMutAt`, an account passed twice under
|
|
221
|
+
`NATIVE_ACCOUNT_WRITES`) can overlap, and `d.v = s.v` then copies between overlapping bytes. The destination ends with
|
|
222
|
+
the source's old bytes, in either direction and at any size, as Rust's `copy_within` or a struct copied out and
|
|
223
|
+
written back leaves it: below 80 bytes every byte is loaded before any is stored (a load and then a store per 8
|
|
224
|
+
bytes), from 80 bytes the memmove syscall copies them. A copy through a local (`const c: T = s.v; d.v = c;`) and
|
|
225
|
+
`copyData` give the same bytes
|
|
226
|
+
([`test/language/bulk-copies.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/bulk-copies.test.ts)).
|
|
227
|
+
|
|
218
228
|
## lib-sokoban's red-black tree
|
|
219
229
|
|
|
220
230
|
```ts
|
|
@@ -368,9 +378,19 @@ On remaining accounts and `AccountInfo` parameters:
|
|
|
368
378
|
the account's owner: check that it is this program's first (the runtime would fail the instruction after it returns,
|
|
369
379
|
having changed another program's account). The length does not change, so views made before stay valid and read the
|
|
370
380
|
zeros.
|
|
371
|
-
- `
|
|
372
|
-
|
|
373
|
-
|
|
381
|
+
- `copyData(account, from, to, length)` copies `length` bytes of the data from offset `from` to offset `to`, as a
|
|
382
|
+
native program's `data.copy_within(from..from + length, to)` or a struct copied out and written back at another
|
|
383
|
+
offset (a memcpy in Rust): the memmove syscall from 32 bytes, about constant compute units whatever the length (a
|
|
384
|
+
whole-struct assignment `a.p = b.p` between views uses it too, from 80 bytes: [overlapping
|
|
385
|
+
views](#struct-copies-between-views-that-overlap)). The ranges may overlap. A range past the end of the data fails
|
|
386
|
+
with 3003 and copies nothing; without `NATIVE_ACCOUNT_WRITES` the account must be writable (3006). Like `zeroData`
|
|
387
|
+
it does not check the owner, and views made before stay valid and read the copied bytes (Percolator v16's InitMarket
|
|
388
|
+
copies asset 0's 424-byte oracle profile into every slot of the market this way;
|
|
389
|
+
[`test/language/native-copy-data.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/native-copy-data.test.ts)).
|
|
390
|
+
- `resizeAccount(account, size)` also takes a remaining account (`realloc(size, true)`: new bytes zeroed, 64 or more
|
|
391
|
+
by the memset syscall as Rust's realloc zeroes them, fewer by stores; at most 10 KiB past the size it had when the
|
|
392
|
+
instruction started, 3016). That size is the one the entrypoint records in the account's record, as solana_program
|
|
393
|
+
1.14's does, only in programs that resize a remaining account.
|
|
374
394
|
- A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node or a struct read
|
|
375
395
|
through one) is a compile error to use after it: its bounds were checked against the old length, so take the view
|
|
376
396
|
again.
|
|
@@ -380,6 +400,7 @@ On remaining accounts and `AccountInfo` parameters:
|
|
|
380
400
|
(`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`), and plain
|
|
381
401
|
`AccountInfo` parameters are enough.
|
|
382
402
|
|
|
403
|
+
|
|
383
404
|
## Errors and panics as the original reports them
|
|
384
405
|
|
|
385
406
|
```ts
|
|
@@ -423,6 +444,30 @@ export function entry(): void {
|
|
|
423
444
|
location)` log one line, `panicked at <location>:` and the message after a newline, and then abort ("SBF program
|
|
424
445
|
panicked"), as that panic handler does: `panicked at src/wide_math.rs:1554:30:\nmul_div_floor_u128: a*b overflow`.
|
|
425
446
|
As under "solana-1.14", a message is required and `PANIC_ON_OVERFLOW`'s panics abort.
|
|
447
|
+
- **Panics as pinocchio's entrypoint writes them.** `export const PANIC_STYLE = "pinocchio"` (a program built with
|
|
448
|
+
pinocchio's `entrypoint!`, whose `default_panic_handler!` hook runs under std: Percolator v16) makes `panic(message,
|
|
449
|
+
location)` log two lines, the location's file exactly as Rust records it and then `** PANICKED **`, and abort ("SBF
|
|
450
|
+
program panicked"):
|
|
451
|
+
|
|
452
|
+
```
|
|
453
|
+
Program log: src/v16.rs
|
|
454
|
+
Program log: ** PANICKED **
|
|
455
|
+
Program <id> failed: SBF program panicked
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
- The file is `Location::file()` verbatim: the path rustc was given, which cargo makes relative to the crate
|
|
459
|
+
(`src/v16.rs`, `src/account_info.rs` inside solana-program) and which is the toolchain's absolute path for a panic
|
|
460
|
+
inside the standard library that is not reported at its caller (Percolator v16's binary holds
|
|
461
|
+
`/home/runner/work/platform-tools/platform-tools/out/rust/library/alloc/src/raw_vec/mod.rs`). Give it as the
|
|
462
|
+
location, alone or with its line and column (`"src/v16.rs:812:9"`, logged as `src/v16.rs`), so the port's source
|
|
463
|
+
keeps the original's place. Index, `unwrap`, `RefCell::borrow_mut` and `Vec::with_capacity`'s capacity panics are
|
|
464
|
+
reported at their caller (`#[track_caller]`), so their file is the caller's.
|
|
465
|
+
- No message is logged (the hook ignores it): the message may be `null` or a note for the reader. Without a
|
|
466
|
+
location this source file's name is logged.
|
|
467
|
+
- `panicsAt(location, expression)` logs its location's file the same way. `PANIC_ON_OVERFLOW` is refused with this
|
|
468
|
+
style: its panics have no file; wrap the arithmetic in `panicsAt`.
|
|
469
|
+
- Every panic site calls one shared helper (the two log calls and the abort), so a port with many panic sites stays
|
|
470
|
+
small.
|
|
426
471
|
- **Overflow panics with Rust's message and location.** `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
|
|
427
472
|
checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
|
|
428
473
|
"attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with
|
|
@@ -438,7 +483,8 @@ export function entry(): void {
|
|
|
438
483
|
quantities.rs, wherever the addition is written): give the port a helper, `function addQuoteLots(a: u64, b: u64):
|
|
439
484
|
u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`.
|
|
440
485
|
- The bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks
|
|
441
|
-
them differently, or with other messages)
|
|
486
|
+
them differently, or with other messages): `panicsAt(LOC, a ** 2n)` fails with 5100 when the square overflows,
|
|
487
|
+
while an operator in `**`'s operands (`(a + b) ** 2n`) still panics at the location.
|
|
442
488
|
- [`test/language/rust-panics.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/rust-panics.test.ts) checks the lines against the Phoenix binary's own panics.
|
|
443
489
|
|
|
444
490
|
## Log lines as the original writes them
|
package/docs/language-pdas.md
CHANGED
|
@@ -56,7 +56,10 @@ A seed list is an array literal written where the seeds go. Each seed contribute
|
|
|
56
56
|
A seed is at most 32 bytes (`a seed can be at most 32 bytes`, when its length is known at compile time). A `string`
|
|
57
57
|
argument longer than that is only known at run time: `create`, `createIfNeeded`, `requirePda` and `Seeds<…>` then fail
|
|
58
58
|
with 2006, as for any other address that is not the PDA; check `byteLength(s) <= 32n` first to fail with an error of
|
|
59
|
-
your own.
|
|
59
|
+
your own. A list whose every seed has a length known at compile time (keys, integers, enums, string literals and
|
|
60
|
+
constants) cannot exceed the limits, so its derivation skips the run-time check of the seed lengths; a list with a
|
|
61
|
+
`string` value keeps it, and so do the account-creating calls (`create`, `createIfNeeded`, `createPda` and the token
|
|
62
|
+
creates) of any program that passes one of them such a list. Solana takes at
|
|
60
63
|
most 16 seeds per address, the bump included. A list the derivation adds the bump to (`create`, `requirePda`,
|
|
61
64
|
`findProgramAddress`) holds at most 15 entries (`at most 15 seeds: the bump the derivation adds makes 16, Solana's
|
|
62
65
|
limit`); a list that ends with its bump (signer seeds, `createProgramAddress`) holds 16: 15 seeds and the bump (`at
|
|
@@ -135,7 +138,8 @@ export function locate(book: Mut<Book>, owner: Pubkey, start: u64): void {
|
|
|
135
138
|
- `findProgramAddress(seeds, program)` is the canonical PDA of any program (Rust's
|
|
136
139
|
`Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id), and `findProgramAddressBump(seeds, program)` its
|
|
137
140
|
bump. `const [address, bump] = findProgramAddressWithBump(seeds, program)` gives both from one search (Rust's
|
|
138
|
-
`let (address, bump) = …`). Each search costs about 450 CU per bump tried
|
|
141
|
+
`let (address, bump) = …`). Each search costs about 450 CU per bump tried, and tries 255 down to 1 as Solana's
|
|
142
|
+
does: bump 0 is never tried.
|
|
139
143
|
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address`: the address for seeds that include the
|
|
140
144
|
bump, or `null` when they give none.
|
|
141
145
|
- `programId()` is this program's address.
|
|
@@ -10,8 +10,9 @@ In short, a function body may contain:
|
|
|
10
10
|
| --- | --- |
|
|
11
11
|
| `const`, `let` | one name each, with an initializer ([declarations](#declarations)) |
|
|
12
12
|
| assignment, `+=` … `>>=`, `++`, `--` | checked arithmetic ([types](language-types.md#integers)) |
|
|
13
|
+
| `\|\|=`, `&&=`, `??=` | [logical assignment](#logical-assignment): booleans, Options |
|
|
13
14
|
| `if` / `else`, `? :`, `&&`, `\|\|`, `!` | conditions are `boolean` |
|
|
14
|
-
| `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops) |
|
|
15
|
+
| `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops), labeled too (`outer: for …`) |
|
|
15
16
|
| `switch` | on integers, enums and a data enum's `kind` |
|
|
16
17
|
| `return` | |
|
|
17
18
|
| calls | helpers, closures, built-ins, account methods |
|
|
@@ -65,7 +66,39 @@ You can assign to a local, a field of a writable account (`Mut<T>`), a field of
|
|
|
65
66
|
read-only; copy the value into a local first`), and so are helper parameters (see [Inout](#inout-parameters)).
|
|
66
67
|
|
|
67
68
|
Compound assignments (`+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`) and `++` / `--` are
|
|
68
|
-
checked like the operators they stand for.
|
|
69
|
+
checked like the operators they stand for. All of them are statements: used as a value (`const y = x++`, `f(x += 1n)`)
|
|
70
|
+
they are refused (`x++ is a statement in TypeSOL, not a value: …`).
|
|
71
|
+
|
|
72
|
+
### Logical assignment
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { type Mut, type Option, type u64 } from "typesol";
|
|
76
|
+
|
|
77
|
+
export interface Prefs {
|
|
78
|
+
seen: boolean;
|
|
79
|
+
open: boolean;
|
|
80
|
+
limit: Option<u64>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function fallback(): u64 {
|
|
84
|
+
return 100n;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function touch(prefs: Mut<Prefs>, now: boolean): void {
|
|
88
|
+
prefs.seen ||= now; // written only when seen is false
|
|
89
|
+
prefs.open &&= now; // written only when open is true
|
|
90
|
+
prefs.limit ??= fallback(); // fallback() runs only when limit is empty
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- `x ||= v`, `x &&= v` and `x ??= v` work wherever `x = v` does (a local, a field of a writable account or of a local
|
|
95
|
+
struct, a list element's field), as JavaScript runs them: the place is found once, its value read, and only when it
|
|
96
|
+
decides so (false for `||=`, true for `&&=`, empty for `??=`) is `v` evaluated and written. Otherwise `v` does not
|
|
97
|
+
run and nothing is written.
|
|
98
|
+
- `||=` and `&&=` take booleans. On an integer, JavaScript would test for `0n`, which TypeSOL does not do implicitly:
|
|
99
|
+
`||= works on booleans; on u64 JavaScript would test for 0n: write if (…) x = …`.
|
|
100
|
+
- `??=` takes an `Option` (of an integer, boolean, `Pubkey`, struct or array; `acct.home ??= { x, y }` writes the
|
|
101
|
+
whole struct). On anything else it is refused (`??= needs an Option on the left (u64 is never null): …`).
|
|
69
102
|
|
|
70
103
|
### Copies and references
|
|
71
104
|
|
|
@@ -100,6 +133,10 @@ export function edit(shape: Mut<Shape>): void {
|
|
|
100
133
|
refused (`bind struct references with const`).
|
|
101
134
|
- **An annotation makes a copy.** `const p: Point = acct.home` (or `= { x, y }`) is a local struct of its own. Lists
|
|
102
135
|
likewise: `const ys: FixedVec<u64, 4> = acct.xs` is a copy.
|
|
136
|
+
- **A spread copies.** `{ ...p, x: 1n }` copies p's fields at its place in the literal, as `field: p.field` entries
|
|
137
|
+
would ([structs](language-types.md#spreads-in-struct-literals)). A field holding a struct, list or data enum must
|
|
138
|
+
be given after the spread (`pos: { ...p.pos }`): JavaScript would share that nested object between the two values,
|
|
139
|
+
which TypeSOL, copying, could not.
|
|
103
140
|
- **A reference cannot outlive what it names.** Replacing the referenced place (`book.bids.set(i, …)`, `pop()`,
|
|
104
141
|
`clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JavaScript would
|
|
105
142
|
keep the old object: `"q" still refers to a.home; replacing it here would change what "q" reads (in JS it keeps the
|
|
@@ -115,7 +152,8 @@ export function edit(shape: Mut<Shape>): void {
|
|
|
115
152
|
refused.
|
|
116
153
|
- **Evaluation order**: operands and arguments are read left to right, as in JavaScript, even when a later one changes
|
|
117
154
|
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).
|
|
155
|
+
callback writing it). Built-ins too: `log64(a.count, bump(a), 0n, 0n, 0n)` logs the count before the bump, and
|
|
156
|
+
`require(a.count === n, codeOf(a))` tests the count before a helper computing the error code runs.
|
|
119
157
|
- **Ternaries** run only the chosen branch: `const fee = vip ? 0n : 30n`. Between accounts too:
|
|
120
158
|
`const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or
|
|
121
159
|
`RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a
|
|
@@ -147,7 +185,12 @@ A condition (in `if`, `while`, `for`, `? :`, `&&`, `||`, `!`) must be a `boolean
|
|
|
147
185
|
truthiness: `if (amount)` is refused (`expected boolean, got u64`).
|
|
148
186
|
|
|
149
187
|
`==` 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.
|
|
188
|
+
so there is no coercion for the loose forms to do. All four compare integers, booleans, enums, `Pubkey`s, strings and
|
|
189
|
+
Options of those by value. On two structs, data enums, lists, Options of a struct or accounts they are refused: those
|
|
190
|
+
are held by reference, so the comparison would test where they are rather than what they hold, and the compiler copies
|
|
191
|
+
them where JavaScript would pass the same object (a struct argument of a helper, a local declared with its type), so
|
|
192
|
+
the answer would differ from JavaScript's. Compare the fields (`a.x === b.x && a.y === b.y`), a data enum's `.kind`,
|
|
193
|
+
a list's `.length` and elements, or two accounts' `.key`. Comparing an Option with `null` is unchanged.
|
|
151
194
|
|
|
152
195
|
## Loops
|
|
153
196
|
|
|
@@ -186,8 +229,36 @@ export function tally(book: Mut<Book>, extra: Vec<u64>, n: u64): void {
|
|
|
186
229
|
- `for (const f of [dbl, inc])` runs a list of named functions in turn ([functions](#arrow-functions-and-closures)).
|
|
187
230
|
- `while`, `do … while`, `break` and `continue`. Inside a `switch`, `break` leaves the switch and `continue` the
|
|
188
231
|
enclosing loop, as in JavaScript.
|
|
189
|
-
-
|
|
232
|
+
- A label names a loop or a block: `break outer` leaves the labeled statement, `continue outer` goes on with the
|
|
233
|
+
labeled loop's next pass (a `for` runs its update first), from any depth, as in JavaScript. A label on another
|
|
234
|
+
statement (`done: if (…)`) is refused, and so is a second label on one statement. A `loadAccountMut` view held by a
|
|
235
|
+
loop the jump leaves is dropped, as at the end of that loop's pass; a plain `break` drops its loop's views too, so
|
|
236
|
+
the accounts can be loaded again after the loop, and so does a `return` from a helper or a closure for every loop it
|
|
237
|
+
leaves.
|
|
238
|
+
- `for … in` is refused.
|
|
190
239
|
- There is no iteration limit: loops are bounded by the transaction's compute budget.
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
import { type u64 } from "typesol";
|
|
243
|
+
|
|
244
|
+
export function firstPair(n: u64, target: u64): u64 {
|
|
245
|
+
let found = 0n;
|
|
246
|
+
search: for (let i = 0n; i < n; i++) {
|
|
247
|
+
for (let j = i + 1n; j < n; j++) {
|
|
248
|
+
if (j % 3n === 0n) continue search; // next i
|
|
249
|
+
if (i + j === target) {
|
|
250
|
+
found = i * 1000n + j;
|
|
251
|
+
break search; // leaves both loops
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
done: {
|
|
256
|
+
if (found !== 0n) break done;
|
|
257
|
+
found = 1n;
|
|
258
|
+
}
|
|
259
|
+
return found;
|
|
260
|
+
}
|
|
261
|
+
```
|
|
191
262
|
- Remaining accounts are iterated by index: `for (let i = 0n; i < rest.length; i++) rest.get(i)`.
|
|
192
263
|
|
|
193
264
|
## switch
|
|
@@ -344,9 +415,14 @@ while passing large values by pointer:
|
|
|
344
415
|
|
|
345
416
|
### Inline and @noinline
|
|
346
417
|
|
|
347
|
-
clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame
|
|
418
|
+
clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame (on SBPF v1 and v2,
|
|
419
|
+
a frame of at most 32,767 bytes, with 256 KiB for all the frames of a call path).
|
|
348
420
|
`/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with
|
|
349
|
-
large locals of its own (Phoenix's order ids, built after its event recorder's last CPI)
|
|
421
|
+
large locals of its own (Phoenix's order ids, built after its event recorder's last CPI). A program that does not fit
|
|
422
|
+
the stack without it is laid out by the build itself, which keeps helpers out of line as needed
|
|
423
|
+
([Memory](language-basics.md#memory-stack-and-heap)), so `@noinline` is for compute units (a rarely taken path kept out
|
|
424
|
+
of its caller) and for explicit control. `/** @inline */` on a helper keeps the build from doing that to it (clang may
|
|
425
|
+
still keep it out of line on its own); a helper is not both.
|
|
350
426
|
|
|
351
427
|
```ts
|
|
352
428
|
import { type Mut, type u64, fixedArray } from "typesol";
|
|
@@ -561,15 +637,17 @@ may gain a hint line.
|
|
|
561
637
|
| reassigning a parameter | `n = 3n;` | "n" is const or an argument and cannot be reassigned |
|
|
562
638
|
| writing an argument | `p.x = 3n;` (`p: Point` argument) | instruction arguments are read-only; copy the value into a local first |
|
|
563
639
|
| `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 |
|
|
564
|
-
|
|
|
640
|
+
| a label on another statement | `done: if (n > 1n) { break done; }` | a label goes on a loop or a block: done: for (…) { … } (break / continue done) or done: { … } (break done) |
|
|
641
|
+
| `\|\|=` / `&&=` on a non-boolean | `b.value \|\|= n;` | \|\|= works on booleans; on u64 JavaScript would test for 0n: write if (…) b.value = … |
|
|
642
|
+
| `??=` on a non-Option | `b.value ??= n;` | ??= needs an Option on the left (u64 is never null): write b.value = … |
|
|
565
643
|
| truthiness | `if (n) log("x");` | expected boolean, got u64 |
|
|
566
644
|
| indexing with `[ ]` | `b.value = b.xs[0];` | indexing with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n) |
|
|
567
645
|
| 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) |
|
|
568
|
-
| untyped object literals
|
|
569
|
-
| `new` | `const m = new Map<u64, u64>();` |
|
|
646
|
+
| untyped object literals | `const o = { a: 1n };` | an object literal needs a struct type here: give it one (const p: Point = { … }), … |
|
|
647
|
+
| `new` | `const m = new Map<u64, u64>();` | new is not supported: a program has no Map or Set; keep entries in a FixedVec<T, N> of structs (or a FixedArray), or one account per key (a PDA) |
|
|
570
648
|
| `typeof` | `const t = typeof n;` | typeof is not supported at run time: the types are known when the program compiles |
|
|
571
649
|
| `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) |
|
|
572
|
-
| `void` | `const v = void n;` |
|
|
650
|
+
| `void` | `const v = void n;` | void is not supported: call the function as a statement (its result is then unused) |
|
|
573
651
|
| `instanceof` | `if (b instanceof Object) {}` | operator instanceof is not supported |
|
|
574
652
|
| `in` | `if ("value" in b) {}` | operator in is not supported |
|
|
575
653
|
| the comma operator | `y = (b.value = 1n, 2n);` | operator , is not supported |
|
|
@@ -582,8 +660,18 @@ may gain a hint line.
|
|
|
582
660
|
| optional fields | `export interface O { v?: u64 }` | optional fields are not supported; use v: Option<T> (null for none) |
|
|
583
661
|
| methods in interfaces | `export interface G { v(): u64 }` | structs may only contain plain fields |
|
|
584
662
|
| enum initializers | `export enum E { A = 1, B = 2 }` | value enum members are numbered 0, 1, 2… in order; leave out initializers |
|
|
585
|
-
| nested `function` declarations | `function inner(x: u64): u64 { return x; }` (in a body) |
|
|
663
|
+
| nested `function` declarations | `function inner(x: u64): u64 { return x; }` (in a body) | function declarations inside a function are not supported: write const inner = (…): T => { … } (a closure), or declare inner at the top level |
|
|
664
|
+
| a function called where it is written | `b.value = ((v: u64): u64 => v)(n);` | a function called where it is written is not supported: bind it first (const f = (…) => …) and call f(…) |
|
|
665
|
+
| `++` / `--` / `+=` as a value | `const y = m++;` | m++ is a statement in TypeSOL, not a value: read m into a const first, then write m++; on its own line |
|
|
666
|
+
| union types | `export function f(x: u64 \| boolean): void {}` | union types (u64 \| boolean) are not supported: a value has one type; use a data enum (…) for a value of several shapes |
|
|
667
|
+
| literal types | `type Side = "bid" \| "ask";` | a union of literal types ("bid" \| "ask") is not supported: use an enum (export enum Side { … }) for named choices, or the integer type itself |
|
|
668
|
+
| intersection types | `export type B = Box & { n: u64 };` | intersection types (Box & { n: u64 }) are not supported: declare an interface that extends the named structs and adds the other fields (…) |
|
|
669
|
+
| `Readonly`, `Pick`, `keyof`, `typeof` and other type operators | `function h(p: Readonly<Point>): u64 { … }` | Readonly<T> is not supported: write T itself (helper parameters are read-only already) |
|
|
670
|
+
| a spread that would share a nested object | `const c: Line = { ...l, n };` (`l.a: Point`) | ...l would copy a, a Point: JavaScript shares that object between the two values, TypeSOL copies it; give a after the spread (a: { ...l.a } copies it in JavaScript too) |
|
|
671
|
+
| a struct passed as its parent | `c.base = c.child;` (`Child extends Base`) | expected a Base: an object literal, another Base; a Child is not used as its parent Base (TypeSOL copies structs where JavaScript shares the object): … |
|
|
586
672
|
| recursion | `function a(x: u64): u64 { return x === 0n ? 0n : a(x - 1n); }` | recursion is not supported: a -> a |
|
|
673
|
+
| `declare function` | `declare function ext(x: u64): u64;` | declare function has no body to compile: a program calls only the helpers it defines and TypeSOL's built-ins (another program is called with a CPI) |
|
|
674
|
+
| overload signatures | `function h(x: u64): u64;` (before `function h(x: u64): u64 { … }`) | overload signatures are not supported: write one function, with an Option<T> parameter for an argument that may be left out |
|
|
587
675
|
| 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) |
|
|
588
676
|
| namespaces | `namespace N { export const x = 1n; }` | namespaces are not supported: use separate files and import from them |
|
|
589
677
|
| npm and Node.js imports | `import { x } from "lodash";` | only imports from "typesol" and relative TypeSOL files ("./math") are allowed, got "lodash" |
|
|
@@ -600,6 +688,9 @@ may gain a hint line.
|
|
|
600
688
|
| unary minus on unsigned | `b.value = -n;` | unary minus needs a signed integer (i8 … i128) |
|
|
601
689
|
| 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) |
|
|
602
690
|
| `===` 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) |
|
|
691
|
+
| `===` on structs | `if (p === q) {}` (`p`, `q`: `Point` arguments) | === on two structs is not supported: it would compare where they are held, not their contents, and a struct passed to a helper or declared with its type is a copy; compare the fields you need (a.x === b.x && …) |
|
|
692
|
+
| `===` on data enums | `if (e === g) {}` (`e`, `g`: data enum arguments) | === on two data enums is not supported: it would compare where they are held, not their contents; compare .kind, then the fields of the narrowed variants |
|
|
693
|
+
| `===` on lists | `if (u === w) {}` (`u`, `w`: `Vec<u64>` arguments) | === on two lists is not supported: it would compare where they are held, not their contents; compare .length and the elements (.get(i)) |
|
|
603
694
|
| 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) |
|
|
604
695
|
| 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) |
|
|
605
696
|
| `?.` on a non-optional value | `const v = b?.value;` | ?. works on optional accounts and Option<struct> values (other values are never null) |
|