@typesol/cli 0.43.0 → 0.44.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 (64) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/NOTICE +71 -0
  3. package/README.md +25 -11
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +4 -0
  9. package/dist/compiler/emit/alias.d.ts +1 -1
  10. package/dist/compiler/emit/alias.js +10 -4
  11. package/dist/compiler/emit/base.d.ts +3 -1
  12. package/dist/compiler/emit/base.js +20 -3
  13. package/dist/compiler/emit/borsh.js +11 -5
  14. package/dist/compiler/emit/calls.d.ts +13 -0
  15. package/dist/compiler/emit/calls.js +91 -8
  16. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  17. package/dist/compiler/emit/cpi-core.js +35 -7
  18. package/dist/compiler/emit/create.js +3 -0
  19. package/dist/compiler/emit/expressions.js +6 -1
  20. package/dist/compiler/emit/function.js +10 -0
  21. package/dist/compiler/emit/shared.d.ts +17 -0
  22. package/dist/compiler/emit/shared.js +36 -3
  23. package/dist/compiler/emit/statements.js +17 -4
  24. package/dist/compiler/emit/storage.d.ts +2 -0
  25. package/dist/compiler/emit/storage.js +16 -8
  26. package/dist/compiler/index.d.ts +15 -1
  27. package/dist/compiler/index.js +40 -3
  28. package/dist/compiler/toolchain.d.ts +41 -1
  29. package/dist/compiler/toolchain.js +102 -3
  30. package/dist/testing-stake.d.ts +2 -1
  31. package/dist/testing-stake.js +2 -1
  32. package/dist/testing.js +6 -4
  33. package/dist/tools/clientgen.d.ts +15 -0
  34. package/dist/tools/clientgen.js +173 -7
  35. package/dist/tools/cpigen.d.ts +0 -15
  36. package/dist/tools/cpigen.js +19 -8
  37. package/dist/tools/doctor.d.ts +17 -2
  38. package/dist/tools/doctor.js +64 -4
  39. package/dist/tools/portgen.js +43 -18
  40. package/dist/workspace.d.ts +20 -0
  41. package/dist/workspace.js +173 -6
  42. package/docs/ai.md +10 -5
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +63 -17
  45. package/docs/case-study-escrow.md +1 -1
  46. package/docs/case-study-phoenix.md +10 -10
  47. package/docs/case-study-raydium-amm.md +3 -3
  48. package/docs/case-study-spl-stake-pool.md +5 -5
  49. package/docs/cli.md +17 -8
  50. package/docs/client.md +11 -3
  51. package/docs/errors.md +1 -1
  52. package/docs/language.md +10 -5
  53. package/docs/mainnet.md +21 -10
  54. package/docs/migrate-from-anchor.md +2 -1
  55. package/docs/runtime.md +11 -1
  56. package/docs/security-model.md +38 -6
  57. package/docs/stability.md +21 -2
  58. package/docs/testing.md +25 -0
  59. package/docs/troubleshooting.md +12 -0
  60. package/llms-full.txt +168 -52
  61. package/llms.txt +1 -1
  62. package/package.json +3 -1
  63. package/runtime/typesol_rt.h +22 -13
  64. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/docs/audit.md CHANGED
@@ -7,26 +7,29 @@ with TypeSOL are out of scope; their authors audit them.
7
7
 
8
8
  ## Scope
9
9
 
10
- In order of priority. Line counts at 0.40.0 (November 2026).
10
+ In order of priority. Line counts at 0.43.0 (November 2026).
11
11
 
12
12
  | Priority | Component | Files | Lines | Why |
13
13
  | --- | --- | --- | ---: | --- |
14
- | 1 | C runtime | `runtime/typesol_rt.h` | 2,510 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
- | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 870 | Which checks each account parameter gets, and their order |
16
- | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 2,802 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
17
- | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 4,084 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
14
+ | 1 | C runtime | `runtime/typesol_rt.h` | 2,995 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
+ | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 879 | Which checks each account parameter gets, and their order |
16
+ | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 3,742 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
17
+ | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 5,633 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
18
+ | 1 | Raw views and the red-black tree | `src/compiler/emit/views.ts`, `rbtree.ts` | 655 | Accounts read without a discriminator at run-time offsets (`loadRaw`, `loadRawAt`, `rawArrayAt`, `BigVec`), their bounds, and the red-black tree's node indexes (`rbTreeAt`) |
18
19
  | 1 | Metaplex CPIs | `src/compiler/emit/metaplex.ts` | 1,454 | Token Metadata, Core and Bubblegum instruction layouts and their account lists |
19
- | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 1,820 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
20
- | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 2,930 | What the language accepts; constraints and account types as parsed from the source |
21
- | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,316 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
20
+ | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 2,088 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
21
+ | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 3,486 | What the language accepts; constraints and account types as parsed from the source |
22
+ | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,460 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
22
23
  | 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, deploy and verification commands |
23
24
 
24
- The language surface is `lib/typesol.d.ts` (2,163 lines): every type and built-in a program can use, with its
25
+ The language surface is `lib/typesol.d.ts` (2,581 lines): every type and built-in a program can use, with its
25
26
  documented behavior. [docs/language.md](language.md) is the reference; [docs/architecture.md](architecture.md) maps
26
27
  the code, [docs/runtime.md](runtime.md) the runtime's conventions.
27
28
 
28
29
  Out of scope: the Solana runtime, platform-tools (clang, lld), the TypeScript compiler, and programs written with
29
- TypeSOL.
30
+ TypeSOL. The platform-tools are part of what a binary trusts all the same: the tests cover the toolchain the release
31
+ declares (`TESTED_TOOLCHAIN` in `src/compiler/toolchain.ts`: Agave 3.1.10, platform-tools v1.52), builds with another
32
+ one warn, and the review of 0.43.0 traced one defect to how that backend passes struct arguments.
30
33
 
31
34
  ## What to check
32
35
 
@@ -48,14 +51,57 @@ accepts. Areas where a bug would be most damaging, and where earlier internal re
48
51
 
49
52
  ## Earlier reviews
50
53
 
