@typesol/cli 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +397 -0
  2. package/NOTICE +9 -0
  3. package/README.md +25 -8
  4. package/SECURITY.md +4 -3
  5. package/dist/compiler/analyze.d.ts +2 -0
  6. package/dist/compiler/analyze.js +7 -1
  7. package/dist/compiler/emit/base.d.ts +4 -3
  8. package/dist/compiler/emit/base.js +9 -3
  9. package/dist/compiler/emit/borsh.js +8 -8
  10. package/dist/compiler/emit/calls.d.ts +6 -0
  11. package/dist/compiler/emit/calls.js +71 -12
  12. package/dist/compiler/emit/cpi-core.js +3 -3
  13. package/dist/compiler/emit/cpi.js +2 -2
  14. package/dist/compiler/emit/expressions.d.ts +1 -0
  15. package/dist/compiler/emit/expressions.js +12 -0
  16. package/dist/compiler/emit/function.js +12 -8
  17. package/dist/compiler/emit/program.js +8 -2
  18. package/dist/compiler/emit/rbtree.js +1 -1
  19. package/dist/compiler/emit/shared.d.ts +12 -2
  20. package/dist/compiler/emit/shared.js +26 -6
  21. package/dist/compiler/emit/statements.d.ts +8 -1
  22. package/dist/compiler/emit/statements.js +53 -5
  23. package/dist/compiler/emit/storage.js +12 -10
  24. package/dist/compiler/emit/views.js +1 -1
  25. package/dist/compiler/index.d.ts +15 -1
  26. package/dist/compiler/index.js +50 -9
  27. package/dist/keys.d.ts +12 -1
  28. package/dist/keys.js +57 -7
  29. package/dist/workspace.d.ts +8 -0
  30. package/dist/workspace.js +90 -15
  31. package/docker/deps/0.50.0.lock.json +1206 -0
  32. package/docs/architecture.md +1 -1
  33. package/docs/audit.md +13 -12
  34. package/docs/case-study-jito-mev.md +14 -14
  35. package/docs/case-study-marginfi.md +127 -127
  36. package/docs/case-study-multisig.md +16 -4
  37. package/docs/case-study-raydium-clmm.md +44 -28
  38. package/docs/case-study-raydium-cp-swap.md +18 -18
  39. package/docs/cli.md +4 -3
  40. package/docs/language-accounts.md +16 -10
  41. package/docs/language-basics.md +4 -1
  42. package/docs/language-builtins.md +4 -2
  43. package/docs/language-cpi.md +34 -0
  44. package/docs/language-native.md +50 -4
  45. package/docs/language-statements.md +2 -1
  46. package/docs/language-types.md +13 -3
  47. package/docs/runtime.md +19 -2
  48. package/docs/security-model.md +4 -3
  49. package/docs/stability.md +5 -4
  50. package/docs/testing.md +6 -2
  51. package/lib/typesol.d.ts +25 -3
  52. package/llms-full.txt +136 -31
  53. package/package.json +1 -1
  54. package/releases/0.49.0.json +857 -0
  55. package/runtime/typesol_builtins.c +47 -2
  56. package/runtime/typesol_rt.h +129 -3
package/docs/cli.md CHANGED
@@ -7,9 +7,9 @@ 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)). |
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). 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. 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
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. |
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. |
@@ -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. It warns, with the install commands, when the platform-tools that building needs are missing, and
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
 
