@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/llms-full.txt
CHANGED
|
@@ -591,9 +591,12 @@ export function setup(config: Mut<Config>): void {
|
|
|
591
591
|
- Constants are inlined where they are used, and may be seeds; when a seed is a constant, the IDL records its value.
|
|
592
592
|
- A constant with an integer type is computed in that type, every step checked: `const X: u64 = 1n - 2n + 5n` is an
|
|
593
593
|
error (`1n - 2n is -1, which does not fit in u64`), and `const M: u8 = ~1n` is 254 (`~` within the width).
|
|
594
|
-
Division by zero, a negative exponent or a shift past the width are compile errors
|
|
594
|
+
Division by zero, a negative exponent or a shift past the width are compile errors, and so is a signed type's
|
|
595
|
+
minimum divided by or reduced modulo -1 (`const X: i8 = -128n % -1n`: the quotient does not fit, and at run time
|
|
596
|
+
that remainder fails with 5100 too), where JavaScript's bigint gives 0.
|
|
595
597
|
- An untyped integer constant is inlined as its value and takes the type of the place it is used in, as a literal
|
|
596
598
|
does: `const FEE = 30n` stores into a `u16` field, and `const FEE = 300n` into a `u8` one is `300 does not fit in u8`.
|
|
599
|
+
It is computed as a JavaScript bigint, without a width: `const R = -128n % -1n` is 0.
|
|
597
600
|
- Top-level `let` and `var` are refused: `top-level variables must be const literals`. A program has no global state
|
|
598
601
|
other than its accounts.
|
|
599
602
|
- A few names configure the compiler: `HEAP_SIZE_KIB` ([below](#memory-stack-and-heap)), `MAX_ACCOUNTS`
|
|
@@ -673,10 +676,34 @@ From the source alone, a build writes:
|
|
|
673
676
|
## Memory: stack and heap
|
|
674
677
|
|
|
675
678
|
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
|
|
676
|
-
holds at most 2 KiB, and a frame that overflows is a compile error that names its biggest locals.
|
|
679
|
+
holds at most 2 KiB, and a frame that overflows is a compile error that names its biggest locals. Under SBPF v1 and v2
|
|
680
|
+
(`--sbpf v1` / `v2`) each function's frame is sized to fit, so the 4 KiB limit is lifted, but one frame holds at most
|
|
681
|
+
32,767 bytes and all the frames of a call path share 256 KiB; the build refuses a program past either
|
|
682
|
+
([troubleshooting](troubleshooting.md#-needs-n-bytes-of-stack-sbpf-v1-allows-one-function-at-most-32767)). Strings built at run
|
|
677
683
|
time and a few other values live on the heap ([heap values](language-types.md#heap-values)), which is never freed
|
|
678
684
|
during an instruction.
|
|
679
685
|
|
|
686
|
+
A program that does not fit the stack as written is laid out another way by the build before it gives up. It does
|
|
687
|
+
nothing to a program that fits, which builds to the same bytes as before. In order, measuring with clang after each
|
|
688
|
+
step, until the program fits:
|
|
689
|
+
|
|
690
|
+
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
|
|
691
|
+
clang can give the temporaries of different statements one slot (a struct literal's, a helper result's); nothing
|
|
692
|
+
else changes;
|
|
693
|
+
2. helpers inlined into it are kept out of line, as if each were [`@noinline`](language-statements.md#inline-and-noinline),
|
|
694
|
+
largest frame first (about 10 compute units per call), except a helper that takes a function or is marked
|
|
695
|
+
`/** @inline */`; nothing else changes;
|
|
696
|
+
3. in an instruction, its largest list and struct locals and the struct results of helpers it holds are kept on the
|
|
697
|
+
heap, as if each were [`@heap`](language-types.md#heap-values) (about 17 compute units each, and their bytes of
|
|
698
|
+
heap), as long as the instruction's heap locals together fit in the heap; never a local marked `/** @stack */`.
|
|
699
|
+
|
|
700
|
+
Each step is printed as a note (`note: instruction f did not fit the stack (4864 bytes; SBPF v0 allows 4096); now 64
|
|
701
|
+
bytes`, `note: helper settle() kept out of line, for instruction trade …`) and recorded in `<name>.build.json` as
|
|
702
|
+
`stack.actions` ([cli.md](cli.md)). The steps depend only on the sources and clang's measurements, so a
|
|
703
|
+
rebuild (`typesol verify`, `--docker`) takes the same ones and gives the same bytes. When none of them is enough, the
|
|
704
|
+
build fails with the error it would have given, and a line saying what it tried. `const STACK_AUTO = false` in the
|
|
705
|
+
program (or `typesol build --stack-auto off` for one build) turns this off: the program then fails to build instead.
|
|
706
|
+
|
|
680
707
|
`const HEAP_SIZE_KIB = 64n` (32 to 256) lets the program use a bigger heap; the client must then add a ComputeBudget
|
|
681
708
|
`requestHeapFrame` instruction with that size to the transaction.
|
|
682
709
|
|
|
@@ -763,7 +790,9 @@ export function record(stats: Mut<Stats>, by: u64, change: i64): void {
|
|
|
763
790
|
u8; convert with u64(...) etc.` Comparisons (`<`, `<=`, `===`, …) need equal types too.
|
|
764
791
|
- **Every operation is checked.** `+ - * / % **` and their assignments (`+=` … `**=`) fail the instruction on
|
|
765
792
|
overflow (5100) or division by zero (5101); `**` with a negative exponent fails as well (JavaScript throws there).
|
|
766
|
-
Unlike JavaScript there are no silent wraps and no `Infinity`.
|
|
793
|
+
Unlike JavaScript there are no silent wraps and no `Infinity`. A signed type's minimum divided by -1 overflows, and
|
|
794
|
+
so does its remainder by -1 (`x % -1n` with an `i8` holding -128 fails with 5100, as Rust's checked `%` does, where
|
|
795
|
+
JavaScript gives 0); a typed constant computing it is a compile error ([constants](language-basics.md#constants)).
|
|
767
796
|
- **Bitwise operators.** `& | ^` work on equal types; `~` flips the bits within the type's width (`~1n` as a `u8` is
|
|
768
797
|
254). Both shifts fail (5100) when the amount is negative or not below the width (`x >> 64n` on a `u64`), and `<<`
|
|
769
798
|
also when bits would be lost; `>>` is arithmetic on signed types. Unlike JavaScript, where a bigint shift never
|
|
@@ -912,7 +941,8 @@ export function report(owner: Pubkey, amount: u64, limit: Option<u64>): void {
|
|
|
912
941
|
or `Hash` prints as base58 and an `Option` of an integer, boolean, `Pubkey` or `Hash` as its value or `null`, as
|
|
913
942
|
JavaScript prints it (after `x !== null`, the value). A template is joined in one allocation; text known when the
|
|
914
943
|
program compiles (literals, string and `Pubkey` constants) is folded in; `s += …` grows the newest heap string in
|
|
915
|
-
place.
|
|
944
|
+
place. The left side of `s += …` is read before the right side runs, as in JavaScript: a right side that assigns `s`
|
|
945
|
+
(a closure it calls) does not change what is appended to. Tagged templates (`` String.raw`…` ``) are refused.
|
|
916
946
|
|
|
917
947
|
## Enums
|
|
918
948
|
|
|
@@ -975,6 +1005,7 @@ export function apply(vault: Mut<Vault>, action: Action): void {
|
|
|
975
1005
|
|
|
976
1006
|
- A data enum is a union of object types, each with a `kind` string literal: Rust's enum with fields, Borsh-encoded as
|
|
977
1007
|
Anchor encodes one. `a.kind === "Deposit"` or `switch (a.kind)`, and TypeScript narrowing picks the variant.
|
|
1008
|
+
Two data enums are not compared with `===` (refused): compare their `kind`, then the fields of the narrowed variants.
|
|
978
1009
|
- Reading a variant's field is checked again at run time: when the value is not that variant, 5112.
|
|
979
1010
|
- In account data: 1 tag byte then room for the largest variant. In arguments and events: the tag, then that
|
|
980
1011
|
variant's fields.
|
|
@@ -1010,12 +1041,87 @@ export function step(player: Mut<Player>, dx: u64): void {
|
|
|
1010
1041
|
```
|
|
1011
1042
|
|
|
1012
1043
|
- An `interface` with fixed-size fields is a struct; exported ones are in the IDL. Fields are stored in declaration
|
|
1013
|
-
order, back to back, with no padding.
|
|
1044
|
+
order, back to back, with no padding. An object type alias is the same struct: `export type Point = { x: u64; y: u64 }`
|
|
1045
|
+
works wherever `export interface Point { … }` does (account data, arguments, results, events, helper parameters,
|
|
1046
|
+
fields of other structs). An object type with `kind: "Name"` is a [data enum](#data-enums) of one variant instead.
|
|
1047
|
+
Account groups are interfaces only.
|
|
1014
1048
|
- A struct literal names every field (`{ x, y: 2n }`); a missing or unknown field is an error. An object literal needs
|
|
1015
1049
|
a known struct type: a typed local (`const p: Point = { … }`), a field, a helper parameter, `emit<T>(…)`.
|
|
1016
|
-
- `a.home = b.home` copies the whole struct, as Rust and Anchor do; how `const` binds one is in
|
|
1017
|
-
|
|
1050
|
+
- `a.home = b.home` copies the whole struct, as Rust and Anchor do; how `const` binds one is in [copies and
|
|
1051
|
+
references](language-statements.md#copies-and-references). A copy between places reached through pointers (account
|
|
1052
|
+
data, a view, a helper's struct parameter) of 80 bytes or more is the memmove syscall (16 compute units up to 2,749
|
|
1053
|
+
bytes, one more per 250 bytes past that), as Rust's memcpy is; below, 8-byte loads and stores (26 units for 80
|
|
1054
|
+
bytes, 54 for 192). A copy into or out of a local of the function (a local copy, a helper's result, a struct literal
|
|
1055
|
+
built in a temporary) takes the syscall from 400 bytes, where clang stops unrolling the loads and stores (and about
|
|
1056
|
+
1 unit a byte is the loop's cost): below that the optimizer drops what nothing reads, which a call would prevent.
|
|
1057
|
+
The same holds wherever TypeSOL copies a whole value itself (Borsh fields, instruction arguments, a helper's copy of
|
|
1058
|
+
a struct argument, events), and a value it zeroes whole (`x.o = null` on an `Option<struct>`, a data-enum literal)
|
|
1059
|
+
takes the memset syscall from 192 bytes in account data and 600 in a local.
|
|
1060
|
+
- `===`, `!==`, `==` and `!=` on two structs are refused (`=== on two structs is not supported`): a struct is held by
|
|
1061
|
+
reference and copied where JavaScript would share it, so the comparison could not give JavaScript's answer. Compare
|
|
1062
|
+
the fields you need: `a.x === b.x && a.y === b.y`. The same holds for data enums, lists and Options of a struct
|
|
1063
|
+
([conditions](language-statements.md#conditions)).
|
|
1018
1064
|
- A struct cannot contain itself.
|
|
1065
|
+
- Generic structs (`interface Pair<T>`, `type Pair<T> = { … }`) and intersection types (`type B = A & { … }`) are
|
|
1066
|
+
refused; write the struct out, or extend it ([below](#structs-that-extend-others)).
|
|
1067
|
+
|
|
1068
|
+
### Structs that extend others
|
|
1069
|
+
|
|
1070
|
+
```ts
|
|
1071
|
+
import { type Mut, type Pubkey, type u32, type u64, type u8 } from "typesol";
|
|
1072
|
+
|
|
1073
|
+
export interface Base {
|
|
1074
|
+
id: u32;
|
|
1075
|
+
owner: Pubkey;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
export type Tagged = { tag: u8 };
|
|
1079
|
+
|
|
1080
|
+
// Fields, in this order: id, owner (Base's), tag (Tagged's), then qty.
|
|
1081
|
+
export interface Item extends Base, Tagged {
|
|
1082
|
+
qty: u64;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
export interface Shelf {
|
|
1086
|
+
base: Base;
|
|
1087
|
+
item: Item;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
export function stock(shelf: Mut<Shelf>, qty: u64): void {
|
|
1091
|
+
shelf.item = { ...shelf.base, tag: 1n, qty }; // a parent's fields, then the child's own
|
|
1092
|
+
shelf.base = { ...shelf.item }; // a child's copy of the parent's fields
|
|
1093
|
+
}
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
- `interface B extends A, C { … }` (with `A` and `C` structs of the program, interfaces or object types) has A's fields,
|
|
1097
|
+
then C's, then its own, in that order: that is its layout in account data, arguments and events, and its order in
|
|
1098
|
+
the IDL. In the fixed layout growable `Vec`s still go last ([fixed layout](#structs)); a `BigVec` must stay the last
|
|
1099
|
+
field, so a struct cannot extend one that ends in a `BigVec` and add fields.
|
|
1100
|
+
- A field in two parents is one field when it has the same type in both (`C.a and A.a have different types; B cannot
|
|
1101
|
+
extend both` otherwise). A struct cannot declare an inherited field again, extend a generic type, a data enum or an
|
|
1102
|
+
account group, or extend the same struct twice. Doc tags (`@layout`, `@discriminator`) are each struct's own.
|
|
1103
|
+
- A `B` is not passed or assigned where an `A` is expected (`a Child is not used as its parent Base (TypeSOL copies
|
|
1104
|
+
structs where JavaScript shares the object): …`): JavaScript would pass the object itself, extra fields and all,
|
|
1105
|
+
which TypeSOL, copying structs, could not reproduce. Write the parent's copy as a spread, `{ ...child }`, or field by
|
|
1106
|
+
field.
|
|
1107
|
+
|
|
1108
|
+
### Spreads in struct literals
|
|
1109
|
+
|
|
1110
|
+
- `{ ...p, x: 1n }` and `{ x: 1n, ...p }` build a struct from p's fields and the entries given: entries run left to
|
|
1111
|
+
right, each once, and a later one overwrites an earlier one, as in JavaScript. `...p` reads p's fields at its place,
|
|
1112
|
+
so an entry after it that changes p (a helper writing the account) does not change what was copied, and an entry
|
|
1113
|
+
before it does.
|
|
1114
|
+
- p is a struct place (a local, a field, a list element, a helper's struct parameter) or a struct account; of the
|
|
1115
|
+
literal's type, of a struct the literal's type extends (its fields are copied, the rest are given), or of one that
|
|
1116
|
+
extends it (the literal's fields are copied from it).
|
|
1117
|
+
- A spread copies as assignment does ([copies and references](language-statements.md#copies-and-references)). For
|
|
1118
|
+
scalars, strings and Options of scalars that is JavaScript's result. A field holding a struct, list or data enum
|
|
1119
|
+
would be shared by JavaScript between p and the new value, so it must be given after the spread:
|
|
1120
|
+
`{ ...p, pos: { ...p.pos } }` is a copy in JavaScript too, while `{ ...p }` alone is refused (`...p would copy pos,
|
|
1121
|
+
a Point: JavaScript shares that object between the two values, TypeSOL copies it; give pos after the spread …`).
|
|
1122
|
+
- `acct.p = { ...acct.p, x: 1n }` reads the old fields: the new value is built before it is stored.
|
|
1123
|
+
- Spreads are for struct literals of a known struct type. In `emit<T>(…)`, a data enum literal, a list literal or a
|
|
1124
|
+
built-in's object argument they are refused.
|
|
1019
1125
|
|
|
1020
1126
|
### File-local structs
|
|
1021
1127
|
|
|
@@ -1043,6 +1149,7 @@ export function bid(auction: Mut<Auction>, amount: u64, cap: Option<u64>): void
|
|
|
1043
1149
|
```
|
|
1044
1150
|
|
|
1045
1151
|
- `Option<T>` (or `T | null`) is a value or `null`. Compare with `=== null` / `!== null`; TypeScript narrows it.
|
|
1152
|
+
Two Options of a struct are not compared with `===` (refused): check each against `null`, then compare fields.
|
|
1046
1153
|
- Using an empty option where a value is needed fails with 5108; `x!` is the value, or 5108.
|
|
1047
1154
|
- `a ?? b` takes `b` only when `a` is empty, and evaluates `b` only then; the result is an Option when `b` can be null.
|
|
1048
1155
|
- `===` between options, or with a value, follows JavaScript: `null === null`, and an empty option never equals a
|
|
@@ -1157,8 +1264,8 @@ own PDA must sign, which only its `executeTransaction` does, for a transaction e
|
|
|
1157
1264
|
- Setting one up costs about the same at any size: `fixedVec([])` of 1280 bytes is about 10 CU (the free slots are
|
|
1158
1265
|
zeroed by the memset syscall, the elements written in place, also as a struct literal's field).
|
|
1159
1266
|
- **Size limit.** One list holds at most 2 KiB of elements (the FixedVec's u32 length aside: `FixedVec<u32, 512>`
|
|
1160
|
-
fits). The 4 KiB stack frame is shared with the rest of the function, and
|
|
1161
|
-
its biggest locals; a bigger list is a compile error naming its size. [`@heap`](#heap-values) moves one to the heap.
|
|
1267
|
+
fits). The 4 KiB stack frame (on SBPF v1 and v2, at most 32,767 bytes) is shared with the rest of the function, and
|
|
1268
|
+
a frame that overflows is reported with its biggest locals; a bigger list is a compile error naming its size. [`@heap`](#heap-values) moves one to the heap.
|
|
1162
1269
|
- A `FixedVec<u8, N>` is also a byte buffer: `pushLE`, `pushKey`, `pushBorsh`, `setLE`, `truncate`
|
|
1163
1270
|
([byte builders](language-native.md#byte-strings-built-by-hand)).
|
|
1164
1271
|
|
|
@@ -1294,6 +1401,8 @@ Locals live on the stack. These live on the heap (32 KiB by default;
|
|
|
1294
1401
|
- strings built at run time (5110 when the heap is full);
|
|
1295
1402
|
- a `@layout borsh` struct's `Vec` fields while the instruction runs;
|
|
1296
1403
|
- the CPI scratch lists of a program that declares `MAX_ACCOUNTS`;
|
|
1404
|
+
- a list or struct local of an instruction that the build moved there because the program did not fit the stack
|
|
1405
|
+
([Memory](language-basics.md#memory-stack-and-heap)), as it moves a helper's struct result the instruction holds;
|
|
1297
1406
|
- a list or struct local marked `/** @heap */`:
|
|
1298
1407
|
|
|
1299
1408
|
```ts
|
|
@@ -1309,7 +1418,10 @@ export function collect(n: u8): void {
|
|
|
1309
1418
|
|
|
1310
1419
|
`/** @heap */` on an instruction's list or struct local keeps it on the heap instead of the stack: one allocation per
|
|
1311
1420
|
declaration, reused when a loop declares it again, up to the heap's size, for about 18 CU. Not in helpers, which may
|
|
1312
|
-
run many times while the heap is never freed.
|
|
1421
|
+
run many times while the heap is never freed. A local the build moves to the heap to fit the stack is handled the same
|
|
1422
|
+
way (one allocation per declaration, reused by a loop; for a helper's struct result, one per call site), and only while
|
|
1423
|
+
the instruction's `@heap` and moved locals together fit in the heap; the note gives its bytes. `/** @stack */` on a
|
|
1424
|
+
list or struct local (or on `const r = helper(…)` returning a struct) keeps it off the heap; a local is not both.
|
|
1313
1425
|
|
|
1314
1426
|
**Next:** [Statements and functions](language-statements.md): which TypeScript is TypeSOL.
|
|
1315
1427
|
|
|
@@ -1327,8 +1439,9 @@ In short, a function body may contain:
|
|
|
1327
1439
|
| --- | --- |
|
|
1328
1440
|
| `const`, `let` | one name each, with an initializer ([declarations](#declarations)) |
|
|
1329
1441
|
| assignment, `+=` … `>>=`, `++`, `--` | checked arithmetic ([types](language-types.md#integers)) |
|
|
1442
|
+
| `\|\|=`, `&&=`, `??=` | [logical assignment](#logical-assignment): booleans, Options |
|
|
1330
1443
|
| `if` / `else`, `? :`, `&&`, `\|\|`, `!` | conditions are `boolean` |
|
|
1331
|
-
| `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops) |
|
|
1444
|
+
| `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops), labeled too (`outer: for …`) |
|
|
1332
1445
|
| `switch` | on integers, enums and a data enum's `kind` |
|
|
1333
1446
|
| `return` | |
|
|
1334
1447
|
| calls | helpers, closures, built-ins, account methods |
|
|
@@ -1382,7 +1495,39 @@ You can assign to a local, a field of a writable account (`Mut<T>`), a field of
|
|
|
1382
1495
|
read-only; copy the value into a local first`), and so are helper parameters (see [Inout](#inout-parameters)).
|
|
1383
1496
|
|
|
1384
1497
|
Compound assignments (`+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`) and `++` / `--` are
|
|
1385
|
-
checked like the operators they stand for.
|
|
1498
|
+
checked like the operators they stand for. All of them are statements: used as a value (`const y = x++`, `f(x += 1n)`)
|
|
1499
|
+
they are refused (`x++ is a statement in TypeSOL, not a value: …`).
|
|
1500
|
+
|
|
1501
|
+
### Logical assignment
|
|
1502
|
+
|
|
1503
|
+
```ts
|
|
1504
|
+
import { type Mut, type Option, type u64 } from "typesol";
|
|
1505
|
+
|
|
1506
|
+
export interface Prefs {
|
|
1507
|
+
seen: boolean;
|
|
1508
|
+
open: boolean;
|
|
1509
|
+
limit: Option<u64>;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
function fallback(): u64 {
|
|
1513
|
+
return 100n;
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
export function touch(prefs: Mut<Prefs>, now: boolean): void {
|
|
1517
|
+
prefs.seen ||= now; // written only when seen is false
|
|
1518
|
+
prefs.open &&= now; // written only when open is true
|
|
1519
|
+
prefs.limit ??= fallback(); // fallback() runs only when limit is empty
|
|
1520
|
+
}
|
|
1521
|
+
```
|
|
1522
|
+
|
|
1523
|
+
- `x ||= v`, `x &&= v` and `x ??= v` work wherever `x = v` does (a local, a field of a writable account or of a local
|
|
1524
|
+
struct, a list element's field), as JavaScript runs them: the place is found once, its value read, and only when it
|
|
1525
|
+
decides so (false for `||=`, true for `&&=`, empty for `??=`) is `v` evaluated and written. Otherwise `v` does not
|
|
1526
|
+
run and nothing is written.
|
|
1527
|
+
- `||=` and `&&=` take booleans. On an integer, JavaScript would test for `0n`, which TypeSOL does not do implicitly:
|
|
1528
|
+
`||= works on booleans; on u64 JavaScript would test for 0n: write if (…) x = …`.
|
|
1529
|
+
- `??=` takes an `Option` (of an integer, boolean, `Pubkey`, struct or array; `acct.home ??= { x, y }` writes the
|
|
1530
|
+
whole struct). On anything else it is refused (`??= needs an Option on the left (u64 is never null): …`).
|
|
1386
1531
|
|
|
1387
1532
|
### Copies and references
|
|
1388
1533
|
|
|
@@ -1417,6 +1562,10 @@ export function edit(shape: Mut<Shape>): void {
|
|
|
1417
1562
|
refused (`bind struct references with const`).
|
|
1418
1563
|
- **An annotation makes a copy.** `const p: Point = acct.home` (or `= { x, y }`) is a local struct of its own. Lists
|
|
1419
1564
|
likewise: `const ys: FixedVec<u64, 4> = acct.xs` is a copy.
|
|
1565
|
+
- **A spread copies.** `{ ...p, x: 1n }` copies p's fields at its place in the literal, as `field: p.field` entries
|
|
1566
|
+
would ([structs](language-types.md#spreads-in-struct-literals)). A field holding a struct, list or data enum must
|
|
1567
|
+
be given after the spread (`pos: { ...p.pos }`): JavaScript would share that nested object between the two values,
|
|
1568
|
+
which TypeSOL, copying, could not.
|
|
1420
1569
|
- **A reference cannot outlive what it names.** Replacing the referenced place (`book.bids.set(i, …)`, `pop()`,
|
|
1421
1570
|
`clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JavaScript would
|
|
1422
1571
|
keep the old object: `"q" still refers to a.home; replacing it here would change what "q" reads (in JS it keeps the
|
|
@@ -1432,7 +1581,8 @@ export function edit(shape: Mut<Shape>): void {
|
|
|
1432
1581
|
refused.
|
|
1433
1582
|
- **Evaluation order**: operands and arguments are read left to right, as in JavaScript, even when a later one changes
|
|
1434
1583
|
account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list
|
|
1435
|
-
callback writing it).
|
|
1584
|
+
callback writing it). Built-ins too: `log64(a.count, bump(a), 0n, 0n, 0n)` logs the count before the bump, and
|
|
1585
|
+
`require(a.count === n, codeOf(a))` tests the count before a helper computing the error code runs.
|
|
1436
1586
|
- **Ternaries** run only the chosen branch: `const fee = vip ? 0n : 30n`. Between accounts too:
|
|
1437
1587
|
`const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or
|
|
1438
1588
|
`RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a
|
|
@@ -1464,7 +1614,12 @@ A condition (in `if`, `while`, `for`, `? :`, `&&`, `||`, `!`) must be a `boolean
|
|
|
1464
1614
|
truthiness: `if (amount)` is refused (`expected boolean, got u64`).
|
|
1465
1615
|
|
|
1466
1616
|
`==` and `!=` compile like `===` and `!==`: both operands have the same type (`operands have different types` otherwise),
|
|
1467
|
-
so there is no coercion for the loose forms to do.
|
|
1617
|
+
so there is no coercion for the loose forms to do. All four compare integers, booleans, enums, `Pubkey`s, strings and
|
|
1618
|
+
Options of those by value. On two structs, data enums, lists, Options of a struct or accounts they are refused: those
|
|
1619
|
+
are held by reference, so the comparison would test where they are rather than what they hold, and the compiler copies
|
|
1620
|
+
them where JavaScript would pass the same object (a struct argument of a helper, a local declared with its type), so
|
|
1621
|
+
the answer would differ from JavaScript's. Compare the fields (`a.x === b.x && a.y === b.y`), a data enum's `.kind`,
|
|
1622
|
+
a list's `.length` and elements, or two accounts' `.key`. Comparing an Option with `null` is unchanged.
|
|
1468
1623
|
|
|
1469
1624
|
## Loops
|
|
1470
1625
|
|
|
@@ -1503,8 +1658,36 @@ export function tally(book: Mut<Book>, extra: Vec<u64>, n: u64): void {
|
|
|
1503
1658
|
- `for (const f of [dbl, inc])` runs a list of named functions in turn ([functions](#arrow-functions-and-closures)).
|
|
1504
1659
|
- `while`, `do … while`, `break` and `continue`. Inside a `switch`, `break` leaves the switch and `continue` the
|
|
1505
1660
|
enclosing loop, as in JavaScript.
|
|
1506
|
-
-
|
|
1661
|
+
- A label names a loop or a block: `break outer` leaves the labeled statement, `continue outer` goes on with the
|
|
1662
|
+
labeled loop's next pass (a `for` runs its update first), from any depth, as in JavaScript. A label on another
|
|
1663
|
+
statement (`done: if (…)`) is refused, and so is a second label on one statement. A `loadAccountMut` view held by a
|
|
1664
|
+
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
|
|
1665
|
+
the accounts can be loaded again after the loop, and so does a `return` from a helper or a closure for every loop it
|
|
1666
|
+
leaves.
|
|
1667
|
+
- `for … in` is refused.
|
|
1507
1668
|
- There is no iteration limit: loops are bounded by the transaction's compute budget.
|
|
1669
|
+
|
|
1670
|
+
```ts
|
|
1671
|
+
import { type u64 } from "typesol";
|
|
1672
|
+
|
|
1673
|
+
export function firstPair(n: u64, target: u64): u64 {
|
|
1674
|
+
let found = 0n;
|
|
1675
|
+
search: for (let i = 0n; i < n; i++) {
|
|
1676
|
+
for (let j = i + 1n; j < n; j++) {
|
|
1677
|
+
if (j % 3n === 0n) continue search; // next i
|
|
1678
|
+
if (i + j === target) {
|
|
1679
|
+
found = i * 1000n + j;
|
|
1680
|
+
break search; // leaves both loops
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
done: {
|
|
1685
|
+
if (found !== 0n) break done;
|
|
1686
|
+
found = 1n;
|
|
1687
|
+
}
|
|
1688
|
+
return found;
|
|
1689
|
+
}
|
|
1690
|
+
```
|
|
1508
1691
|
- Remaining accounts are iterated by index: `for (let i = 0n; i < rest.length; i++) rest.get(i)`.
|
|
1509
1692
|
|
|
1510
1693
|
## switch
|
|
@@ -1661,9 +1844,14 @@ while passing large values by pointer:
|
|
|
1661
1844
|
|
|
1662
1845
|
### Inline and @noinline
|
|
1663
1846
|
|
|
1664
|
-
clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame
|
|
1847
|
+
clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame (on SBPF v1 and v2,
|
|
1848
|
+
a frame of at most 32,767 bytes, with 256 KiB for all the frames of a call path).
|
|
1665
1849
|
`/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with
|
|
1666
|
-
large locals of its own (Phoenix's order ids, built after its event recorder's last CPI)
|
|
1850
|
+
large locals of its own (Phoenix's order ids, built after its event recorder's last CPI). A program that does not fit
|
|
1851
|
+
the stack without it is laid out by the build itself, which keeps helpers out of line as needed
|
|
1852
|
+
([Memory](language-basics.md#memory-stack-and-heap)), so `@noinline` is for compute units (a rarely taken path kept out
|
|
1853
|
+
of its caller) and for explicit control. `/** @inline */` on a helper keeps the build from doing that to it (clang may
|
|
1854
|
+
still keep it out of line on its own); a helper is not both.
|
|
1667
1855
|
|
|
1668
1856
|
```ts
|
|
1669
1857
|
import { type Mut, type u64, fixedArray } from "typesol";
|
|
@@ -1878,15 +2066,17 @@ may gain a hint line.
|
|
|
1878
2066
|
| reassigning a parameter | `n = 3n;` | "n" is const or an argument and cannot be reassigned |
|
|
1879
2067
|
| writing an argument | `p.x = 3n;` (`p: Point` argument) | instruction arguments are read-only; copy the value into a local first |
|
|
1880
2068
|
| `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 |
|
|
1881
|
-
|
|
|
2069
|
+
| 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) |
|
|
2070
|
+
| `\|\|=` / `&&=` on a non-boolean | `b.value \|\|= n;` | \|\|= works on booleans; on u64 JavaScript would test for 0n: write if (…) b.value = … |
|
|
2071
|
+
| `??=` on a non-Option | `b.value ??= n;` | ??= needs an Option on the left (u64 is never null): write b.value = … |
|
|
1882
2072
|
| truthiness | `if (n) log("x");` | expected boolean, got u64 |
|
|
1883
2073
|
| indexing with `[ ]` | `b.value = b.xs[0];` | indexing with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n) |
|
|
1884
2074
|
| 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) |
|
|
1885
|
-
| untyped object literals
|
|
1886
|
-
| `new` | `const m = new Map<u64, u64>();` |
|
|
2075
|
+
| untyped object literals | `const o = { a: 1n };` | an object literal needs a struct type here: give it one (const p: Point = { … }), … |
|
|
2076
|
+
| `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) |
|
|
1887
2077
|
| `typeof` | `const t = typeof n;` | typeof is not supported at run time: the types are known when the program compiles |
|
|
1888
2078
|
| `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) |
|
|
1889
|
-
| `void` | `const v = void n;` |
|
|
2079
|
+
| `void` | `const v = void n;` | void is not supported: call the function as a statement (its result is then unused) |
|
|
1890
2080
|
| `instanceof` | `if (b instanceof Object) {}` | operator instanceof is not supported |
|
|
1891
2081
|
| `in` | `if ("value" in b) {}` | operator in is not supported |
|
|
1892
2082
|
| the comma operator | `y = (b.value = 1n, 2n);` | operator , is not supported |
|
|
@@ -1899,8 +2089,18 @@ may gain a hint line.
|
|
|
1899
2089
|
| optional fields | `export interface O { v?: u64 }` | optional fields are not supported; use v: Option<T> (null for none) |
|
|
1900
2090
|
| methods in interfaces | `export interface G { v(): u64 }` | structs may only contain plain fields |
|
|
1901
2091
|
| enum initializers | `export enum E { A = 1, B = 2 }` | value enum members are numbered 0, 1, 2… in order; leave out initializers |
|
|
1902
|
-
| nested `function` declarations | `function inner(x: u64): u64 { return x; }` (in a body) |
|
|
2092
|
+
| 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 |
|
|
2093
|
+
| 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(…) |
|
|
2094
|
+
| `++` / `--` / `+=` 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 |
|
|
2095
|
+
| 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 |
|
|
2096
|
+
| 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 |
|
|
2097
|
+
| 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 (…) |
|
|
2098
|
+
| `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) |
|
|
2099
|
+
| 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) |
|
|
2100
|
+
| 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): … |
|
|
1903
2101
|
| recursion | `function a(x: u64): u64 { return x === 0n ? 0n : a(x - 1n); }` | recursion is not supported: a -> a |
|
|
2102
|
+
| `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) |
|
|
2103
|
+
| 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 |
|
|
1904
2104
|
| 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) |
|
|
1905
2105
|
| namespaces | `namespace N { export const x = 1n; }` | namespaces are not supported: use separate files and import from them |
|
|
1906
2106
|
| npm and Node.js imports | `import { x } from "lodash";` | only imports from "typesol" and relative TypeSOL files ("./math") are allowed, got "lodash" |
|
|
@@ -1917,6 +2117,9 @@ may gain a hint line.
|
|
|
1917
2117
|
| unary minus on unsigned | `b.value = -n;` | unary minus needs a signed integer (i8 … i128) |
|
|
1918
2118
|
| 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) |
|
|
1919
2119
|
| `===` 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) |
|
|
2120
|
+
| `===` 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 && …) |
|
|
2121
|
+
| `===` 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 |
|
|
2122
|
+
| `===` 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)) |
|
|
1920
2123
|
| 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) |
|
|
1921
2124
|
| 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) |
|
|
1922
2125
|
| `?.` on a non-optional value | `const v = b?.value;` | ?. works on optional accounts and Option<struct> values (other values are never null) |
|
|
@@ -2139,18 +2342,21 @@ export function remove(owner: Mut<Signer>, log: HasOne<Mut<Log>, "owner">): void
|
|
|
2139
2342
|
}
|
|
2140
2343
|
```
|
|
2141
2344
|
|
|
2142
|
-
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2345
|
+
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable account)
|
|
2346
|
+
and its data is zeroed (by the memset syscall when the account's type takes 64 bytes or more, by stores below). The
|
|
2347
|
+
account is not used after it in the function, except its `key` (compile errors, or 2040 at run time in a helper
|
|
2348
|
+
given one account twice). `CloseTo<A, "dest">` does the same when the instruction succeeds
|
|
2349
|
+
([constraints](#constraints)).
|
|
2146
2350
|
- Who may call them: `HasOne` above lets only the log's owner close it (the lamports of a closed account are value)
|
|
2147
2351
|
or resize it. Without that check anyone could pay to grow, or shrink, another user's account.
|
|
2148
2352
|
- `realloc(account, newSize, payer)` on a `Mut<Struct>`: growing charges the payer the extra rent (at most 10 KiB per
|
|
2149
|
-
instruction, 3016); shrinking keeps the lamports in the account; never below the struct.
|
|
2150
|
-
|
|
2353
|
+
instruction, 3016); shrinking keeps the lamports in the account; never below the struct (3016). For a `@layout borsh`
|
|
2354
|
+
struct that is its discriminator and smallest Borsh form (an empty `FixedString<64>` takes 4 bytes, not 68), the size
|
|
2355
|
+
its load accepts; the value written back when the instruction returns must still fit (3004). Refused on a struct
|
|
2356
|
+
with a growable `Vec` (its push / pop / clear size the account).
|
|
2151
2357
|
- `resizeAccount(account, newSize)` on a `Mut<AccountInfo>` of this program is Rust's `AccountInfo::resize`: the
|
|
2152
|
-
length only, new bytes zeroed
|
|
2153
|
-
(3016).
|
|
2358
|
+
length only, new bytes zeroed (64 or more by the memset syscall, as `realloc` zeroes them too), no rent moved (fund
|
|
2359
|
+
it first: `rentExempt(newSize)`), at most 10 KiB of growth (3016).
|
|
2154
2360
|
- An account grows at most 10 KiB per instruction, counted from its length when the instruction started (Solana's
|
|
2155
2361
|
limit): realloc again in the next instruction.
|
|
2156
2362
|
- `account.lamports` can be read on any account and written on a `Mut` one.
|
|
@@ -2213,7 +2419,8 @@ the body, in Anchor's order, and recorded in the IDL (`relations`, `pda`, `addre
|
|
|
2213
2419
|
among its types, not its accounts (an error named on such an `Owner` is not used: the load fails with 3007). Such a
|
|
2214
2420
|
struct may carry a shorter discriminator, `/** @discriminator 0x01 */` (1 to 8 bytes, as Anchor's
|
|
2215
2421
|
`discriminator = &[1]`; Solend's reserve), its fields then starting right after it; this program's own accounts
|
|
2216
|
-
keep 8.
|
|
2422
|
+
keep 8. A `@layout borsh` struct's Borsh bytes start there too, and the account must hold the discriminator and the
|
|
2423
|
+
struct's smallest Borsh form (3003).
|
|
2217
2424
|
- `Address<InstructionsSysvar, "Sysvar1nstructions1111111111111111111111111">` checks the address as Anchor's
|
|
2218
2425
|
`address = sysvar::instructions::ID` on an `UncheckedAccount` does (2012, with the constraints).
|
|
2219
2426
|
|
|
@@ -2246,7 +2453,9 @@ are compared too ([native programs](language-native.md#inout-places-that-may-be-
|
|
|
2246
2453
|
|
|
2247
2454
|
At most 32 accounts per instruction; more is refused with 5113. `export const MAX_ACCOUNTS = 128n` (up to 255; Anchor
|
|
2248
2455
|
takes what the runtime allows) raises it for programs that take many remaining accounts. The CPI scratch lists are
|
|
2249
|
-
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before.
|
|
2456
|
+
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before. 255 is also
|
|
2457
|
+
the runtime's limit: an instruction naming more accounts (repeats count) fails with MaxAccountsExceeded before any
|
|
2458
|
+
program runs.
|
|
2250
2459
|
|
|
2251
2460
|
## Optional accounts
|
|
2252
2461
|
|
|
@@ -2499,7 +2708,10 @@ A seed list is an array literal written where the seeds go. Each seed contribute
|
|
|
2499
2708
|
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`
|
|
2500
2709
|
argument longer than that is only known at run time: `create`, `createIfNeeded`, `requirePda` and `Seeds<…>` then fail
|
|
2501
2710
|
with 2006, as for any other address that is not the PDA; check `byteLength(s) <= 32n` first to fail with an error of
|
|
2502
|
-
your own.
|
|
2711
|
+
your own. A list whose every seed has a length known at compile time (keys, integers, enums, string literals and
|
|
2712
|
+
constants) cannot exceed the limits, so its derivation skips the run-time check of the seed lengths; a list with a
|
|
2713
|
+
`string` value keeps it, and so do the account-creating calls (`create`, `createIfNeeded`, `createPda` and the token
|
|
2714
|
+
creates) of any program that passes one of them such a list. Solana takes at
|
|
2503
2715
|
most 16 seeds per address, the bump included. A list the derivation adds the bump to (`create`, `requirePda`,
|
|
2504
2716
|
`findProgramAddress`) holds at most 15 entries (`at most 15 seeds: the bump the derivation adds makes 16, Solana's
|
|
2505
2717
|
limit`); a list that ends with its bump (signer seeds, `createProgramAddress`) holds 16: 15 seeds and the bump (`at
|
|
@@ -2578,7 +2790,8 @@ export function locate(book: Mut<Book>, owner: Pubkey, start: u64): void {
|
|
|
2578
2790
|
- `findProgramAddress(seeds, program)` is the canonical PDA of any program (Rust's
|
|
2579
2791
|
`Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id), and `findProgramAddressBump(seeds, program)` its
|
|
2580
2792
|
bump. `const [address, bump] = findProgramAddressWithBump(seeds, program)` gives both from one search (Rust's
|
|
2581
|
-
`let (address, bump) = …`). Each search costs about 450 CU per bump tried
|
|
2793
|
+
`let (address, bump) = …`). Each search costs about 450 CU per bump tried, and tries 255 down to 1 as Solana's
|
|
2794
|
+
does: bump 0 is never tried.
|
|
2582
2795
|
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address`: the address for seeds that include the
|
|
2583
2796
|
bump, or `null` when they give none.
|
|
2584
2797
|
- `programId()` is this program's address.
|
|
@@ -3165,6 +3378,40 @@ Pubkeys, unit enums and arrays is read as its bytes (booleans and enums checked)
|
|
|
3165
3378
|
Vecs is declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106. The
|
|
3166
3379
|
type argument is required.
|
|
3167
3380
|
|
|
3381
|
+
Return data of any length, checked by the program itself (Rust's `get_return_data()`, as a native program reads a
|
|
3382
|
+
reply of several records), is `getReturnData()`:
|
|
3383
|
+
|
|
3384
|
+
```ts
|
|
3385
|
+
import { getReturnData, instructionData, invoke, log, remainingAccounts, require, u8 } from "typesol";
|
|
3386
|
+
|
|
3387
|
+
export enum MatchError {
|
|
3388
|
+
/** @code 0 */
|
|
3389
|
+
NoReply = "NoReply",
|
|
3390
|
+
BadReply = "BadReply",
|
|
3391
|
+
}
|
|
3392
|
+
|
|
3393
|
+
/** @fallback */
|
|
3394
|
+
export function entry(): void {
|
|
3395
|
+
const matcher = remainingAccounts().get(0n);
|
|
3396
|
+
const data = instructionData();
|
|
3397
|
+
const legs = data.readU64(0n);
|
|
3398
|
+
invoke(matcher, [], [u8(1n), legs]);
|
|
3399
|
+
const [from, reply] = getReturnData();
|
|
3400
|
+
// Rust's None: no return data (the runtime keeps no empty return data); `from` is then all zeros.
|
|
3401
|
+
require(reply.length > 0n, MatchError.NoReply);
|
|
3402
|
+
require(from === matcher.key && reply.length === legs * 64n, MatchError.BadReply);
|
|
3403
|
+
log(reply.readU64(8n));
|
|
3404
|
+
}
|
|
3405
|
+
```
|
|
3406
|
+
|
|
3407
|
+
- `from` is the program that set the return data (a Pubkey); `reply` its bytes, up to the runtime's 1,024, with the
|
|
3408
|
+
methods of instruction data (`length`, `get`, `readU8` … `readU128`, `readPubkey`, `slice`; 5104 past the end).
|
|
3409
|
+
- Nothing is checked and nothing fails: the program, the length and the contents are the caller's to check, with its
|
|
3410
|
+
own errors. It reads whatever the runtime holds: the last CPI's callee's return data, or what this instruction set
|
|
3411
|
+
with `setReturnData` after it.
|
|
3412
|
+
- Bound with `const [program, data] = …` where it is called (either name may be left out: `const [, data]`). The bytes
|
|
3413
|
+
are copied into 1 KiB of the calling function's stack frame.
|
|
3414
|
+
|
|
3168
3415
|
## invokeInstruction
|
|
3169
3416
|
|
|
3170
3417
|
A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
|
|
@@ -3773,6 +4020,16 @@ A native account whose parts start where its header says (Phoenix's market at by
|
|
|
3773
4020
|
after a helper that may close or resize one it is given: its bounds were checked against the old length, so it is a
|
|
3774
4021
|
compile error saying to take the view again.
|
|
3775
4022
|
|
|
4023
|
+
### Struct copies between views that overlap
|
|
4024
|
+
|
|
4025
|
+
Two views of one account at run-time offsets (`loadRawAt`, `loadRawMutAt`, an account passed twice under
|
|
4026
|
+
`NATIVE_ACCOUNT_WRITES`) can overlap, and `d.v = s.v` then copies between overlapping bytes. The destination ends with
|
|
4027
|
+
the source's old bytes, in either direction and at any size, as Rust's `copy_within` or a struct copied out and
|
|
4028
|
+
written back leaves it: below 80 bytes every byte is loaded before any is stored (a load and then a store per 8
|
|
4029
|
+
bytes), from 80 bytes the memmove syscall copies them. A copy through a local (`const c: T = s.v; d.v = c;`) and
|
|
4030
|
+
`copyData` give the same bytes
|
|
4031
|
+
([`test/language/bulk-copies.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/bulk-copies.test.ts)).
|
|
4032
|
+
|
|
3776
4033
|
## lib-sokoban's red-black tree
|
|
3777
4034
|
|
|
3778
4035
|
```ts
|
|
@@ -3926,9 +4183,19 @@ On remaining accounts and `AccountInfo` parameters:
|
|
|
3926
4183
|
the account's owner: check that it is this program's first (the runtime would fail the instruction after it returns,
|
|
3927
4184
|
having changed another program's account). The length does not change, so views made before stay valid and read the
|
|
3928
4185
|
zeros.
|
|
3929
|
-
- `
|
|
3930
|
-
|
|
3931
|
-
|
|
4186
|
+
- `copyData(account, from, to, length)` copies `length` bytes of the data from offset `from` to offset `to`, as a
|
|
4187
|
+
native program's `data.copy_within(from..from + length, to)` or a struct copied out and written back at another
|
|
4188
|
+
offset (a memcpy in Rust): the memmove syscall from 32 bytes, about constant compute units whatever the length (a
|
|
4189
|
+
whole-struct assignment `a.p = b.p` between views uses it too, from 80 bytes: [overlapping
|
|
4190
|
+
views](#struct-copies-between-views-that-overlap)). The ranges may overlap. A range past the end of the data fails
|
|
4191
|
+
with 3003 and copies nothing; without `NATIVE_ACCOUNT_WRITES` the account must be writable (3006). Like `zeroData`
|
|
4192
|
+
it does not check the owner, and views made before stay valid and read the copied bytes (Percolator v16's InitMarket
|
|
4193
|
+
copies asset 0's 424-byte oracle profile into every slot of the market this way;
|
|
4194
|
+
[`test/language/native-copy-data.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/native-copy-data.test.ts)).
|
|
4195
|
+
- `resizeAccount(account, size)` also takes a remaining account (`realloc(size, true)`: new bytes zeroed, 64 or more
|
|
4196
|
+
by the memset syscall as Rust's realloc zeroes them, fewer by stores; at most 10 KiB past the size it had when the
|
|
4197
|
+
instruction started, 3016). That size is the one the entrypoint records in the account's record, as solana_program
|
|
4198
|
+
1.14's does, only in programs that resize a remaining account.
|
|
3932
4199
|
- A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node or a struct read
|
|
3933
4200
|
through one) is a compile error to use after it: its bounds were checked against the old length, so take the view
|
|
3934
4201
|
again.
|
|
@@ -3938,6 +4205,7 @@ On remaining accounts and `AccountInfo` parameters:
|
|
|
3938
4205
|
(`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`), and plain
|
|
3939
4206
|
`AccountInfo` parameters are enough.
|
|
3940
4207
|
|
|
4208
|
+
|
|
3941
4209
|
## Errors and panics as the original reports them
|
|
3942
4210
|
|
|
3943
4211
|
```ts
|
|
@@ -3981,6 +4249,30 @@ export function entry(): void {
|
|
|
3981
4249
|
location)` log one line, `panicked at <location>:` and the message after a newline, and then abort ("SBF program
|
|
3982
4250
|
panicked"), as that panic handler does: `panicked at src/wide_math.rs:1554:30:\nmul_div_floor_u128: a*b overflow`.
|
|
3983
4251
|
As under "solana-1.14", a message is required and `PANIC_ON_OVERFLOW`'s panics abort.
|
|
4252
|
+
- **Panics as pinocchio's entrypoint writes them.** `export const PANIC_STYLE = "pinocchio"` (a program built with
|
|
4253
|
+
pinocchio's `entrypoint!`, whose `default_panic_handler!` hook runs under std: Percolator v16) makes `panic(message,
|
|
4254
|
+
location)` log two lines, the location's file exactly as Rust records it and then `** PANICKED **`, and abort ("SBF
|
|
4255
|
+
program panicked"):
|
|
4256
|
+
|
|
4257
|
+
```
|
|
4258
|
+
Program log: src/v16.rs
|
|
4259
|
+
Program log: ** PANICKED **
|
|
4260
|
+
Program <id> failed: SBF program panicked
|
|
4261
|
+
```
|
|
4262
|
+
|
|
4263
|
+
- The file is `Location::file()` verbatim: the path rustc was given, which cargo makes relative to the crate
|
|
4264
|
+
(`src/v16.rs`, `src/account_info.rs` inside solana-program) and which is the toolchain's absolute path for a panic
|
|
4265
|
+
inside the standard library that is not reported at its caller (Percolator v16's binary holds
|
|
4266
|
+
`/home/runner/work/platform-tools/platform-tools/out/rust/library/alloc/src/raw_vec/mod.rs`). Give it as the
|
|
4267
|
+
location, alone or with its line and column (`"src/v16.rs:812:9"`, logged as `src/v16.rs`), so the port's source
|
|
4268
|
+
keeps the original's place. Index, `unwrap`, `RefCell::borrow_mut` and `Vec::with_capacity`'s capacity panics are
|
|
4269
|
+
reported at their caller (`#[track_caller]`), so their file is the caller's.
|
|
4270
|
+
- No message is logged (the hook ignores it): the message may be `null` or a note for the reader. Without a
|
|
4271
|
+
location this source file's name is logged.
|
|
4272
|
+
- `panicsAt(location, expression)` logs its location's file the same way. `PANIC_ON_OVERFLOW` is refused with this
|
|
4273
|
+
style: its panics have no file; wrap the arithmetic in `panicsAt`.
|
|
4274
|
+
- Every panic site calls one shared helper (the two log calls and the abort), so a port with many panic sites stays
|
|
4275
|
+
small.
|
|
3984
4276
|
- **Overflow panics with Rust's message and location.** `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
|
|
3985
4277
|
checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
|
|
3986
4278
|
"attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with
|
|
@@ -3996,7 +4288,8 @@ export function entry(): void {
|
|
|
3996
4288
|
quantities.rs, wherever the addition is written): give the port a helper, `function addQuoteLots(a: u64, b: u64):
|
|
3997
4289
|
u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`.
|
|
3998
4290
|
- The bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks
|
|
3999
|
-
them differently, or with other messages)
|
|
4291
|
+
them differently, or with other messages): `panicsAt(LOC, a ** 2n)` fails with 5100 when the square overflows,
|
|
4292
|
+
while an operator in `**`'s operands (`(a + b) ** 2n`) still panics at the location.
|
|
4000
4293
|
- [`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.
|
|
4001
4294
|
|
|
4002
4295
|
## Log lines as the original writes them
|
|
@@ -4076,7 +4369,7 @@ void instruction (Phoenix's Borsh `Vec<FIFOOrderId>` of the orders that rested,
|
|
|
4076
4369
|
|
|
4077
4370
|
<!-- Generated by scripts/language-builtins.ts from lib/typesol.d.ts; do not edit by hand. -->
|
|
4078
4371
|
|
|
4079
|
-
Every name `"typesol"` exports (
|
|
4372
|
+
Every name `"typesol"` exports (222 names, 235 declarations), grouped, with its declaration and the first sentence of its doc
|
|
4080
4373
|
comment in `lib/typesol.d.ts`. Each group links to the part of the [language guide](language.md) that explains it;
|
|
4081
4374
|
your editor shows the full doc comment on hover. Methods of account and program types (`systemProgram.transfer`,
|
|
4082
4375
|
`acct.create`, …) are described with their types in the guide.
|
|
@@ -4214,7 +4507,7 @@ Explained in [Accounts: Closing and resizing](language-accounts.md#closing-and-r
|
|
|
4214
4507
|
| --- | --- | --- |
|
|
4215
4508
|
| `close` | `function close(account: AccountMeta, destination: AccountMeta): void` | Close a program-owned account: move all lamports to `destination` and wipe it. |
|
|
4216
4509
|
| `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. |
|
|
4217
|
-
| `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. |
|
|
4510
|
+
| `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). |
|
|
4218
4511
|
|
|
4219
4512
|
## Accounts created by hand
|
|
4220
4513
|
|
|
@@ -4294,6 +4587,7 @@ Explained in [Calling other programs: invoke](language-cpi.md#invoke).
|
|
|
4294
4587
|
| `sighash` | `function sighash(name: string): Bytes` | The 8-byte Anchor instruction discriminator for `name` (sha256("global:<snake_case name>")[..8]). |
|
|
4295
4588
|
| `hex` | `function hex(literal: string): Bytes` | Bytes from a hex string literal, e.g. hex("0a0b"). |
|
|
4296
4589
|
| `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)`. |
|
|
4590
|
+
| `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()`. |
|
|
4297
4591
|
| `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)`). |
|
|
4298
4592
|
| `InstructionAccountMeta` | `interface InstructionAccountMeta` | One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. |
|
|
4299
4593
|
| `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. |
|
|
@@ -4478,6 +4772,7 @@ Explained in [Porting a native program (advanced)](language-native.md).
|
|
|
4478
4772
|
| `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). |
|
|
4479
4773
|
| `assignOwner` | `function assignOwner(account: RemainingAccount \| Mut<AccountInfo>, owner: Pubkey): void` | Set an account's owner in place (Rust's `AccountInfo::assign`). |
|
|
4480
4774
|
| `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. |
|
|
4775
|
+
| `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. |
|
|
4481
4776
|
| `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. |
|
|
4482
4777
|
| `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). |
|
|
4483
4778
|
| `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. |
|
|
@@ -4549,7 +4844,8 @@ bytes. See [seeds](language-pdas.md#seeds).
|
|
|
4549
4844
|
## Bump
|
|
4550
4845
|
|
|
4551
4846
|
The one byte added to a PDA's seeds so that the derived address has no private key. The canonical bump is the
|
|
4552
|
-
highest that works; it is found by trying 255, 254, …
|
|
4847
|
+
highest that works; it is found by trying 255, 254, … down to 1, as Solana's `find_program_address` does (bump 0 is
|
|
4848
|
+
never tried), and is usually stored in the account. See [PDAs](language-pdas.md).
|
|
4553
4849
|
|
|
4554
4850
|
## Signer
|
|
4555
4851
|
|
|
@@ -5021,10 +5317,10 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
|
|
|
5021
5317
|
| Command | What it does |
|
|
5022
5318
|
| --- | --- |
|
|
5023
5319
|
| `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow] [--no-agent-files]` | Create a project ([below](#typesol-init)). |
|
|
5024
|
-
| `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. |
|
|
5320
|
+
| `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). |
|
|
5025
5321
|
| `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. |
|
|
5026
|
-
| `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)). |
|
|
5027
|
-
| `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. |
|
|
5322
|
+
| `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)). |
|
|
5323
|
+
| `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. |
|
|
5028
5324
|
| `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). |
|
|
5029
5325
|
| `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. |
|
|
5030
5326
|
| `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
|
|
@@ -5061,7 +5357,8 @@ process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `war
|
|
|
5061
5357
|
`<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the
|
|
5062
5358
|
program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above
|
|
5063
5359
|
rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). `init` refuses to
|
|
5064
|
-
overwrite files
|
|
5360
|
+
overwrite files, and to write through a symbolic link inside `<dir>` (a linked `.cursor/`, say, whose files would
|
|
5361
|
+
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
|
|
5065
5362
|
says whether the Agave CLI is missing or only its platform-tools (on Linux arm64, where there is no Agave CLI, the
|
|
5066
5363
|
commands that set up the platform-tools' `linux-aarch64` package).
|
|
5067
5364
|
|
|
@@ -5544,7 +5841,8 @@ a ComputeBudget `requestHeapFrame` instruction to the transaction.
|
|
|
5544
5841
|
### "instruction X (with the helpers inlined into it) needs N bytes of stack; SBPF v0 gives each function 4096"
|
|
5545
5842
|
|
|
5546
5843
|
Under SBPF v0 (the default) every function gets a fixed 4 KiB stack frame, and going past it corrupts memory, so the
|
|
5547
|
-
build refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`)
|
|
5844
|
+
build refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`) size each function's frame, so the 4 KiB limit is lifted there,
|
|
5845
|
+
but they have limits of their own (the next two entries). Large
|
|
5548
5846
|
structs and arrays copied into typed locals (`const q: Big = acct.big`) are the usual cause: bind them without a type
|
|
5549
5847
|
(`const q = acct.big`, a reference into the account data). The message lists the biggest locals (clang's frame layout: a
|
|
5550
5848
|
local's name and the source line near it; the locals of an inlined helper show as unnamed, with the helpers' locals that
|
|
@@ -5552,6 +5850,49 @@ may be them). Helpers are often inlined into their instruction, so their locals
|
|
|
5552
5850
|
@noinline */` to give it a 4 KiB frame of its own (a few compute units per call), or declare a large local list or
|
|
5553
5851
|
struct of an instruction `/** @heap */` to keep it on the heap (about 18 CU for the allocation).
|
|
5554
5852
|
|
|
5853
|
+
The build tries those itself before it gives this error ([Memory](language-basics.md#memory-stack-and-heap)): when they
|
|
5854
|
+
were not enough, the message ends with "To fit, the build also tried …", and lists the locals the heap could not hold.
|
|
5855
|
+
What is left is usually a helper's own locals (the build keeps a helper's locals on the stack: it may run many times,
|
|
5856
|
+
and the heap is never freed) or one local larger than the heap. With `const STACK_AUTO = false` (or `--stack-auto off`)
|
|
5857
|
+
the build does not try, and gives the error as it is.
|
|
5858
|
+
|
|
5859
|
+
### "note: instruction X did not fit the stack …"
|
|
5860
|
+
|
|
5861
|
+
Not an error: the program did not fit the stack as written, and the build laid it out another way (the notes after it
|
|
5862
|
+
say how, and `<name>.build.json` records it under `stack`). Its binary differs from what the source would give if it
|
|
5863
|
+
fitted, so a port comparing compute units with its original should look at the notes: a helper kept out of line costs
|
|
5864
|
+
about 10 compute units per call, a local on the heap about 17 and its bytes of heap. Declaring the same yourself
|
|
5865
|
+
(`/** @noinline */`, `/** @heap */`) or binding large values as references instead of copies gives the same or better,
|
|
5866
|
+
and `/** @inline */` or `/** @stack */` keeps the build from choosing a helper or a local.
|
|
5867
|
+
|
|
5868
|
+
### "… needs N bytes of stack; SBPF v1 allows one function at most 32767"
|
|
5869
|
+
|
|
5870
|
+
On SBPF v1 and v2 a load or store reaches its stack slot with a signed 16-bit offset, so a frame over 32,767 bytes
|
|
5871
|
+
cannot be addressed: clang's SBF backend builds it anyway, with the large offsets wrapped, and the program reads and
|
|
5872
|
+
writes the wrong memory. The build refuses such a frame. The remedies are the ones above: references instead of copies,
|
|
5873
|
+
`/** @heap */` on a large local of an instruction, or a `/** @noinline */` helper for work with large locals of its
|
|
5874
|
+
own.
|
|
5875
|
+
|
|
5876
|
+
### "the deepest call path needs N bytes of stack; SBPF v1 gives all the frames of a call path together 262144"
|
|
5877
|
+
|
|
5878
|
+
On SBPF v1 and v2 every frame of a call path (the entrypoint, the instruction, each helper it calls in turn) comes out
|
|
5879
|
+
of one 256 KiB stack, and past it the program fails with an access violation. After linking, the build measures the
|
|
5880
|
+
deepest path from the program's own code (its calls and the frame each function reserves, so a helper clang inlined
|
|
5881
|
+
counts in its caller) and refuses a program whose deepest path is over 262,144 bytes. The message lists the path with
|
|
5882
|
+
each function's frame. Shorten it: keep large values in account data or on the heap, or call the helpers with large
|
|
5883
|
+
frames one after another rather than from each other. (An indirect call, which TypeSOL does not generate, cannot be
|
|
5884
|
+
followed: a program with one is refused with a request to report it.)
|
|
5885
|
+
|
|
5886
|
+
### "… a call passes arguments on the stack past the end of the 4096-byte frame of SBPF v0"
|
|
5887
|
+
|
|
5888
|
+
A helper call with more than 5 arguments in C (its parameters, plus one for the program's context and one for a
|
|
5889
|
+
returned value) passes the rest on the stack, after the caller's locals. When the caller's frame is at the limit,
|
|
5890
|
+
those arguments overwrite its own values. clang's SBF backend reports this ("A function call in method … overwrites
|
|
5891
|
+
values in the frame") but still builds, and such a program computed wrong results; the build now refuses it, naming the
|
|
5892
|
+
function and the helpers it calls with arguments on the stack. Give the helper fewer parameters (a struct parameter is
|
|
5893
|
+
passed as one pointer) or make room in the caller as above. The backend's other message, "Stack offset of N exceeded
|
|
5894
|
+
max offset of M", is refused the same way.
|
|
5895
|
+
|
|
5555
5896
|
### "… is missing, but typesol.json records …"
|
|
5556
5897
|
|
|
5557
5898
|
The program keypair under `target/deploy/` was deleted or replaced. Restore it from your backup. Without it you cannot
|
|
@@ -6039,12 +6380,15 @@ exposed to them.
|
|
|
6039
6380
|
The compiler and runtime have had internal security reviews, the latest of 0.44.0 (above); its findings are fixed in
|
|
6040
6381
|
0.44.1. It was an internal review, not an independent audit; it covered the token, Token-2022, Metaplex and Stake
|
|
6041
6382
|
wrappers, the oracles and SBPF v1/v2 builds of the examples that the review of 0.43.0 left out, but not the Metaplex
|
|
6042
|
-
wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. 0.45.0 to 0.
|
|
6383
|
+
wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. 0.45.0 to 0.51.0
|
|
6043
6384
|
have had no security review. They add, among others, `runtime/typesol_builtins.c` (the
|
|
6044
6385
|
compiler builtins as TypeSOL's own C, 0.45.0), `transferCheckedWithHook`, `EVENT_AUTHORITY_CHECK` and the reads of
|
|
6045
|
-
processed sibling instructions (0.48.0),
|
|
6386
|
+
processed sibling instructions (0.48.0), `zeroData`, `log64`,
|
|
6046
6387
|
`PANIC_STYLE = "solana-1.18"`, `executable` on remaining accounts and lamport writes on remaining accounts under
|
|
6047
|
-
`NATIVE_ACCOUNT_WRITES` (0.49.0)
|
|
6388
|
+
`NATIVE_ACCOUNT_WRITES` (0.49.0), `copyData`, `getReturnData()`, `PANIC_STYLE = "pinocchio"` and whole values
|
|
6389
|
+
copied and zeroed by the memory syscalls (0.50.0), and the base58 text of keys from a table, derivations without
|
|
6390
|
+
the run-time seed-limit check, object-type structs, `extends`, struct spreads, labels, logical assignment and the
|
|
6391
|
+
stack layout the build chooses for a program that does not fit (0.51.0). There has been no external audit: see [audit.md](audit.md).
|
|
6048
6392
|
|
|
6049
6393
|
<!-- docs/ai.md -->
|
|
6050
6394
|
|
|
@@ -6179,10 +6523,11 @@ arm64 has no Agave CLI, so there the package is set up by hand with `TYPESOL_SBF
|
|
|
6179
6523
|
[troubleshooting.md](troubleshooting.md#linux-arm64-the-agave-installer-fails-with-a-404)): for
|
|
6180
6524
|
SBPF v0 (the default), the 76 programs then in the sources (`scripts/release-manifest.ts`, every program under
|
|
6181
6525
|
`examples/` and `showcase/`); for SBPF v1 and v2, the 14 programs of `test/golden/binaries.json` (counter, vault,
|
|
6182
|
-
escrow, multisig and the 10 below). Programs added since were not measured on the three hosts, and
|
|
6183
|
-
divide 128-bit and wider integers, the Meteora DBC port (0.48.0; u128 and u256 division)
|
|
6184
|
-
(0.49.0; U256 and U512), are not in `test/golden/binaries.json`, so CI's
|
|
6185
|
-
(adding them needs the file regenerated in the `--docker` reference
|
|
6526
|
+
escrow, multisig and the 10 below). Programs added since were not measured on the three hosts, and three of them that
|
|
6527
|
+
divide 128-bit and wider integers, the Meteora DBC port (0.48.0; u128 and u256 division), the Percolator port
|
|
6528
|
+
(0.49.0; U256 and U512) and the Percolator v16 port (0.50.0; u256), are not in `test/golden/binaries.json`, so CI's
|
|
6529
|
+
cross-host check does not build them yet (adding them needs the file regenerated in the `--docker` reference
|
|
6530
|
+
environment).
|
|
6186
6531
|
|
|
6187
6532
|
| What | Same on the three hosts? |
|
|
6188
6533
|
| --- | --- |
|
|
@@ -6248,7 +6593,11 @@ Useful today, but may still change before 1.0 (each change listed in the CHANGEL
|
|
|
6248
6593
|
- Constant expressions (0.43.0): top-level integer constants folded from literals and earlier constants, a typed
|
|
6249
6594
|
one computed in its type.
|
|
6250
6595
|
- Comma-separated `for` updates and initializers (0.43.0).
|
|
6251
|
-
- Stack room (0.43.0): `/** @noinline */` helpers and `/** @heap */` locals.
|
|
6596
|
+
- Stack room (0.43.0): `/** @noinline */` helpers and `/** @heap */` locals. A program that does not fit the stack is
|
|
6597
|
+
laid out by the build (statements in blocks of their own, helpers kept out of line, an instruction's locals on the
|
|
6598
|
+
heap), with `STACK_AUTO`, `--stack-auto`, `/** @inline */` and `/** @stack */` to turn it off (unreleased). Which
|
|
6599
|
+
steps it takes, and so the bytes of a program that did not fit as written, may change between releases; a program
|
|
6600
|
+
that fits is never laid out.
|
|
6252
6601
|
- Local `FixedVec` / `FixedArray` lists of structs, `FixedVec.pushAll`, the instruction data as a list (`slice`,
|
|
6253
6602
|
`InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0); local FixedVecs given for read-only
|
|
6254
6603
|
`FixedVec<T, N>` / `Vec<T>` helper parameters (0.43.0).
|