51
- Internal reviews, by the maintainers, in October 2026. Their findings and fixes are in the CHANGELOG. The releases
52
- after 0.25.0 (0.26.0 to 0.40.0) have had no review of this kind yet; they add, among others, `u256`, big-endian seeds
54
+ Internal reviews, by the maintainers: none of them is an independent audit. Their findings and fixes are in the
55
+ CHANGELOG.
56
+
57
+ ### 0.43.0 (2026-11-11)
58
+
59
+ An internal review of 0.43.0 as published. It probed the compiler's semantics with targeted programs (helpers,
60
+ references, closures, seeds, `close()`, Borsh decoding), read the runtime header and the C generated for those
61
+ programs, and exercised the tooling (the CLI commands and `typesol/testing`). It did not cover the emitters of the
62
+ Metaplex and token CPI wrappers, the oracles, builds for SBPF v1 and v2, or Windows.
63
+
64
+ Defects found, fixed in 0.44.0 (its CHANGELOG section, with a test
65
+ for each):
66
+
67
+ - **Helper arguments were not copies.** A Pubkey, Option, string or u256 argument reaches a helper as a pointer to the
68
+ caller's object (that is how the SBF backend passes it), so a helper that was not inlined and wrote that object read
69
+ its own write through the parameter: an authorization check on the old value (`rotate(v, v.admin, caller)` with
70
+ `v.admin = v.pending` inside) passed on the new one. Whether it happened depended on clang's inlining.
71
+ - **Seed lists were read at the CPI instead of where they are written.** A list bound to a name, given to a helper,
72
+ or written beside an argument with side effects read its seeds when the CPI ran, so after `st.count += 1n` the
73
+ program signed for another PDA than the one the source names.
74
+ - **The reference rule was skipped for account-group fields and loaded accounts.** A reference into an account used
75
+ after a helper that may move the account's data is refused; it was not when the account reached the helper as an
76
+ account-group field or had been loaded with `loadAccountMut`, and such a program wrote through the stale reference.
77
+ - **Borsh length checks wrapped.** The decoder subtracted before comparing, so for an `Option` of a struct holding an
78
+ Option (or a Vec of such structs) a short buffer wrapped the subtraction and the read went past the end of the
79
+ input: bounded by the struct's size, and read only.
80
+ - **Evaluation order with closures.** A local read before a closure or list callback that changes it kept the new
81
+ value instead of the one it had when read; a string viewing text inside an `Inout` place was not copied for the
82
+ helper taking the place.
83
+ - **`close()` gaps.** Closing an account into itself compiled, `Dup<…>` was accepted on an account the body closes,
84
+ and an account could be used after `close()` in the same instruction (its writes were dropped).
85
+ - **Tooling: IDL text reached generated code unvalidated.** `typesol cpi` and `typesol port` wrote names and other text
86
+ from the IDL they were given into the TypeScript they generate without the checks `typesol client` makes.
87
+
88
+ Programs built with 0.43.0 or earlier should be rebuilt with 0.44.0 or later and redeployed. The first defect is
89
+ the one that can break an authorization check; [security-model.md](security-model.md#review-of-0430-2026-11-11)
90
+ says how to tell whether a program was exposed to it.
91
+
92
+ ### Before 0.43.0
93
+
94
+ Internal reviews in October 2026. The releases from 0.26.0 to 0.42.0 were not reviewed one by one: the 0.43.0 review
95
+ read the code that includes them, but probed only the areas above. They add, among others, `u256`, big-endian seeds
53
96
  and accounts loaded in the body (0.37.0), stored bumps in nested fields and error members without messages (0.38.0),
54
97
  `@code`, `@repr` / `@serialization`, `@bytes` / `@idlName`, `f64`, Options inside Options in arguments and events,
55
98
  loop-scoped `loadAccountMut` with `Dup<T>`, account resizing and raw writes, `systemProgram.createPda` (0.39.0), and
56
99
  the native-program surface: `loadRaw` / `loadRawMut` (accounts without a discriminator), instruction data readers,
57
- error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0). An external review should include them;
58
- the native-program surface first, since it skips the account checks Anchor-style parameters get.
100
+ error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0), the agent tooling (`typesol mcp`, 0.41.0),
101
+ Borsh accounts without a discriminator, `BigVec<T>`, typed CPIs on remaining accounts and the Stake program's CPIs
102
+ (0.42.0), views at run-time offsets (`loadRawAt`, `rawArrayAt`), the built-in red-black tree (`rbTreeAt`), `Inout<T>`
103
+ helper parameters and `closeRaw` (0.43.0). An external review should include them; the native-program surface first,
104
+ since it skips the account checks Anchor-style parameters get, and the areas the 0.43.0 review did not cover.
59
105
 
60
106
  - **0.25.0** (runtime and emitted checks): two Medium issues fixed, a remaining account loaded mutably twice through
61
107
  the same slot, and a Vec element written after its right side resized the Vec; plus a token program ambiguity,
@@ -67,8 +113,8 @@ the native-program surface first, since it skips the account checks Anchor-style
67
113
 
68
114
  ## Evidence
69
115
 
70
- - **Tests**: by subject under `test/` (`docs/architecture.md`); the count of each run is in CI's log (727 on main on
71
- 2026-11-01). `test/security/` holds the attacks.
116
+ - **Tests**: by subject under `test/` (`docs/architecture.md`); the count of each run is in CI's log.
117
+ `test/security/` holds the attacks.
72
118
  - **Differential tests**: the same transactions to TypeSOL and to Anchor twins (`test/anchor-twins`), comparing
73
119
  outcomes, account contents and balances after every step.
74
120
  - **Model-based fuzzing** (`test/verification/`): arithmetic against BigInt at every width, `u256` against BigInt,
@@ -93,7 +139,7 @@ git clone https://github.com/typesol-lang/typesol && cd typesol
93
139
  pnpm install && pnpm build
94
140
  pnpm fetch:programs # Metaplex binaries for the token-metadata, Core and Bubblegum tests
95
141
  pnpm build:twins # the Anchor twins (Rust + Anchor 1.0.2)
96
- pnpm test # everything; CI runs it on Ubuntu (Node 22, 24) per change, macOS daily
142
+ pnpm test # everything; CI runs it on Ubuntu (Node 22, 24) per change, macOS on demand (macos.yml)
97
143
  pnpm fuzz # the randomized checks, wide
98
144
  ```
99
145
 
@@ -212,7 +212,7 @@ with their Solscan links in the [performance report](https://typesol.com/report/
212
212
 
213
213
  The steps this port followed, in order:
214
214
 
215
- 1. Generate the skeleton from the Anchor IDL: `npx typesol port target/idl/escrow.json --out programs/escrow.ts`. It
215
+ 1. Generate the skeleton from the Anchor IDL: `npx @typesol/cli port target/idl/escrow.json --out programs/escrow.ts`. It
216
216
  keeps instruction names, discriminators, account order and error codes.
217
217
  2. Turn each `#[account(...)]` into the parameter's type, using the table above and