@@ -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
- account) and its data is zeroed. The account is not used after it in the function, except its `key` (compile
202
- errors, or 2040 at run time in a helper given one account twice). `CloseTo<A, "dest">` does the same when the
203
- instruction succeeds ([constraints](#constraints)).
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. Refused on a struct with a
208
- growable `Vec` (its push / pop / clear size the account).
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, no rent moved (fund it first: `rentExempt(newSize)`), at most 10 KiB of growth
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
 
@@ -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`
@@ -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 (220 names, 233 declarations), grouped, with its declaration and the first sentence of its doc
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. |
@@ -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
@@ -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
- - `resizeAccount(account, size)` also takes a remaining account (`realloc(size, true)`: new bytes zeroed, at most
372
- 10 KiB past the size it had when the instruction started, 3016). That size is the one the entrypoint records in the
373
- account's record, as solana_program 1.14's does, only in programs that resize a remaining account.
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
@@ -115,7 +115,8 @@ export function edit(shape: Mut<Shape>): void {
115
115
  refused.
116
116
  - **Evaluation order**: operands and arguments are read left to right, as in JavaScript, even when a later one changes
117
117
  account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list
118
- callback writing it).
118
+ callback writing it). Built-ins too: `log64(a.count, bump(a), 0n, 0n, 0n)` logs the count before the bump, and
119
+ `require(a.count === n, codeOf(a))` tests the count before a helper computing the error code runs.
119
120
  - **Ternaries** run only the chosen branch: `const fee = vip ? 0n : 30n`. Between accounts too:
120
121
  `const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or
121
122
  `RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a
@@ -50,7 +50,9 @@ export function record(stats: Mut<Stats>, by: u64, change: i64): void {
50
50
  u8; convert with u64(...) etc.` Comparisons (`<`, `<=`, `===`, …) need equal types too.
51
51
  - **Every operation is checked.** `+ - * / % **` and their assignments (`+=` … `**=`) fail the instruction on
52
52
  overflow (5100) or division by zero (5101); `**` with a negative exponent fails as well (JavaScript throws there).
53
- Unlike JavaScript there are no silent wraps and no `Infinity`.
53
+ Unlike JavaScript there are no silent wraps and no `Infinity`. A signed type's minimum divided by -1 overflows, and
54
+ so does its remainder by -1 (`x % -1n` with an `i8` holding -128 fails with 5100, as Rust's checked `%` does, where
55
+ JavaScript gives 0); a typed constant computing it is a compile error ([constants](language-basics.md#constants)).
54
56
  - **Bitwise operators.** `& | ^` work on equal types; `~` flips the bits within the type's width (`~1n` as a `u8` is
55
57
  254). Both shifts fail (5100) when the amount is negative or not below the width (`x >> 64n` on a `u64`), and `<<`
56
58
  also when bits would be lost; `>>` is arithmetic on signed types. Unlike JavaScript, where a bigint shift never
@@ -300,8 +302,16 @@ export function step(player: Mut<Player>, dx: u64): void {
300
302
  order, back to back, with no padding.
301
303
  - A struct literal names every field (`{ x, y: 2n }`); a missing or unknown field is an error. An object literal needs
302
304
  a known struct type: a typed local (`const p: Point = { … }`), a field, a helper parameter, `emit<T>(…)`.
303
- - `a.home = b.home` copies the whole struct, as Rust and Anchor do; how `const` binds one is in
304
- [copies and references](language-statements.md#copies-and-references).
305
+ - `a.home = b.home` copies the whole struct, as Rust and Anchor do; how `const` binds one is in [copies and
306
+ references](language-statements.md#copies-and-references). A copy between places reached through pointers (account
307
+ data, a view, a helper's struct parameter) of 80 bytes or more is the memmove syscall (16 compute units up to 2,749
308
+ bytes, one more per 250 bytes past that), as Rust's memcpy is; below, 8-byte loads and stores (26 units for 80
309
+ 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
310
+ built in a temporary) takes the syscall from 400 bytes, where clang stops unrolling the loads and stores (and about
311
+ 1 unit a byte is the loop's cost): below that the optimizer drops what nothing reads, which a call would prevent.
312
+ The same holds wherever TypeSOL copies a whole value itself (Borsh fields, instruction arguments, a helper's copy of
313
+ a struct argument, events), and a value it zeroes whole (`x.o = null` on an `Option<struct>`, a data-enum literal)
314
+ takes the memset syscall from 192 bytes in account data and 600 in a local.
305
315
  - A struct cannot contain itself.
306
316
 
307
317
  ### File-local structs
package/docs/runtime.md CHANGED
@@ -9,7 +9,13 @@ Since 0.45.0 the runtime is no longer header-only: `runtime/typesol_builtins.c`
9
9
  `__divdi3`, …). It is compiled with every program by the same clang and linked after it, in place of platform-tools'
10
10
  `compiler-builtins` library, whose layout differed by host package
11
11
  ([stability.md](stability.md#what-builds-the-same-bytes-where)); `test/language/builtins.test.ts` checks it against
12
- BigInt and its compute units against compiler-builtins'.
12
+ BigInt and its compute units against compiler-builtins'. Multiplication and shifts are assembly written for the 128-bit
13
+ libcall convention of clang 20 (platform-tools v1.52) and earlier: the result's address in r1, the operands after it.
14
+ clang 22 (platform-tools v1.57) passes the operands from r1 and returns the result in registers, so for a clang above
15
+ 20 the file compiles C definitions of the same four functions instead (`TS_ASM_LIBCALLS`), which take whatever
16
+ convention that clang gives their C signatures; with the assembly, a program built by clang 22 stored its first
17
+ 128-bit product through the operand's low half ("Access violation writing 8 bytes at address …"). The test runs the C
18
+ definitions too, compiled by the tested clang as a clang above 20 would select them.
13
19
 
14
20
  ## Conventions
15
21
 
@@ -36,6 +42,17 @@ BigInt and its compute units against compiler-builtins'.
36
42
  - **No byte loops from the SDK.** The SDK's `sol_memcpy`, `sol_memcmp` and `SolPubkey_same` move one byte per
37
43
  iteration. The runtime uses `ts_ld64` / `ts_st64` (unaligned 8-byte loads and stores, which SBF allows) in
38
44
  `ts_memcpy`, `ts_memzero`, `ts_mem_eq`, `ts_key_eq` and `ts_memmove`.
45
+ - **The memory syscalls where they cost less.** `sol_memmove_` and `sol_memset_` cost about 16 and 14 compute units
46
+ whatever the length up to 2,749 bytes. Whole values of a size known when compiling are copied by `TS_COPY` from 80
47
+ bytes and zeroed by `TS_ZERO` from 192 between places reached through pointers (account data, views, a helper's
48
+ pointer parameters), where the unrolled loads and stores cost at least 10 units more. Where a side is a local of the
49
+ function, `TS_COPY_LOCAL` / `TS_MEMCPY` take the syscall from 400 bytes and `TS_ZERO_LOCAL` from 600, where clang
50
+ stops unrolling: below that the optimizer drops the stores and loads nothing reads (a struct literal built in place, a
51
+ helper's result read field by field), which a call would prevent. The size folds when compiling, so smaller copies
52
+ compile to exactly the code they were. Run-time lengths, always loops, take the syscall from 64 bytes: the bytes an
53
+ account grows by (`ts_memzero_run`, one unit more below 64) and an account's data at `close` (`TS_CLOSE`, decided from
54
+ the type's smallest size). The measured table is above these macros in `typesol_rt.h`. Copies always use memmove:
55
+ `sol_memcpy_` fails the transaction on overlapping ranges, which two views of one account can give.
39
56
  - **Same results as the reference.** Fast paths must give bit-identical results to what they replace: `ts_add_overflow_u64`
40
57
  matches `__builtin_add_overflow`, the rent fast path and `ts_rent_slow` match the double computation, PDA search
41
58
  matches `sol_try_find_program_address`. A change here needs a test against the reference, not only against itself.
@@ -47,7 +64,7 @@ In file order:
47
64
  | Section | What it provides |
48
65
  | --- | --- |
49
66
  | Error codes, `TS_FAIL`, `TS_TRY` | The codes above and the two macros |
50
- | Word-wise memory helpers | `ts_ld64`, `ts_st64`, `ts_memcpy`, `ts_memmove`, `ts_memzero`, `ts_mem_eq`; checked u64 add/subtract/multiply |
67
+ | Word-wise memory helpers | `ts_ld64`, `ts_st64`, `ts_memcpy`, `ts_memmove`, `ts_memzero`, `ts_mem_eq`; the memory syscalls past their thresholds (`TS_COPY`, `TS_MEMCPY`, `TS_ZERO`, `ts_memzero_run`); checked u64 add/subtract/multiply |
51
68
  | Well-known program ids | System, Token, Token-2022, ATA, Metaplex and the other programs the language names |
52
69
  | Strings | `TS_Str` views (pointer, length), UTF-8 validation, comparison, `FixedString<N>` storage |
53
70
  | Entry point input | `TsAccount` (the loader's serialized account, read in place), `TsParams`, `ts_deserialize` |
@@ -180,9 +180,10 @@ exposed to them.
180
180
  The compiler and runtime have had internal security reviews, the latest of 0.44.0 (above); its findings are fixed in
181
181
  0.44.1. It was an internal review, not an independent audit; it covered the token, Token-2022, Metaplex and Stake
182
182
  wrappers, the oracles and SBPF v1/v2 builds of the examples that the review of 0.43.0 left out, but not the Metaplex
183
- wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. 0.45.0 to 0.49.0
183
+ wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. 0.45.0 to 0.50.0
184
184
  have had no security review. They add, among others, `runtime/typesol_builtins.c` (the
185
185
  compiler builtins as TypeSOL's own C, 0.45.0), `transferCheckedWithHook`, `EVENT_AUTHORITY_CHECK` and the reads of
186
- processed sibling instructions (0.48.0), and `zeroData`, `log64`,
186
+ processed sibling instructions (0.48.0), `zeroData`, `log64`,
187
187
  `PANIC_STYLE = "solana-1.18"`, `executable` on remaining accounts and lamport writes on remaining accounts under
188
- `NATIVE_ACCOUNT_WRITES` (0.49.0). There has been no external audit: see [audit.md](audit.md).
188
+ `NATIVE_ACCOUNT_WRITES` (0.49.0), and `copyData`, `getReturnData()`, `PANIC_STYLE = "pinocchio"` and whole values
189
+ copied and zeroed by the memory syscalls (0.50.0). There has been no external audit: see [audit.md](audit.md).
package/docs/stability.md CHANGED
@@ -68,10 +68,11 @@ arm64 has no Agave CLI, so there the package is set up by hand with `TYPESOL_SBF
68
68
  [troubleshooting.md](troubleshooting.md#linux-arm64-the-agave-installer-fails-with-a-404)): for
69
69
  SBPF v0 (the default), the 76 programs then in the sources (`scripts/release-manifest.ts`, every program under
70
70
  `examples/` and `showcase/`); for SBPF v1 and v2, the 14 programs of `test/golden/binaries.json` (counter, vault,
71
- escrow, multisig and the 10 below). Programs added since were not measured on the three hosts, and two of them that
72
- divide 128-bit and wider integers, the Meteora DBC port (0.48.0; u128 and u256 division) and the Percolator port
73
- (0.49.0; U256 and U512), are not in `test/golden/binaries.json`, so CI's cross-host check does not build them yet
74
- (adding them needs the file regenerated in the `--docker` reference environment).
71
+ escrow, multisig and the 10 below). Programs added since were not measured on the three hosts, and three of them that
72
+ divide 128-bit and wider integers, the Meteora DBC port (0.48.0; u128 and u256 division), the Percolator port
73
+ (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
74
+ cross-host check does not build them yet (adding them needs the file regenerated in the `--docker` reference
75
+ environment).
75
76
 
76
77
  | What | Same on the three hosts? |
77
78
  | --- | --- |
package/docs/testing.md CHANGED
@@ -59,8 +59,12 @@ or later):
59
59
  from 0.45.0 on, of the runtime's compiler builtins);
60
60
  - the sha256 of the SBF binary, IDL and C that every program under `examples/`, `showcase/mainnet/` and
61
61
  `showcase/program-examples/` builds to (`scripts/release-manifest.ts`);
62
- - the sha256 of the reference binaries the differential tests run against (`test/programs/`);
63
- - a hash of the test corpus.
62
+ - the sha256 of the reference binaries the differential tests run against (`test/programs/`); the script refuses to
63
+ make a release manifest when `test/programs/SOURCES.md` lists a binary the tree lacks (with
64
+ `--allow-missing-references` it lists them under `referencesMissing` instead);
65
+ - a hash of the test corpus: every file under `test/` and `showcase/test/` (the directories the tests run from, the
66
+ mainnet ports' differential tests, helpers and fixtures included) but the reference binaries, with the directories
67
+ it covers (`corpus.roots`). Manifests before this change hashed `test/` alone.
64
68
 
65
69
  It also carries `typesol-<version>-binary-diff.txt` (older releases: `binary-diff.txt`): the previous release's sources built by the previous package and by this one,
66
70
  compared program by program. That is the check behind a changelog line such as "programs that use none of these compile to the
package/lib/typesol.d.ts CHANGED
@@ -1006,12 +1006,13 @@ export declare const AuthorityType: {
1006
1006
  * Resize an account of this program (Anchor `realloc`, struct accounts only): growing charges `payer` the extra rent
1007
1007
  * (never the account's own lamports, which may be deposits); shrinking keeps every lamport in the account — move
1008
1008
  * freed rent out yourself if your program allows it. At most 10 KiB of growth per instruction (3016); never below
1009
- * the struct size. Accounts ending in a Vec size themselves through push/pop/clear.
1009
+ * the struct size (3016; for a `@layout borsh` struct its smallest Borsh form, and the value written back must fit,
1010
+ * 3004). Accounts ending in a Vec size themselves through push/pop/clear.
1010
1011
  */
1011
1012
  export declare function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void;
1012
1013
  /**
1013
1014
  * Resize a `Mut<AccountInfo>` or a remaining account of this program to `newSize` bytes (Rust's `AccountInfo::resize` /
1014
- * `realloc(newSize, true)`): the data length only, the new bytes zeroed. No rent moves: fund the account first
1015
+ * `realloc(newSize, true)`): the data length only, the new bytes zeroed (64 or more by the memset syscall). No rent moves: fund the account first
1015
1016
  * (`rentExempt(newSize)`), the runtime refuses an account left short. At most 10 KiB past its size when the
1016
1017
  * instruction started (3016). A remaining account must be writable (3006) unless the program declares
1017
1018
  * `NATIVE_ACCOUNT_WRITES`, which also lets an `AccountInfo` parameter be resized without `Mut<…>`. A view of the
@@ -2491,7 +2492,9 @@ export declare enum ProgramError {
2491
2492
  * Under `export const PANIC_STYLE = "solana-1.14"` (a program built with solana-program 1.14 to 1.17) it logs
2492
2493
  * `panicked at '<message>', <location>` and aborts, so the runtime reports "SBF program panicked", as that panic
2493
2494
  * handler does; under `"solana-1.18"` (rustc 1.73 and later) it logs `panicked at <location>:` with the message on the
2494
- * next line, in one log line, and aborts. A message is then required.
2495
+ * next line, in one log line, and aborts. A message is then required. Under `"pinocchio"` (pinocchio's
2496
+ * `entrypoint!` panic hook) it logs the location's file alone, then `** PANICKED **`, and aborts: the message is not
2497
+ * logged (it may be null), and `location` may be the file alone (`"src/v16.rs"`).
2495
2498
  */
2496
2499
  export declare function panic(message?: string | null, location?: string): never;
2497
2500
  /**
@@ -2570,6 +2573,16 @@ export declare function emit<T>(event: T): void;
2570
2573
  */
2571
2574
  export declare function returnData<T extends bigint | boolean | Pubkey | Hash | object>(program: AccountMeta): T;
2572
2575
 
2576
+ /**
2577
+ * The return data as the runtime holds it, of any length and from any program (Rust's `get_return_data()`), for a
2578
+ * port that checks it itself: `const [program, data] = getReturnData()`. `program` is the program that set it and
2579
+ * `data` its bytes (up to 1,024, the runtime's maximum), read with the methods of instruction data
2580
+ * (`data.length`, `data.readU64(8n)`, `data.slice(a, b)`). Rust's `None` is `data.length === 0n` (the runtime keeps
2581
+ * no empty return data), `program` then all zeros. Nothing is checked: compare `program` and the length yourself,
2582
+ * failing with your own errors. The bytes take 1 KiB of the calling function's stack frame.
2583
+ */
2584
+ export declare function getReturnData(): [program: Pubkey, data: InstructionBytes];
2585
+
2573
2586
  /**
2574
2587
  * Set this instruction's return data to `bytes` as they are (Rust's `set_return_data(&bytes)`): a list of u8 such as a
2575
2588
  * local `FixedVec<u8, N>`, a Vec or FixedVec in account data, or the instruction data or a slice of it. For a native
@@ -2602,6 +2615,15 @@ export declare function log64(a: u64, b: u64, c: u64, d: u64, e: u64): void;
2602
2615
  */
2603
2616
  export declare function zeroData(account: RemainingAccount | Mut<AccountInfo>, offset: u64, length: u64): void;
2604
2617
 
2618
+ /**
2619
+ * Copy `length` bytes of an account's data from offset `from` to offset `to`, as a native program's
2620
+ * `data.copy_within(from..from + length, to)` (or a struct copied out of the account and written back at another
2621
+ * offset): the memmove syscall, about constant compute units whatever the length; the ranges may overlap. A remaining
2622
+ * account (or a `Mut<AccountInfo>` parameter); a range past the end of the data fails with 3003 and copies nothing.
2623
+ * Only this program's accounts can change: check the owner first.
2624
+ */
2625
+ export declare function copyData(account: RemainingAccount | Mut<AccountInfo>, from: u64, to: u64, length: u64): void;
2626
+
2605
2627
  /**
2606
2628
  * Verify `account.key` is the PDA for `seeds` + `bump` under this program. Any bump that gives a PDA passes (Anchor's
2607
2629
  * `bump = expr`): use a stored bump, not one from the arguments, or the caller picks among up to 256 addresses.