218
218
  [Accounts and constraints](migrate-from-anchor.md#accounts-and-constraints). Keep the account order: it is the
@@ -10,7 +10,7 @@ rebuild.
10
10
  deployed executable's hash (`6877a5b732b3494b828a324ec846d526d962223959534dbaf4209e0da3b2d6a9`); OtterSec's
11
11
  verification registry lists the program as verified from that commit. The repository was under BUSL 1.1 at c16694d;
12
12
  on 2026-05-11 Ellipsis Labs relicensed it under the MIT License (5a34f7f) with the program's sources unchanged since
13
- c16694d, so the port follows c16694d under MIT ([`test/programs/SOURCES.md`](../test/programs/SOURCES.md)).
13
+ c16694d, so the port follows c16694d under MIT ([`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)).
14
14
 
15
15
  Phoenix is a native program built with solana-program 1.14: a u8 tag, the instruction's Borsh arguments after it,
16
16
  accounts by position. A market is one account: a 576-byte header, then a `FIFOMarket` whose bids, asks and traders are
@@ -22,11 +22,11 @@ Rust panics in solana-program 1.14's format, at the original's source locations.
22
22
 
23
23
  | File | Holds |
24
24
  | --- | --- |
25
- | [`phoenix.ts`](../showcase/mainnet/phoenix/phoenix.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`): the four accounts every instruction starts with, the event recorder, dispatch to the 28 tags |
26
- | [`state.ts`](../showcase/mainnet/phoenix/state.ts), [`errors.ts`](../showcase/mainnet/phoenix/errors.ts) | MarketHeader, the FIFOMarket prefix, the tree keys and values, Seat, PhoenixMarketEvent, the instruction arguments, PhoenixError from code 0 |
27
- | [`checkers.ts`](../showcase/mainnet/phoenix/checkers.ts), [`util.ts`](../showcase/mainnet/phoenix/util.ts) | the account checks in the original's order, the market loader with its twelve sizes; PDAs, the quantity operators with their panics, the token CPIs |
28
- | [`recorder.ts`](../showcase/mainnet/phoenix/recorder.ts) | the event recorder: batches of events sent in Log self-CPIs whenever the next event would not fit |
29
- | [`matching.ts`](../showcase/mainnet/phoenix/matching.ts), [`book.ts`](../showcase/mainnet/phoenix/book.ts) | the FIFOMarket: place_order_inner, match_order, check_for_cross, eviction; reduce_order_inner and the cancels built on it |
25
+ | [`phoenix.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/phoenix.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`): the four accounts every instruction starts with, the event recorder, dispatch to the 28 tags |
26
+ | [`state.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/state.ts), [`errors.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/errors.ts) | MarketHeader, the FIFOMarket prefix, the tree keys and values, Seat, PhoenixMarketEvent, the instruction arguments, PhoenixError from code 0 |
27
+ | [`checkers.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/checkers.ts), [`util.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/util.ts) | the account checks in the original's order, the market loader with its twelve sizes; PDAs, the quantity operators with their panics, the token CPIs |
28
+ | [`recorder.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/recorder.ts) | the event recorder: batches of events sent in Log self-CPIs whenever the next event would not fit |
29
+ | [`matching.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/matching.ts), [`book.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/book.ts) | the FIFOMarket: place_order_inner, match_order, check_for_cross, eviction; reduce_order_inner and the cancels built on it |
30
30
  | `orders.ts`, `cancel.ts`, `initialize.ts`, `governance.ts`, `seats.ts`, `funds.ts`, `fees.ts` | the instructions by subject |
31
31
 
32
32
  ## What is ported
@@ -82,7 +82,7 @@ compile to the same C as before:
82
82
  ## How it is checked
83
83
 
84
84
  The mainnet binary and the port run in two LiteSVMs under the same program id and the same Clock
85
- ([`phoenix-helpers.ts`](../showcase/test/phoenix-helpers.ts)). Every account is made the same way in both, and every
85
+ ([`phoenix-helpers.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/phoenix-helpers.ts)). Every account is made the same way in both, and every
86
86
  transaction must give:
87
87
 
88
88
  - the same outcome;
@@ -110,7 +110,7 @@ file fails unless it compares exactly its own count):
110
110
  one instruction, the out-of-memory abort at the 513th, books of up to 8,000 orders, the overflow and division panics.
111
111
  - **The original's own tests** (`phoenix-upstream.test.ts`; 1,082): each of the 50 test functions at c16694d (the
112
112
  integration tests, the matching engine's unit tests, the packet decoder's) is mapped to a case
113
- ([the mapping](../showcase/test/phoenix-upstream.md)): 11 were covered already, 37 are added there and run whole,
113
+ ([the mapping](https://github.com/typesol-lang/typesol/blob/main/showcase/test/phoenix-upstream.md)): 11 were covered already, 37 are added there and run whole,
114
114
  2 are not applicable (compile-time type checks of the quantity macros). Each refusal the upstream test expects is
115
115
  pinned to the original's error and message, and the upstream test's own assertions (balances, the book, free lots,
116
116
  the sequence number, fees) are made on chain.
@@ -180,7 +180,7 @@ What the port does not reproduce, and how a transaction would reach it:
180
180
  original out of its compute budget can complete in the port; the tests give both enough.
181
181
  - **Memory, counted.** Phoenix allocates on solana-program 1.14.9's bump heap: 32 KiB from the top down, never freed,
182
182
  and an allocation past it aborts with "Error: memory allocation failed, out of memory". The port keeps its own lists
183
- fixed and counts Phoenix's heap instead ([`heap.ts`](../showcase/mainnet/phoenix/heap.ts)), charge by charge as the
183
+ fixed and counts Phoenix's heap instead ([`heap.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/phoenix/heap.ts)), charge by charge as the
184
184
  Rust allocates: the entrypoint's 48 bytes per account entry and 72 per distinct account, the discriminant lines, the
185
185
  event recorder, the status checks' messages (built even when they pass), each batch line, each SPL Token transfer's
186
186
  instruction, the cancels' boxed tree iterators with their stacks and the ids they collect, CancelMultipleOrdersById's
@@ -188,7 +188,7 @@ What the port does not reproduce, and how a transaction would reach it:
188
188
  runs) and the "Insufficient funds" lines of the orders it skips, the placed order ids and their Borsh bytes. So a
189
189
  transaction that fills the heap (with up to 255 account entries, which Phoenix ignores past the ones it reads, or with
190
190
  a CPI's larger instruction data) aborts in the port at the same allocation, after the same log lines and batches.
191
- [`phoenix-limits.test.ts`](../showcase/test/phoenix-limits.test.ts) finds the original's boundary and compares both
191
+ [`phoenix-limits.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/phoenix-limits.test.ts) finds the original's boundary and compares both
192
192
  sides of it (one account entry fewer succeeds, the next aborts) for CancelAllOrders and its free-funds form (257 to
193
193
  512 orders, bids and asks, 4 to 20 accounts of their own, top-level and through a CPI), CancelUpTo with a count and
194
194
  with a search limit, ForceCancelOrders, CancelMultipleOrdersById through a CPI (230 and 340 entries; 341 always runs
@@ -11,9 +11,9 @@ its own errors. The port keeps all of that.
11
11
 
12
12
  | File | Holds |
13
13
  | --- | --- |
14
- | [`raydium_amm.ts`](../showcase/mainnet/raydium-amm/raydium_amm.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`), every instruction, the token and system CPIs, the P&L calculation |
15
- | [`state.ts`](../showcase/mainnet/raydium-amm/state.ts) | AmmInfo (752 bytes), TargetOrders, AmmConfig, Fees, the ray_log records, the 61 errors (codes 0–60) |
16
- | [`math.ts`](../showcase/mainnet/raydium-amm/math.ts) | decimal normalization, the constant-product amounts, the exchange rates, with the original's panics at their places |
14
+ | [`raydium_amm.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-amm/raydium_amm.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`), every instruction, the token and system CPIs, the P&L calculation |
15
+ | [`state.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-amm/state.ts) | AmmInfo (752 bytes), TargetOrders, AmmConfig, Fees, the ray_log records, the 61 errors (codes 0–60) |
16
+ | [`math.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-amm/math.ts) | decimal normalization, the constant-product amounts, the exchange rates, with the original's panics at their places |
17
17
 
18
18
  ## What is ported
19
19
 
@@ -10,7 +10,7 @@ deployed code carries a fee-cap message main only gained later. The tag `program
10
10
  branch) rebuilt with `solana-verify build --library-name spl_stake_pool --base-image
11
11
  solanafoundation/solana-verifiable-build:3.1.14` gives the deployed executable's hash
12
12
  (`8df58bc9f9428c02bf34fa845ae2961274156e7ff07a8dc1be0018dd765baeff`). The port follows that tag
13
- ([`test/programs/SOURCES.md`](../test/programs/SOURCES.md)).
13
+ ([`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)).
14
14
 
15
15
  Stake Pool is a native program: one entrypoint decodes a Borsh instruction (a tag byte, then the variant's fields,
16
16
  every byte consumed), the processor takes its accounts by position, the pool account is plain Borsh with Options and
@@ -19,9 +19,9 @@ data enums, the validator list is a header and a `BigVec` of 73-byte entries ove
19
19
 
20
20
  | File | Holds |
21
21
  | --- | --- |
22
- | [`stake_pool.ts`](../showcase/mainnet/spl-stake-pool/stake_pool.ts) | the entrypoint: the instruction decoded as `try_from_slice` does, dispatch to the 27 instructions |
23
- | [`state.ts`](../showcase/mainnet/spl-stake-pool/state.ts), [`errors.ts`](../showcase/mainnet/spl-stake-pool/errors.ts) | StakePool (Borsh, 611 bytes at most), ValidatorList with its `BigVec<ValidatorStakeInfo>`, the stake account layout, StakePoolError from code 0 |
24
- | [`util.ts`](../showcase/mainnet/spl-stake-pool/util.ts) | PDAs, fee arithmetic, the pool-token and lamport conversions, token account and mint checks (Token-2022 extensions included), the stake CPIs as solana_program's builders make them |
22
+ | [`stake_pool.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/spl-stake-pool/stake_pool.ts) | the entrypoint: the instruction decoded as `try_from_slice` does, dispatch to the 27 instructions |
23
+ | [`state.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/spl-stake-pool/state.ts), [`errors.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/spl-stake-pool/errors.ts) | StakePool (Borsh, 611 bytes at most), ValidatorList with its `BigVec<ValidatorStakeInfo>`, the stake account layout, StakePoolError from code 0 |
24
+ | [`util.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/spl-stake-pool/util.ts) | PDAs, fee arithmetic, the pool-token and lamport conversions, token account and mint checks (Token-2022 extensions included), the stake CPIs as solana_program's builders make them |
25
25
  | `admin.ts`, `validators.ts`, `update.ts`, `sol.ts`, `stake_deposit.ts`, `stake_withdraw.ts`, `rebalance.ts`, `metadata.ts` | the instructions by subject |
26
26
 
27
27
  ## What is ported
@@ -66,7 +66,7 @@ bytes in every account it names. There are 2,107 such transactions in six files:
66
66
  authorities, read-only and repeated accounts (the original's RefCell panics included), pools of 50 to 60 validators,
67
67
  warmup and cooldown over several epochs.
68
68
  - **The original's own tests** (`spl-stake-pool-upstream.test.ts`; 701): each of the 221 test functions in
69
- `program/tests` at the tag is mapped to a case ([the mapping](../showcase/test/spl-stake-pool-upstream.md)): 143
69
+ `program/tests` at the tag is mapped to a case ([the mapping](https://github.com/typesol-lang/typesol/blob/main/showcase/test/spl-stake-pool-upstream.md)): 143
70
70
  were covered already, 78 are added there, none is left out. huge_pool.rs runs at 3,000 and 20,000 validators.
71
71
  - **A random walk over epochs** (`spl-stake-pool-fuzz.test.ts`): validators added and removed, users depositing and
72
72
  withdrawing SOL and stake, rebalancing, updates in random chunks, fee and authority changes, rewards, slow warmup,
package/docs/cli.md CHANGED
@@ -6,24 +6,33 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
6
6
 
7
7
  | Command | What it does |
8
8
  | --- | --- |
9
- | `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin), `.vscode/settings.json` (the workspace TypeScript, so the plugin loads) and `.gitignore`. `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
9
+ | `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin), `.vscode/settings.json` (the workspace TypeScript, so the plugin loads), `.gitignore`, the rules for AI coding agents (`AGENTS.md`, `CLAUDE.md` importing it, `.cursor/rules/typesol.mdc`) and the MCP server configuration (`.mcp.json`, `.cursor/mcp.json`; see [ai.md](ai.md)). `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
10
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. |
11
- | `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools, the Solana CLI, 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. 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] [--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 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. |
13
- | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. A project program's `.ts` builds as that program. |
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 }] }`; `--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). |
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, 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. 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] [--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. |
13
+ | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--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
+ | `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`, always (a missing file or unreadable `--files` input is a diagnostic too, exit 1 or 2); `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
15
15
  | `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
16
16
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
17
- | `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …]` | Build, then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. Before sending anything it checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
18
- | `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`). |
17
+ | `typesol mcp` | Serve the Model Context Protocol on stdio for AI coding agents: tools to check a program (errors with hints), read its IDL, search the docs and read the rules a TypeSOL program follows. The `.mcp.json` / `.cursor/mcp.json` that `init` writes start it as `npx --no-install typesol mcp` (the project's own copy); see [ai.md](ai.md). |
18
+ | `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …] [--toolchain-strict]` | Build (`--toolchain-strict` as for `build`), then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. It needs a cluster, `--url` or `json_rpc_url` in the Solana CLI config: it never falls back to the CLI's default. Before sending anything it prints the cluster's host and the payer, checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
19
+ | `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`); it prints the cluster's host and the payer before sending. |
19
20
  | `typesol cpi <idl.json> [--out <file.ts>] [--prefix <name>] [--address <base58>]` | Generate TypeSOL helpers that call another program from its IDL. Unsupported instructions are listed on stderr. |
20
21
  | `typesol port <idl.json> [--out <file.ts>]` | A TypeSOL program skeleton from an Anchor IDL (0.30+/1.x), to port an Anchor program: account structs, enums, errors, events and one function per instruction with its accounts and arguments, each body `require(false, …NotPorted)` until written. Instruction discriminators (an explicit `@discriminator` when the name derives another), account names and error codes are kept, so existing clients keep working where the layouts match; notes on stderr list where they do not (Borsh `String`/`Option` in account data, a `Vec` that is not the last field). Error codes that skip ahead are kept with `@code`, and zero-copy types keep their IDL `repr`, `serialization` and field names (`@repr`, `@serialization`, `@idlName`). |
21
22
  | `typesol client <idl.json> [--out <file.ts>] [--address <base58>]`, `typesol client --address <program id> [--url <rpc>] [--config <cli config>] [--out <file.ts>]` | Generate a typed TypeScript client on `@solana/kit` from an Anchor IDL (0.30+/1.x or TypeSOL); the IDL is validated first, and what the client leaves out is printed as notes. Without a file, the IDL is read from the chain: the canonical Program Metadata IDL, else Anchor's IDL account. See [client.md](client.md). |
22
- | `typesol verify <program\|file.ts> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <cli config>] [--sbpf …]` | Rebuild and compare with what is deployed. Without a `.so`, reads the program from the cluster (`--url`, cluster monikers such as `mainnet-beta` included, else the Solana CLI config) at `--address` or the address `typesol.json` records, under any loader (v2, upgradeable v3, v4); prints the upgrade authority (or that the program is immutable) and the last deploy slot, and compares the IDL published with `typesol idl publish` (a published IDL that differs is a mismatch). With a `.so` (e.g. `solana program dump`), compares with that file. Trailing zero padding is ignored; the SBPF version is read from the deployed ELF unless `--sbpf` is given. |
23
+ | `typesol verify <program\|file.ts> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <cli config>] [--sbpf …] [--manifest <name.build.json>]` | Rebuild and compare with what is deployed. Without a `.so`, reads the program from the cluster (`--url`, cluster monikers such as `mainnet-beta` included, else the Solana CLI config) at `--address` or the address `typesol.json` records, under any loader (v2, upgradeable v3, v4); prints the upgrade authority (or that the program is immutable) and the last deploy slot, and compares the IDL published with `typesol idl publish` (a published IDL that differs is a mismatch). With a `.so` (e.g. `solana program dump`), compares with that file. Trailing zero padding is ignored; the SBPF version is read from the deployed ELF unless `--sbpf` is given. On a mismatch it prints the rebuild's toolchain (clang, platform-tools, host, TypeSOL) and the deployed build's when a build manifest's binary hash is the deployed bytes' (`--manifest`, `<deployed>.build.json` next to a given `.so`, or the local build's), and what differs; otherwise it says the deployed side's toolchain is unknown (a program on chain records none). |
23
24
  | `typesol profile <logs.txt\|-> [--program <id>]` | Compute units per TypeScript line from the logs of a `--profile` build's transaction (exit 1 when the logs have no markers). |
24
25
  | `typesol help <command>` | Same as `typesol <command> --help`. |
25
26
  | `typesol --version` | Print the version. |
26
27
 
28
+ `clone`, `client --address`, `verify` and `idl publish` give up on an RPC request after 30 seconds
29
+ (`TYPESOL_RPC_TIMEOUT=<seconds>` changes it) and, like `doctor` and `deploy`, name only the RPC's host and the cause
30
+ when one fails (an RPC URL can carry an API key). A `--config` file that does not exist is a usage error everywhere.
31
+
32
+ Builds (`build`, `deploy`, `verify`, `typesol/testing`) compare the active clang with the one the release is tested
33
+ with (`TESTED_TOOLCHAIN` in `typesol/compiler`: Agave 3.1.10, platform-tools v1.52): another one gets one warning per
34
+ process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `warn` is the default.
35
+
27
36
  ## typesol.json
28
37
 
29
38
  ```json
package/docs/client.md CHANGED
@@ -79,6 +79,11 @@ integers and floats are `number`, `Pubkey` is kit's `Address`, `string` and `Fix
79
79
  as in the program. Names are camelCase. For Anchor IDLs, data enums use `__kind`, as Codama-generated clients do. The
80
80
  file uses no TypeScript-only syntax (no `enum`), so it also runs under Node's type stripping.
81
81
 
82
+ Anchor IDLs can also hold types a TypeSOL program does not: `u256`/`i256` are `bigint` (32 bytes, little-endian), and
83
+ `Option<Option<T>>` is `Option<T> | null` with kit's `Option` inside, so the three values stay apart: `null` is None,
84
+ `none()` is Some(None) and `some(x)` (or `x`) is Some(Some(x)). A type that holds itself through a Vec or an Option
85
+ (`enum Shape { Dot, Rec { kids: Vec<Shape> } }`) is encoded and decoded to any depth.
86
+
82
87
  ## Safety
83
88
 
84
89
  An IDL can come from anywhere, so `typesol client` refuses one whose names are not identifiers, whose discriminators or
@@ -92,9 +97,12 @@ Anchor IDLs are refused with a hint to convert them (`anchor idl convert`).
92
97
  `Program data:` line only while this program is the innermost one running, and `eventsOf` reads only the `emitCpi`
93
98
  inner instructions that call this program (it needs `tx.transaction`'s account keys for that). `parseCpiEvents(data)`
94
99
  on its own does not check the program: give it this program's inner instructions only.
95
- - **Not filled in automatically** (pass them): PDAs seeded from struct fields (Anchor cannot seed with them either),
96
- PDAs whose program is another account's field, and a PDA seeded from its own fields (derive it with its `pdas`
97
- helper from the values). `typesol client` prints a note for each.
100
+ - **Not filled in by the builder** (pass them): PDAs seeded from a field of another account's data (`state.owner`;
101
+ `resolve` reads the account and derives them), PDAs whose program is another account's field, and a PDA seeded from
102
+ its own fields (derive it with its `pdas` helper from the values). `typesol client` prints a note for each. PDAs
103
+ seeded from a field of a struct argument, at any depth (`params.inner.id`), are filled in.
104
+ - **Left out, with a note**: instructions, accounts and types using `Option<Option<Option<T>>>` or deeper, and types
105
+ the client cannot express (listed by `typesol client`).
98
106
  - **Anchor IDLs**: zero-copy (`bytemuck`) accounts decode and encode at their `#[repr(C)]` offsets as the program sees
99
107
  them on SBF (padding included; `packed` and `align` honored; 128-bit integers align to 8). Generic types become one
100
108
  type per use with concrete arguments (`Pair<u64, 2>` is `PairU64N2`). Left out, with a note: zero-copy types with
package/docs/errors.md CHANGED
@@ -20,7 +20,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
20
20
  | 2016 / 2017 / 2018 | mint authority / freeze authority / decimals mismatch (2018: an existing mint `createIfNeeded` found) |
21
21
  | 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
22
22
  | 2024–2039 | an existing mint `createIfNeeded` found lacks a Token-2022 extension it was given, or holds other keys in it: group pointer 2024–2026, group member pointer 2027–2029, metadata pointer 2030–2032, close authority 2033–2034, permanent delegate 2035–2036, transfer hook 2037–2039 (the first code of each: the extension is missing; the next: the authority / address differs) (ConstraintMint…Extension…) |
23
- | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
23
+ | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount); also `close(a, b)` in a helper given one account for both |
24
24
  | 0 (from the System Program) | an `Init` / `create` on an address already in use (AccountAlreadyInUse): the System Program refuses it, as under Anchor's `init` |
25
25
  | 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
26
26
  | 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
package/docs/language.md CHANGED
@@ -8,7 +8,7 @@ The full reference. For a tour, start with the [README](../README.md).
8
8
  | --- | --- |
9
9
  | Instruction | an exported function returning `void`, one integer / boolean / `Pubkey`, a `string` (a Borsh String), or a fixed-size struct (sent as return data, at most 1024 bytes; `returns` in the IDL, and the generated client decodes it) |
10
10
  | Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
11
- | Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
11
+ | Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits; the amount, also in `<<=` / `>>=`, may be any integer type). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit), `min` / `max`, `switch` and as a list index (5104 past u64); a shift amount or an exponent is a u128 or smaller (compile error); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
12
12
  | Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
13
13
  | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
14
14
  | Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+ (`/** @code 6200 */` before a member jumps to that code, Anchor's `Name = 200`; `Name = ""` has no message in the IDL); `require(cond, "message")` makes an error of its own (`RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL); `require(cond, AnchorError.RequireKeysEqViolated)` fails with one of Anchor's own codes (2502 here; any anchor-lang `ErrorCode` can be raised this way); `require(cond, code)` with a `u32` value fails with that code as computed at run time (a helper returning its error: `require(r.err === 0n, r.err)`). See [errors.md](errors.md) |
@@ -55,13 +55,13 @@ The full reference. For a tour, start with the [README](../README.md).
55
55
  | Randomness | A chain has no secret randomness of its own: slot hashes and timestamps are known to, or chosen by, the block producer. `SwitchboardRandomness` (Switchboard On-Demand's RandomnessAccountData; owner, discriminator and size checked) gives verifiable randomness by commit and reveal: commit while `r.seedSlot === currentSlot() - 1n` and store `r.key` and `r.seedSlot`; settle in a later transaction after checking both, with `r.value()` (32 bytes) or `r.valueU64()`, which fail (5111) unless the value was revealed in this slot. See test/fixtures/coinflip.ts |
56
56
  | Multiple files | `import { Side, min } from "./math"` — structs, enums, constants and helpers can live in other files; only the entry file's exported functions are instructions; names are program-wide, so imports from TypeSOL files cannot be renamed; error codes number imported files first |
57
57
  | Loops | `for (let i = 0n; i < n; i++)` (or two counters, `for (let i = 0n, j = n; i < j; i++, j--)`: several declarations, and comma-separated updates run in order after each pass, `continue` included), `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
58
- | Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
58
+ | Helpers | non-exported functions (and every function of an imported file): take values, structs, lists (a `FixedVec<T, N>` or `Vec<T>` parameter takes a Vec argument, a slice of one, or the caller's FixedVec of the same elements: a local, a field of a local struct or of account data, at most N elements of room; read-only, passed as a view of its elements, by pointer; a list in account data is copied first when the helper also takes accounts, as a struct is), `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); a struct, data-enum or `fixedArray<T, N>(fill)` argument may be written in place (`applyFee({ denominator: 100n, numerator: 3n }, amount)`, nested literals and a ternary with a literal branch too), built in a local of its own as `const fee: Fee = { … }` would be; no recursion. Struct, list and data-enum parameters are read-only, passed by pointer; when the helper also takes accounts, one that is account data (a field of a view or of a loaded account) is copied at the call, since the helper's writes could change it, while a struct the caller owns (a local, a helper's result, an instruction argument, return data, or a struct parameter of a helper that itself takes accounts) is still passed in place. Pubkey, Option, string and u256 parameters are passed by pointer too (the SBF target passes a C struct as a pointer to the caller's object and does not copy it); a helper that can write (it takes accounts, remaining accounts or `Inout<T>` places) gets a copy taken at the call, unless the argument is a local, a temporary, an instruction argument, a constant, an account's key, the program id or a parameter of the calling helper, which nothing it is given reaches; a helper that writes nothing reads the caller's value in place. Text a string argument views in account data or in an `Inout<T>` place is copied for such a helper too; `Inout<T>` (below) gives the helper the caller's place to change. clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame; `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with large locals of its own (Phoenix's order ids built after its event recorder's last CPI). A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
59
59
  | `Inout<T>` parameters | `function addEvent(rec: Inout<Recorder>, e: Event): void { rec.count += 1n; … }` is Rust's `rec: &mut Recorder`: the helper gets the caller's place itself (a pointer, no copy: about the compute units of the same code written inline) and the caller sees its writes after the call, as JS shares an object passed to a function. `T` is a fixed-size struct, a `FixedArray<T, N>` or a `FixedVec<T, N>` (its `push`, `pop` and `clear` included). The argument is a writable place: a local struct or list, a `loadBorsh` local, a field path of a local, of a `loadRawMut` view or of a `Mut<T>` account, a list element (`book.levels.get(i)`, a narrowed Option's value), another `Inout` parameter (passed on), or a literal (a fresh value nobody else sees); a read-only one (a field of an `Account<T>`, a `loadRaw` view, an instruction argument, a read-only parameter) is a compile error naming what to change. At each call, so that the helper's parameter is the only way to the place while it runs: no other argument may share storage with an Inout one (one place inside the other; two elements of one list, whatever their indexes, a BigVec slice's elements included; an account and a place inside it; a read-only struct argument inside it: pass a copy); an element of a `Vec` or `BigVec` is refused when the call may resize or filter that list (the helper takes writable or remaining accounts), since its elements would move; and a reference into the place (`const e = p.items.get(0n)`) that is read after the call is refused, since the helper may replace what it points at (copy the fields first, or read them through the place). Places that differ in the source but may be one account at run time (two `Dup<…>` accounts, a writable and a read-only account, two native views under `NATIVE_ACCOUNT_WRITES`: `loadRawMut`, `loadRawMutAt`, `rawArrayMutAt` elements, `rbTreeMutAt` nodes, a helper's own account parameters) are compared before the call: 2040 when they overlap. The comparison covers an Inout argument against every other argument passed in place (another Inout one, a read-only struct, array or list, an account), so a read-only argument cannot change under the helper while it writes; one copied for the call (a helper that takes accounts gets a copy of account data) shares nothing and is not compared. One pair is left to run time: a place in a `loadRawMut` view passed with the `RemainingAccount` it was loaded from (without `NATIVE_ACCOUNT_WRITES` a second `loadRawMut` of it in the helper fails, 2040; with the flag the helper can load and write the same bytes, the flag's trade-off). Integers, Pubkeys, strings and Options are values, which JS copies into a function too: return the new value (`x = f(x)`) or keep it in a struct and take `Inout<ThatStruct>`. `Vec<T>`, `BigVec<T>`, accounts and data enums are refused with what to write instead, and so is `Inout<T>` anywhere but a helper's parameter. Closures (and helpers expanded because they were given one) take `Inout<T>` the same way; their struct parameters were references already |
60
60
  | Arrow functions and closures | `const fee = (x: u64): u64 => x / 100n` (or `const f = function (…) {…}`) at the top level or inside a function. One that reads or writes the enclosing function's variables (a closure: `let total = 0n; const add = (v: u64): void => { total += v; }`) is expanded where it is called: its names mean what they meant where it was declared, struct parameters are references, `return` leaves the closure; it cannot call itself. One that captures nothing becomes a helper. Parameter types may be left out on closures (taken from the arguments). Functions are values where they can be expanded: `const h = g` names the same function, and a function that returns one (`function adder(n: u64): (x: u64) => u64 { return (x) => x + n; }`) makes a closure where it is called (`const add5 = adder(5n)`, or `adder(5n)(x)`). A function can be chosen at run time between named ones, `const g = k === 1n ? dbl : inc` (the condition is read once, there; a call runs only the chosen one), and a list of named functions can be run in turn, `for (const f of [dbl, inc]) total += f(x)` (unrolled; `continue` and `break` work) |
61
61
  | Functions as arguments | a helper may take a function parameter (`function applyTwice(f: (x: u64) => u64, v: u64): u64`): it is compiled once per named function passed (a helper or a local function that captures nothing). An arrow written at the call works too (`applyTwice((x) => x * 3n, v)`: its types come from the parameter) when it reads none of the function's variables. Given a closure (one that reads them), the helper is expanded where it is called instead, like a closure, so it runs where the closure can (its type parameters bound from the call, its accounts the caller's) |
62
62
  | List callbacks | on a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument: `forEach`, `some`, `every`, `find` (an Option of the element; scalar elements; on struct elements read a field with `xs.find(f)!.qty`, which aborts with 5108 when nothing matched, or `xs.find(f)?.qty`, an Option), `findIndex` (i64, -1 when absent), `reduce(fn, initial)`, `includes(value)`, `indexOf(value)` (i64), `map` and `filter`. The arrow written at the call is expanded into a loop (elements as `list.get(i)` gives them, structs by reference) and may read and write the function's variables. A `map` / `filter` chain used right away (`xs.filter(f).map(g).reduce(h, 0n)`, `.length`, `for … of`) is one loop that stores nothing; callbacks after a filter get the index among the elements it let through. Stored (`const ys = xs.filter(f)`), it is a FixedVec on the stack as big as the list it starts from; from a `Vec`, give the size: `const ys: FixedVec<u64, 16> = …` (at most 2 KiB; one element more aborts with 5104). `map` gives integers, booleans, Pubkeys or enums; stored with a `FixedVec<Struct, N>` or `FixedVec<FixedString<N>, M>` annotation it gives structs (`(o) => ({ qty: o.qty })`) or text, and inside a chain it gives structs when the callback names its struct, `xs.map((o): Scored => ({ … })).filter(…).reduce(…)` (one struct per element, nothing stored) |
63
63
  | Generic helpers | `function max<T extends bigint>(a: T, b: T): T` — compiled once per set of types it is called with (`max(a, b)` with u64 arguments, or `max<u128>(x, 1n)` when only literals tell); a type parameter stands for an integer, boolean, Pubkey, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: `return (a + b) as T` (`as` names a type the value already has; it never converts) |
64
- | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) |
64
+ | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list callback writing it) |
65
65
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
66
66
  | Sysvars | `now()`, `currentSlot()`, `currentEpoch()`, `epochStartTimestamp()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()`; `epochRewards()` (EpochRewards through its syscall, Rust's `EpochRewards::get()`, no account: a read-only copy with `distributionStartingBlockHeight`, `numPartitions`, `parentBlockhash` (Hash), `totalPoints` (u128), `totalRewards`, `distributedRewards`, `active`; `const er = epochRewards()` or `epochRewards().active` inline, not a helper parameter); `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
67
67
  | Account size | `realloc(account, newSize, payer)` on a `Mut<Struct>` — growing charges the payer the extra rent (at most 10 KiB per instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a growable `Vec` (its push / pop / clear size the account). `resizeAccount(account, newSize)` on a `Mut<AccountInfo>` of this program is Rust's `AccountInfo::resize`: the length only, new bytes zeroed, no rent moved (fund it first: `rentExempt(newSize)`), at most 10 KiB of growth (3016) |
@@ -142,7 +142,9 @@ of a position, as Raydium CLMM's tick arrays).
142
142
  come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
143
143
  `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
144
144
  `initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`; and the Token Group interface: `initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize)` (a collection mint with a GroupPointer to itself; fund the rent for the group, which Token-2022 adds to the account), `initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority)`, `updateGroupMaxSize(group, authority, maxSize)`, `updateGroupAuthority(group, authority, next | null)`. Each takes optional signerSeeds
145
- - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
145
+ - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts (the destination
146
+ is another writable account; the account is not used after it in the function, except its `key`: compile errors, or
147
+ 2040 at run time in a helper given one account twice)
146
148
  - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
147
149
  stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
148
150
  among up to 256 addresses for the same seeds
@@ -187,7 +189,10 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
187
189
  lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
188
190
  - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
189
191
  wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
190
- signer([…, bump])`.
192
+ signer([…, bump])`. A named list, and one given to a helper, holds its seeds as they were when it was written (JS
193
+ evaluates the array then): a field or local changed afterwards does not change what it signs for. A list written in
194
+ a call (`transfer(…, signer([…]))`, `create(payer, [...], space)`) holds them as they were when the list was read,
195
+ even when a later argument changes a seed.
191
196
  - `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
192
197
  - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
193
198
  A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
package/docs/mainnet.md CHANGED
@@ -2,9 +2,18 @@
2
2
 
3
3
  From an empty directory to a program on Solana mainnet-beta: create, test, deploy, publish the IDL, then check that
4
4
  the deployed binary is the one your source builds. The program here is the counter that `typesol init` creates
5
- (13.2 KiB); any TypeSOL project works the same way.
5
+ (11,400 bytes, 11.1 KiB, built with TypeSOL 0.43.0 and platform-tools clang 20.1.7 for SBPF v0; other versions differ
6
+ slightly); any TypeSOL project works the same way.
6
7
 
7
- You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Requirements).
8
+ You need Node.js 22.12 or later and the Agave CLI with platform-tools (see the README's Quick start).
9
+
10
+ **The toolchain you deploy with.** The binary is what the platform-tools' clang makes of the generated C, so the
11
+ toolchain is part of what you trust. Deploy with the one TypeSOL is tested with (Agave 3.1.10, platform-tools v1.52;
12
+ `typesol doctor` says whether yours is, and `typesol deploy --toolchain-strict` refuses another). Keep
13
+ `target/my_app/my_app.build.json` with each deployment, next to the commit you deployed: it records the TypeSOL,
14
+ TypeScript, clang and platform-tools versions and the host, and the deployed bytes' sha256. Step 6's `verify` matches
15
+ only when it rebuilds with the same TypeSOL version and toolchain, and on a mismatch `--manifest` with that file shows
16
+ what differs.
8
17
 
9
18
  ## 1. Create and test
10
19
 
@@ -21,7 +30,7 @@ Write your program in `programs/my_app.ts` and keep the tests passing before you
21
30
  ## 2. Build
22
31
 
23
32
  ```sh
24
- npx typesol build
33
+ npx --no-install typesol build
25
34
  ```
26
35
 
27
36
  This writes `target/my_app/`: the program (`my_app.so`), its Anchor IDL (`my_app.json`), a TypeScript client
@@ -46,8 +55,10 @@ ever close the program:
46
55
  solana rent $(wc -c < target/my_app/my_app.so)
47
56
  ```
48
57
 
49
- The counter needs 0.069 SOL of rent. During the deploy the program is first written to a buffer account that holds
50
- the same amount again; it is returned when the deploy finishes. Fund about twice the rent plus 0.01 SOL for fees.
58
+ For the counter that is about 0.080 SOL (rent is (128 + size) × 6,960 lamports at the current rate: 80,234,880
59
+ lamports for 11,400 bytes; the program data account holds 45 bytes more). During the deploy the program is first
60
+ written to a buffer account that holds the same amount again; it is returned when the deploy finishes. Fund about
61
+ twice the rent plus 0.01 SOL for fees: 0.17 SOL for the counter.
51
62
 
52
63
  The public mainnet RPC is rate-limited; for deploys, set `--url` (or `solana config set --url`) to your RPC
53
64
  provider's endpoint.
@@ -55,8 +66,8 @@ provider's endpoint.
55
66
  ## 4. Deploy
56
67
 
57
68
  ```sh
58
- npx typesol deploy --dry-run # builds and prints the solana command it will run
59
- npx typesol deploy
69
+ npx --no-install typesol deploy --dry-run # builds and prints the solana command it will run
70
+ npx --no-install typesol deploy
60
71
  ```
61
72
 
62
73
  It runs `solana program deploy` at the address in `target/deploy/my_app-keypair.json`, with your wallet as payer and
@@ -68,7 +79,7 @@ with `solana program close <buffer address>`, or list yours with `solana program
68
79
  ## 5. Publish the IDL
69
80
 
70
81
  ```sh
71
- npx typesol idl publish
82
+ npx --no-install typesol idl publish
72
83
  ```
73
84
 
74
85
  It writes the IDL to the Program Metadata program, signed by the upgrade authority, where Anchor clients and
@@ -77,12 +88,12 @@ explorers look for it. It costs a few thousandths of a SOL of rent.
77
88
  ## 6. Verify
78
89
 
79
90
  ```sh
80
- npx typesol verify my_app
91
+ npx --no-install typesol verify my_app
81
92
  ```
82
93
 
83
94
  `verify` rebuilds the program from `programs/my_app.ts`, reads the deployed one at the address in `typesol.json` from
84
95
  the cluster in your Solana CLI config, and compares the bytes. `match` means anyone with your source and the same
85
- TypeSOL version gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
96
+ TypeSOL version and toolchain gets exactly the program on chain. It also prints the upgrade authority and checks the IDL you
86
97
  published in step 5. Anyone can run it against your program with `--address <program id> --url mainnet-beta`.
87
98
 
88
99
  ## 7. Call it
@@ -10,8 +10,9 @@ original side by side, the checks run against it and its cost, see [Case study:
10
10
  ```sh
11
11
  anchor build # in the Anchor project: target/idl/my_program.json
12
12
  npx @typesol/cli init my-program && cd my-program
13
+ npm install # the project's own TypeSOL, run below as npx --no-install typesol
13
14
  rm programs/my_program.ts tests/my_program.test.ts # the counter template's program and test
14
- npx typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
15
+ npx --no-install typesol port ../anchor/target/idl/my_program.json --out programs/my_program.ts
15
16
  ```
16
17
 
17
18
  `typesol port` writes the account structs, enums, errors and one function per instruction with its accounts and
package/docs/runtime.md CHANGED
@@ -12,7 +12,17 @@ This page is for people changing it; programs never call it directly.
12
12
  many call sites would otherwise each grow the binary (`ts_fail`, the rent fallback `ts_rent_slow`, PDA search).
13
13
  - **Errors are return values.** A function that can fail returns `uint64_t`: `SUCCESS`, or an error code. Fail with
14
14
  `TS_FAIL(code, "TypeSOL: …")` (logs the message, then returns the code) and propagate with `TS_TRY(call)`.
15
- Nothing aborts: the instruction returns the code, and the runtime reports it as `Custom(code)`.
15
+ The instruction returns the code, and the runtime reports it as `Custom(code)`. The exceptions abort the program
16
+ instead: Rust-style panics (`panic`, `PANIC_ON_OVERFLOW`, `PANIC_STYLE`, `panicsAt`) and a RedBlackTree whose bytes
17
+ are inconsistent (`ts_rbt_bad_index`, `ts_rbt_too_deep`, as lib-sokoban panics), which end with the runtime's
18
+ "SBF program panicked".
19
+ - **No C struct by value where it may alias.** The SBF target passes a C struct argument as a pointer to the caller's
20
+ object and makes no copy, so a function that writes memory the argument came from would see its own writes. A
21
+ runtime function taking a struct and an out-pointer it writes reads the struct into scalars first (`ts_str_append`
22
+ is an always-inlined wrapper of `ts_str_append_n`); generated helpers take such values by pointer.
23
+ - **Bounds without wrapping.** Size checks compare `a + b > limit` only when the sum cannot overflow, else
24
+ `n > limit - at` with `at <= limit` known (`ts_alloc`); a check such as `n > len - at - rest` is wrong when `at` may
25
+ be past `len - rest`.
16
26
  - **Error codes follow Anchor.** Where Anchor has a framework error with the same meaning, its number is used (2006
17
27
  ConstraintSeeds, 3003 AccountDidNotDeserialize, …), so Anchor and Codama clients name failures correctly.
18
28
  TypeSOL-only conditions are 5100–5199; user errors start at 6000. Every code is listed in [errors.md](errors.md).