@typesol/cli 0.37.0 → 0.39.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 (52) hide show
  1. package/CHANGELOG.md +352 -1
  2. package/README.md +31 -14
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +7 -6
  5. package/dist/compiler/analyze.js +350 -38
  6. package/dist/compiler/emit/alias.js +3 -2
  7. package/dist/compiler/emit/base.d.ts +5 -0
  8. package/dist/compiler/emit/base.js +2 -0
  9. package/dist/compiler/emit/borsh.js +63 -2
  10. package/dist/compiler/emit/calls.d.ts +9 -1
  11. package/dist/compiler/emit/calls.js +147 -18
  12. package/dist/compiler/emit/cpi-core.js +21 -6
  13. package/dist/compiler/emit/cpi.js +81 -27
  14. package/dist/compiler/emit/create.d.ts +7 -0
  15. package/dist/compiler/emit/create.js +27 -0
  16. package/dist/compiler/emit/expressions.js +7 -4
  17. package/dist/compiler/emit/function.d.ts +7 -0
  18. package/dist/compiler/emit/function.js +168 -30
  19. package/dist/compiler/emit/program.js +15 -2
  20. package/dist/compiler/emit/shared.d.ts +5 -5
  21. package/dist/compiler/emit/shared.js +5 -0
  22. package/dist/compiler/emit/statements.d.ts +8 -0
  23. package/dist/compiler/emit/statements.js +93 -6
  24. package/dist/compiler/emit/storage.d.ts +10 -1
  25. package/dist/compiler/emit/storage.js +50 -11
  26. package/dist/compiler/idl.d.ts +2 -2
  27. package/dist/compiler/idl.js +48 -13
  28. package/dist/compiler/model.d.ts +47 -10
  29. package/dist/compiler/model.js +14 -4
  30. package/dist/testing.js +8 -0
  31. package/dist/tools/clientgen.js +10 -1
  32. package/dist/tools/portgen.d.ts +6 -0
  33. package/dist/tools/portgen.js +68 -17
  34. package/docs/architecture.md +5 -4
  35. package/docs/audit.md +31 -19
  36. package/docs/case-study-escrow.md +5 -5
  37. package/docs/case-study-jito-mev.md +171 -0
  38. package/docs/case-study-marginfi.md +797 -0
  39. package/docs/case-study-multisig.md +3 -3
  40. package/docs/case-study-raydium-clmm.md +151 -101
  41. package/docs/case-study-raydium-cp-swap.md +3 -3
  42. package/docs/cli.md +5 -5
  43. package/docs/client.md +1 -1
  44. package/docs/errors.md +15 -4
  45. package/docs/language.md +39 -26
  46. package/docs/migrate-from-anchor.md +4 -1
  47. package/docs/runtime.md +1 -1
  48. package/docs/security-model.md +2 -1
  49. package/docs/testing.md +33 -1
  50. package/lib/typesol.d.ts +48 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
@@ -3,8 +3,8 @@
3
3
  This page ports a program that holds real authority on mainnet:
4
4
  [coral-xyz/multisig](https://github.com/coral-xyz/multisig) (`programs/multisig/src/lib.rs`, Anchor 0.25, Apache-2.0),
5
5
  deployed at `msigUdDBsR4zSUYqYEDrc1LcgtmuSDDM7KxpRUXNC6U`. The port is
6
- [`examples/multisig.ts`](https://github.com/typesol/typesol/blob/main/examples/multisig.ts). Instead of a twin built for the occasion, it is checked against the
7
- binary that runs on mainnet: [`test/examples/multisig.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/multisig.test.ts) runs both under the
6
+ [`showcase/mainnet/multisig/multisig.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/multisig/multisig.ts). Instead of a twin built for the occasion, it is checked against the
7
+ binary that runs on mainnet: [`showcase/test/multisig.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/multisig.test.ts) runs both under the
8
8
  same program id and compares every outcome and every account byte. See
9
9
  [case-study-escrow.md](case-study-escrow.md) for a token program and [Migrate from Anchor](migrate-from-anchor.md) for
10
10
  the general reference.
@@ -99,7 +99,7 @@ existing clients and existing accounts work with the port unchanged.
99
99
  ## How it was checked
100
100
 
101
101
  `test/programs/coral_multisig.so` is the program dumped from mainnet on 2026-10-29 (sha256 in
102
- [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)). The test loads it into one LiteSVM and the port into
102
+ [`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)). The test loads it into one LiteSVM and the port into
103
103
  another, both at `msigUdDB…`, then sends each transaction to both. After each one it requires the same outcome (success,
104
104
  or the same error down to the code) and the same lamports, owner and data bytes for every account involved.
105
105
 
@@ -1,19 +1,32 @@
1
1
  # Case study: Raydium CLMM
2
2
 
3
- This page ports the core of a production concentrated-liquidity AMM: [Raydium CLMM](https://github.com/raydium-io/raydium-clmm)
3
+ This page ports a production concentrated-liquidity AMM in full: [Raydium CLMM](https://github.com/raydium-io/raydium-clmm)
4
4
  (`programs/amm` at 6d7a0f8, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
5
5
  `CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK`, and its on-chain IDL matches that commit. The port is
6
- [`examples/raydium-clmm/`](https://github.com/typesol/typesol/blob/main/examples/raydium-clmm). As with
6
+ [`showcase/mainnet/raydium-clmm/`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-clmm). As with
7
7
  [Raydium CP-Swap](case-study-raydium-cp-swap.md), it is checked against the binary that runs on mainnet, not a rebuild.
8
8
 
9
9
  ## What is ported
10
10
 
11
- The port covers 8 of the original's 37 instructions, the ones a pool lives on:
12
-
13
- - `create_amm_config` and `create_pool`;
14
- - `open_position_with_token22_nft`, `increase_liquidity_v2` and `decrease_liquidity_v2`;
15
- - `swap_v2`;
16
- - `collect_protocol_fee` and `collect_fund_fee`.
11
+ All 37 of the original's instructions:
12
+
13
+ - **Pools.** `create_pool`, `create_customizable_pool` and `create_customizable_pool_v2`, which choose the fee mode,
14
+ a dynamic fee and a seed index.
15
+ - **Positions.** `open_position_with_token22_nft`, and `open_position` / `open_position_v2` with a Metaplex NFT;
16
+ `increase_liquidity` / `_v2`, `decrease_liquidity` / `_v2` and `close_position`.
17
+ - **Swaps.** `swap`, `swap_v2` and `swap_router_base_in`, a multi-hop route.
18
+ - **Limit orders.** `open_limit_order`, `increase_limit_order`, `decrease_limit_order`, `settle_limit_order` and
19
+ `close_limit_order`.
20
+ - **Rewards.** `initialize_reward`, `set_reward_params`, `update_reward_infos`, `collect_remaining_rewards` and
21
+ `transfer_reward_owner`.
22
+ - **Fees.** `collect_protocol_fee`, `collect_fund_fee` and `collect_excess_lamports`.
23
+ - **Admin.**
24
+ - `create_amm_config` and `update_amm_config`;
25
+ - `update_pool_status`;
26
+ - the operation account (`create_` / `update_operation_account`);
27
+ - the dynamic fee configs (`create_` / `update_dynamic_fee_config`);
28
+ - the support mints (`create_` / `close_support_mint_associated`);
29
+ - `close_protocol_position`.
17
30
 
18
31
  The files follow the original's modules:
19
32
 
@@ -22,37 +35,21 @@ The files follow the original's modules:
22
35
  | `math.ts` | `libraries/` | tick math, sqrt-price math, liquidity and token deltas, the swap step, in u128 and u256 |
23
36
  | `state.ts` | `states/` | every account and event, byte for byte |
24
37
  | `liquidity.ts` | `states/tick_array.rs`, `pool.rs`, `personal_position.rs`, `instructions/open_position.rs`, … | tick arrays, the tick array bitmap and its extension, rewards, positions' fees and rewards |
25
- | `swap.ts` | `instructions/swap.rs`, `states/pool_fee.rs`, `states/oracle.rs` | fee splitting, the dynamic fee, limit orders met during a swap, the bitmap searches, the oracle |
26
- | `raydium_clmm.ts` | `instructions/` | the 8 instructions |
38
+ | `swap.ts` | `instructions/swap.rs`, `states/pool_fee.rs`, `states/oracle.rs` | the swap loop over one tick array, fee splitting, the dynamic fee, limit orders met during a swap, the bitmap searches, the oracle |
39
+ | `limit_order.ts` | `states/limit_order.rs`, `instructions/limit_order/` | checks on an order, its share of what its tick filled |
40
+ | `raydium_clmm.ts` | `instructions/` | the 37 instructions |
27
41
 
28
42
  The port keeps the original's account layouts:
29
43
 
30
- - `PoolState`, `TickArrayState`, `TickArrayBitmapExtension` and `ObservationState` are zero-copy
44
+ - `PoolState`, `TickArrayState`, `TickArrayBitmapExtension`, `ObservationState` and `OperationState` are zero-copy
31
45
  `#[repr(C, packed)]` structs, which is TypeSOL's fixed layout.
32
- - `AmmConfig`, `PersonalPositionState` and `ProtocolPositionState` are Borsh accounts with only fixed-size fields, so
33
- their bytes are the same layout.
46
+ - `AmmConfig`, `PersonalPositionState`, `ProtocolPositionState`, `DynamicFeeConfig`, `SupportMintAssociated`,
47
+ `LimitOrderState` and `LimitOrderNonce` are Borsh accounts with only fixed-size fields, so their bytes are the same
48
+ layout.
34
49
 
35
50
  It also keeps the original's names, argument order and error codes, and emits the same events. The IDL it produces
36
- matches the on-chain IDL for these instructions: accounts, flags, addresses, PDA seeds, arguments and discriminators.
37
-
38
- A swap works the same on any pool the original runs, including features whose own instructions are not ported:
39
-
40
- - the dynamic fee (a pool with a `DynamicFeeInfo`: one tick spacing group at a time, the volatility accumulator, decay);
41
- - limit orders resting on a tick, filled as the price crosses it;
42
- - reward streams accruing, and fee modes that take the fee in token 0 only or token 1 only.
43
-
44
- These are not ported yet:
45
-
46
- - **The v1 instructions** (`open_position`, `open_position_v2` with a Metaplex NFT, `increase_liquidity`,
47
- `decrease_liquidity`, `swap`) and `swap_router_base_in`.
48
- - **`close_position`** and `close_protocol_position`.
49
- - **The limit order instructions**: `open_limit_order`, `increase_limit_order`, `decrease_limit_order`,
50
- `settle_limit_order` and `close_limit_order`.
51
- - **The reward instructions**: `initialize_reward`, `set_reward_params`, `update_reward_infos`,
52
- `collect_remaining_rewards` and `transfer_reward_owner`.
53
- - **The other admin instructions**: `update_amm_config`, `update_pool_status`, the operation account and dynamic-fee
54
- config instructions, `create_customizable_pool` (v1 and v2), the support-mint instructions and
55
- `collect_excess_lamports`.
51
+ matches the on-chain IDL: accounts, flags, addresses, PDA seeds, arguments and discriminators. Two details differ
52
+ (see the end of this page).
56
53
 
57
54
  ## What it needed
58
55
 
@@ -62,9 +59,9 @@ BigInt (`test/verification/fuzz-u256.test.ts`).
62
59
 
63
60
  The positions needed:
64
61
 
65
- - **Big-endian seeds.** Tick arrays are at `["tick_array", pool, start_index.to_be_bytes()]`. TypeSOL now has
66
- `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in seed lists. The IDL records the argument without the byte order,
67
- as Anchor's does.
62
+ - **Big-endian seeds.** Tick arrays are at `["tick_array", pool, start_index.to_be_bytes()]`, and dynamic fee configs
63
+ and limit orders use the same form. TypeSOL now has `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in seed
64
+ lists. The IDL records the argument without the byte order, as Anchor's does.
68
65
  - **Accounts loaded in the body.** A tick array may not exist yet, so the original takes it as an `UncheckedAccount`,
69
66
  creates it if needed, then loads it. `loadAccount` / `loadAccountMut` now take an `AccountInfo` parameter. The loaded
70
67
  struct is also its account (`.key`, `.lamports`), and it can be passed to helpers that take `Mut<T>`.
@@ -75,56 +72,92 @@ The positions needed:
75
72
 
76
73
  Tests for these are in `test/language/loaded-accounts.test.ts`.
77
74
 
78
- The swap loop needed nothing new. It is one instruction body:
75
+ The swap needed nothing new:
79
76
 
80
- - tick arrays are loaded from the remaining accounts one at a time, as the swap reaches them;
81
- - the swap state is a struct a helper returns, updated in place;
82
- - `apply_swap_amounts` is a local closure.
77
+ - **One tick array at a time.** `swapInArray` in `swap.ts` runs the original's loop over one array and returns the
78
+ new swap state, a struct the instruction stores whole into a local (`run.s = swapInArray(…)`).
79
+ - **Where the arrays come from.** Each instruction loads its tick arrays as the swap reaches them. `swap` takes the
80
+ first one as an account; `swap_v2` takes them all from the remaining accounts. `swap_router_base_in` reads every
81
+ hop's pool, config, vaults and token accounts from the remaining accounts, and moves tokens with `invoke`.
82
+ - **The router's account count.** It takes more accounts than TypeSOL's default 32, so the program declares
83
+ `MAX_ACCOUNTS = 255n`. That keeps its CPI account lists on the heap, which adds about 3% to a swap.
84
+ - **Routes back through a pool.** A route may pass one pool's accounts again (there and back, or A → B → B → A).
85
+ The router loads each hop's pool, observation, tick arrays and bitmap extension with `loadAccountMut<Dup<T>>`
86
+ inside its loop. A view declared in a loop body ends with the iteration, so the next hop loads the pool again and
87
+ sees what the earlier hop did to it, as in the original. Two live views of one account are still refused.
83
88
 
84
89
  ## How it was checked
85
90
 
86
- [`test/examples/raydium-clmm.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-clmm.test.ts)
91
+ [`showcase/test/raydium-clmm.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/raydium-clmm.test.ts)
87
92
  loads the binary dumped from mainnet on 2026-10-30 (sha256 in
88
- [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one LiteSVM
89
- and the port into another. Both use the same program id and the same clock.
93
+ [`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)) into one LiteSVM
94
+ and the port into another. Both use the same program id and the same clock, and both have Metaplex Token Metadata.
90
95
 
91
96
  **Setup.**
92
97
 
93
- - Mints and token accounts are made by the same token-program instructions in both.
94
- - `AmmConfig` accounts are written in both as the original lays them out, because creating one needs Raydium's admin
95
- key. The mainnet config of the USDC/CC pool is used as cloned.
96
- - Where a case needs state the ported instructions cannot make, it is written into the pool or a tick array in both
97
- VMs. This covers fee growth from earlier swaps, a reward stream, a dynamic fee, limit orders on a tick and the pool
98
- status bits.
98
+ - **The admin key.** Raydium's admin key (`GThUX1…`) gates the admin instructions. To run them, the test swaps it for
99
+ a test key in both programs:
100
+ - in the original, in the 26 places its code loads it (four 64-bit immediates each, `lddw`);
101
+ - in the port, in its source.
102
+
103
+ The other operator keys (lamport collection, limit order operator, support-mint operator) are not swapped. Each
104
+ check accepts the admin too, so those paths run as the admin.
105
+ - **Mints and token accounts** are made by the same token-program instructions in both.
106
+ - **State only swaps make.** Where a case needs it, it is written into the pool or a tick array in both VMs: fee growth
107
+ from earlier swaps, a reward stream, a dynamic fee, limit orders on a tick, the pool status bits.
99
108
 
100
109
  **Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
101
110
  code), the same lamports, owner and data for every account involved, and the same events byte for byte.
102
111
 
103
- There are 166 transactions:
104
-
105
- - **Configs and pools.** SPL Token and Token-2022 transfer-fee pools, the mainnet config, a pre-funded vault, and the
106
- refusals: mints out of order, a vault that is not the PDA, a price out of range, an open time ahead, the wrong
107
- token program, an unsupported extension, a config from anyone but the admin.
112
+ There are 302 transactions:
113
+
114
+ - **Configs and pools.**
115
+ - `create_pool` with SPL Token and Token-2022 transfer-fee mints, the mainnet config and a pre-funded vault.
116
+ - Customizable pools with each fee mode, a dynamic fee from a config, and seed indexes.
117
+ - A seeded pool used for a position, a swap and a decrease, signed with its seed index.
118
+ - Refusals: mints out of order, a vault that is not the PDA, a price out of range, an open time ahead, the wrong
119
+ token program, an unsupported extension, seed index 0, a dynamic fee without its config.
120
+ - **Admin.**
121
+ - Configs created and every `update_amm_config` flag (with the refusals).
122
+ - Operators added (sorted), added again and removed; a reward mint added and removed; more operators than fit.
123
+ - Dynamic fee configs, valid and not.
124
+ - A support mint that lets a pool take a Token-2022 mint with an extension pools refuse, then closed.
125
+ - Pool status, reward owner, a protocol position closed, lamports above rent collected.
126
+ - Each refused for anyone but the admin.
108
127
  - **Positions.**
109
128
  - Positions in range, below and above the price, in one tick array or two, and on the lowest array.
110
- - Liquidity worked out from amount_0 or amount_1, and NFTs with and without metadata.
129
+ - Liquidity worked out from amount_0 or amount_1, and NFTs as Token-2022 mints (with and without metadata) and as
130
+ Metaplex NFTs.
111
131
  - A tick shared by two positions, and a tick array whose address someone pre-funded.
112
- - A restricted-asset pool, whose position NFT account ends frozen.
113
- - Adding and removing liquidity down to an empty position: the counts go back to zero and the bitmap bits clear.
114
- - Fees owed and a reward stream paid out.
115
- - Arrays past the pool's own bitmap, on both sides, and a missing or wrong extension.
116
- - The pool status bits.
117
- - Refusals: slippage, tick order and spacing, wrong arrays, another owner's NFT.
132
+ - A restricted-asset pool, whose position NFT account ends frozen, and its NFT thawed to close it.
133
+ - Adding and removing liquidity with both instruction versions, down to an empty position (counts back to zero,
134
+ bitmap bits cleared); closing a Metaplex and a Token-2022 position.
135
+ - Fees owed and reward streams paid out; arrays past the pool's own bitmap, on both sides.
136
+ - Refusals: slippage, tick order and spacing, wrong arrays, another owner's NFT, closing with liquidity left.
118
137
  - **Swaps.**
119
- - Both directions, by input and by output, across ticks and tick arrays, to a price limit.
120
- - Fees taken in token 0 only or token 1 only, then protocol and fund fees collected.
121
- - A dynamic fee across its filter and decay periods; limit orders filled at a tick while a reward stream accrues, and
122
- orders alone on a tick filled in full (the tick leaves use, its array counts one less).
123
- - Into the bitmap extension and back, above and below the pool's own bitmap, and Token-2022 transfer-fee mints both
124
- ways.
125
- - The USDC/CC pool as cloned from mainnet: its config, vaults, oracle, extension and two tick arrays.
138
+ - `swap`, `swap_v2`, a two-hop `swap_router_base_in`, and routes back through a pool (there and back in one pool;
139
+ four hops through two pools twice); both directions, by input and by output, across ticks and
140
+ tick arrays, to a price limit.
141
+ - Fee modes, protocol and fund fees collected, a dynamic fee across its filter and decay periods.
142
+ - Limit orders filled at a tick while a reward stream accrues.
143
+ - Into the bitmap extension above and below the pool's own bitmap.
144
+ - Token-2022 transfer-fee mints, and the USDC/CC pool as cloned from mainnet (config, vaults, oracle, extension and
145
+ two tick arrays).
126
146
  - Refusals: slippage both ways, a zero amount, a limit on the wrong side, missing or wrong tick arrays, liquidity
127
147
  running out, swapped vaults, swaps disabled.
148
+ - **Limit orders.** Orders placed on a used tick, on a fresh one and in a tick array that does not exist yet, in both
149
+ directions. Then added to, partly taken back, filled by a swap, settled, closed; one taken back in full, which
150
+ clears its tick and the array's bit. Refusals: the wrong side of the price, off the spacing, a zero amount, orders
151
+ disabled, settling nothing, closing an unfilled order, someone else settling.
152
+ - **Rewards.** A stream set up (period too short, in the past, the same mint twice), brought up to date, changed by
153
+ the admin and by its authority (an extension too short, then a valid one), paid to a position, and what is left
154
+ returned after it ends.
155
+
156
+ The test also runs a random sequence: swaps (both ways, exact in and out, price limits, thresholds), positions at
157
+ random ranges, and liquidity added and taken out, with a new seed on every run (CI's included) and the same outcome,
158
+ bytes and events required after every step. `FUZZ_SEED=<seed>` reproduces a run's choices and amounts,
159
+ `CLMM_FUZZ_STEPS=<n>` lengthens it. Its transactions may use 1.4M compute units: one early run found a swap that
160
+ the original needs more than 200,000 for, which the default limit would stop before it is compared.
128
161
 
129
162
  ## Cost
130
163
 
@@ -132,45 +165,62 @@ Compute units per transaction, mainnet original against the port, from one run o
132
165
 
133
166
  | Instruction | Raydium (mainnet) | TypeSOL | |
134
167
  | --- | ---: | ---: | ---: |
135
- | `create_pool` | 67,818 | 26,935 | −60% |
136
- | `open_position_with_token22_nft`, in range | 126,375 | 66,015 | −48% |
137
- | `open_position_with_token22_nft`, Token-2022 transfer fee | 117,706 | 67,592 | −43% |
138
- | `increase_liquidity_v2` | 39,759 | 15,018 | −62% |
139
- | `decrease_liquidity_v2` | 40,615 | 17,263 | −57% |
140
- | `decrease_liquidity_v2`, with a reward paid | 67,766 | 20,683 | −69% |
141
- | `swap_v2` | 49,023 | 22,504 | −54% |
142
- | `swap_v2`, across tick arrays | 55,837 | 28,161 | −50% |
143
- | `swap_v2`, dynamic fee | 58,924 | 30,585 | −48% |
144
- | `swap_v2`, through limit orders | 74,417 | 36,995 | −50% |
145
- | `swap_v2`, into the bitmap extension | 78,605 | 44,428 | −43% |
146
- | `swap_v2`, Token-2022 transfer fee | 47,742 | 23,919 | −50% |
147
- | `swap_v2`, the mainnet USDC/CC pool | 52,708 | 26,881 | −49% |
148
- | `collect_protocol_fee` | 13,626 | 2,353 | −83% |
149
-
150
- Opening a position is mostly the token programs' and the System Program's work: the NFT mint, its metadata, the
151
- associated token account and the transfers. That work costs the same in both. Pool and position creation also vary
152
- from run to run with the PDA bump searches of the random keys the test uses, in both programs alike. Refusals cost far
153
- less; a swap of nothing costs 16,665 against 1,644.
154
-
155
- On size, the port's binary is 277,784 bytes and the deployed original 1,700,160 bytes. The original also contains the
156
- 29 instructions not ported here, so the ratio overstates the gain for the same feature set.
168
+ | `create_pool` | 57,318 | 24,806 | −57% |
169
+ | `create_customizable_pool_v2` | 51,673 | 23,724 | −54% |
170
+ | `open_position_with_token22_nft`, in range | 115,875 | 64,208 | −45% |
171
+ | `open_position` (Metaplex NFT) | 113,951 | 76,312 | −33% |
172
+ | `increase_liquidity_v2` | 39,759 | 15,935 | −60% |
173
+ | `decrease_liquidity_v2` | 40,615 | 16,538 | −59% |
174
+ | `decrease_liquidity_v2`, with a reward paid | 58,182 | 20,302 | −65% |
175
+ | `close_position`, Metaplex NFT | 11,032 | 3,366 | −69% |
176
+ | `close_position`, Token-2022 NFT (its mint closed too) | 22,395 | 10,376 | −54% |
177
+ | `swap_v2` | 49,023 | 22,349 | −54% |
178
+ | `swap_v2`, across tick arrays | 55,837 | 27,517 | −51% |
179
+ | `swap_v2`, dynamic fee | 58,924 | 29,890 | −49% |
180
+ | `swap_v2`, through limit orders | 74,417 | 35,675 | −52% |
181
+ | `swap_v2`, the mainnet USDC/CC pool | 52,677 | 26,536 | −50% |
182
+ | `swap` | 51,009 | 20,902 | −59% |
183
+ | `swap_router_base_in`, two hops | 80,365 | 39,499 | −51% |
184
+ | `swap_router_base_in`, four hops through two pools twice | 159,246 | 88,746 | −44% |
185
+ | `open_limit_order` | 34,220 | 9,951 | −71% |
186
+ | `settle_limit_order` | 15,682 | 6,066 | −61% |
187
+ | `initialize_reward` | 24,605 | 9,640 | −61% |
188
+ | `collect_protocol_fee` | 13,626 | 2,355 | −83% |
189
+ | `update_amm_config` | 3,028 | 491 | −84% |
190
+
191
+ Opening a position is mostly the token programs', the System Program's and (for a Metaplex NFT) Token Metadata's
192
+ work: the NFT mint, its metadata, the associated token account and the transfers. That work costs the same in both.
193
+ Pool and position creation also vary from run to run with the PDA bump searches of the random keys the test uses, in
194
+ both programs alike. Refusals cost far less; a swap of nothing costs 16,665 against 1,650.
195
+
196
+ On size, the port's binary is 552,656 bytes and the deployed original 1,700,160 bytes, for the same 37 instructions.
157
197
 
158
198
  ## Where they differ
159
199
 
160
200
  - **Panics.** Where the original panics (an index out of range, an overflow under `overflow-checks`), it fails with
161
- `ProgramFailedToComplete`; the port fails with a numbered error. For example, a position past the pool's own bitmap
162
- opened without the extension account: the original reads `remaining_accounts[0]` of none, the port fails with 5104.
163
- The test checks only that both fail there.
164
- - **Check order on double faults.** Anchor creates `personal_position` (its `init`) before it checks the token
165
- accounts after it; the port checks every account first and creates the position at the start of the body. A
166
- transaction breaking one check gets the same code. One that breaks two at once can be reported differently.
201
+ `ProgramFailedToComplete`; the port fails with a numbered error. Examples: a position past the pool's own bitmap
202
+ opened without the extension account (the original reads `remaining_accounts[0]` of none), more than 10 operators
203
+ (`copy_from_slice` of the wrong length). The test checks only that both fail there.
204
+ - **Check order on double faults.** Anchor creates `init` accounts (a position, an order) before it checks the other
205
+ accounts' constraints. TypeSOL does the same with the creates a body starts with (since the Marginfi port, whose
206
+ fuzzer found a case), so a transaction breaking both gets Anchor's code there. A body that checks something before
207
+ its creates keeps that order, and a double fault there can still be reported differently.
208
+ - **Reward mints' order.** The original keeps the operation account's reward mints in a hash set's order; the port
209
+ keeps them in the order added. With two or more listed, the `OperationState` bytes differ. Only membership is ever
210
+ read, and operators are sorted the same in both.
167
211
  - **Duplicate tick arrays in a swap.** The original loads every tick array it is given before it starts, so one passed
168
212
  twice fails at once. The port loads an array when the swap reaches it. Passed twice but never reached, it does
169
213
  not fail.
170
- - **Two limit-order fills that empty extension arrays in one swap.** Each needs the extension writable. The port loads
171
- it for each such flip, and a second load in one instruction is refused (2040). Only limit orders can empty an array
172
- during a swap, and their instructions are not ported.
173
- - **Logs.** The original's `msg!` lines in these paths (`exact_swap_internal, …`, the dynamic fee's `state.tick:…`,
174
- `collect reward index: …`) are logged the same. Error messages are TypeSOL's; codes and events are the original's.
214
+ - **Two limit-order fills that empty extension arrays in one swap.** Each needs the extension writable. The port now
215
+ loads it within the tick array's loop iteration, so a second flip in a later array is allowed. No test sets this
216
+ case up against the original yet.
217
+ - **IDL.**
218
+ - For the Metaplex NFTs' associated token account, the original's IDL lists the SPL Token program as a constant
219
+ seed. The port's lists the `token_program` account (fixed to that address) in `open_position`, and nothing in
220
+ `open_position_v2`.
221
+ - `CollectPersonalFeeEvent`, which no instruction emits, is not in the port's IDL.
222
+ - **Logs.** The original's `msg!` lines in these paths are logged the same: `exact_swap_internal, …`, the dynamic fee's
223
+ `state.tick:…`, `collect reward index: …`, `current block timestamp:…`, the close_position reasons. Error messages are
224
+ TypeSOL's; codes and events are the original's.
175
225
  - **Clients and big-endian seeds.** The IDL records tick array seeds as Anchor does, without the byte order, so a client
176
226
  that derives them from the IDL alone gets them wrong (with either program). Pass tick arrays explicitly.
@@ -2,7 +2,7 @@
2
2
 
3
3
  This page ports the trading core of a production AMM: [Raydium CP-Swap](https://github.com/raydium-io/raydium-cp-swap)
4
4
  (`programs/cp-swap`, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
5
- `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`examples/raydium-cp-swap/`](https://github.com/typesol/typesol/blob/main/examples/raydium-cp-swap)
5
+ `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`showcase/mainnet/raydium-cp-swap/`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/raydium-cp-swap)
6
6
  (`state.ts`, `curve.ts`, `raydium_cp_swap.ts`). As with [coral-xyz/multisig](case-study-multisig.md), it is checked
7
7
  against the binary that runs on mainnet, not a rebuild.
8
8
 
@@ -65,8 +65,8 @@ The rest uses features TypeSOL already had:
65
65
 
66
66
  ## How it was checked
67
67
 
68
- [`test/examples/raydium-cp-swap.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-cp-swap.test.ts) loads the binary dumped from
69
- mainnet on 2026-10-30 (slot 452376460; sha256 in [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one
68
+ [`showcase/test/raydium-cp-swap.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/raydium-cp-swap.test.ts) loads the binary dumped from
69
+ mainnet on 2026-10-30 (slot 452376460; sha256 in [`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)) into one
70
70
  LiteSVM and the port into another. Both use the same program id and the same clock.
71
71
 
72
72
  **Setup.**
package/docs/cli.md CHANGED
@@ -6,18 +6,18 @@ 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) 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) 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. |
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
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
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]` | 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]` | 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). |
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). |
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
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
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`). |
19
19
  | `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
- | `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, custom discriminators or error codes). |
20
+ | `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
21
  | `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
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
23
  | `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). |
@@ -36,7 +36,7 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
36
36
 
37
37
  `"clone": ["<address>", …]` lists the cluster accounts `typesol clone` copies for the tests, and `"accounts"` where
38
38
  they are kept (default `tests/accounts`). `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
39
- safe and out of git: it is each program's address and its first upgrade authority must not lose it. A clone without
39
+ safe and out of git: it is the program's address, and it is needed to deploy it again. A clone without
40
40
  it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
41
41
 
42
42
  ## Editor
package/docs/client.md CHANGED
@@ -61,7 +61,7 @@ Kit's own transaction functions work with the instructions as well; `sendInstruc
61
61
 
62
62
  | | |
63
63
  | --- | --- |
64
- | `<program>.<instruction>(accounts, args)` | Builds the `Instruction`. Accounts with a fixed address and PDAs whose seeds are constants, arguments or other accounts' keys are optional and filled in; pass one to override. An optional account passed as `null` is left out (sent as the program id, the convention TypeSOL and Anchor share); left undefined, it is filled in like any other. |
64
+ | `<program>.<instruction>(accounts, args)` | Builds the `Instruction`. Accounts with a fixed address and PDAs whose seeds are constants, arguments (an Option one with its default too: Anchor's `id.unwrap_or(0)`) or other accounts' keys are optional and filled in; pass one to override. An optional account passed as `null` is left out (sent as the program id, the convention TypeSOL and Anchor share); left undefined, it is filled in like any other. |
65
65
  | `<program>.<instruction>(accounts, args, remaining?)` | The same, with remaining accounts appended in order (kit `AccountMeta`s). |
66
66
  | `<program>.accounts.<Name>` | `decode(bytes)`, `encode(value)`, `fetch(rpc, address)`, `fetchMaybe(rpc, address)`, `fetchMultiple(rpc, addresses)`, `fetchAll(rpc, filters?)` (getProgramAccounts by discriminator, plus `{ offset, bytes }` filters), `watch(rpcSubscriptions, address, { abortSignal })`, `discriminator`. `decode` checks the discriminator. |
67
67
  | `<program>.pdas.<account>(seeds)` | The PDA (address and bump) for each account an instruction derives, also one seeded from its own fields (from the field values). |
package/docs/errors.md CHANGED
@@ -7,8 +7,8 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
7
7
  | 100 / 101 / 102 | instruction data missing / unknown instruction / malformed arguments (InstructionMissing / FallbackNotFound / DidNotDeserialize) |
8
8
  | 2000 | a `Mut<…>` / `Init<…>` account passed read-only (ConstraintMut) |
9
9
  | 2001 | HasOne constraint failed (ConstraintHasOne) |
10
- | 2003 | a `constraint(acct, condition)` without its own error failed (ConstraintRaw) |
11
10
  | 2002 | a `Signed<…>` account (or the event authority) did not sign (ConstraintSigner) |
11
+ | 2003 | a `constraint(acct, condition)` without its own error failed (ConstraintRaw) |
12
12
  | 2004 | Owner constraint failed (ConstraintOwner) |
13
13
  | 2005 | Zeroed account is not rent-exempt (ConstraintRentExempt) |
14
14
  | 2006 | PDA seeds mismatch (ConstraintSeeds) |
@@ -23,6 +23,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
23
23
  | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
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
+ | 3001 | a zero-copy (`@serialization bytemuck`) account with fewer than 8 bytes of data (AccountDiscriminatorNotFound) |
26
27
  | 3002 | discriminator mismatch (AccountDiscriminatorMismatch) |
27
28
  | 3003 | data too small, not an initialized token account / mint, a read past the end, or a `@layout borsh` account whose bytes are not a valid Borsh value (AccountDidNotDeserialize) |
28
29
  | 3004 | a `@layout borsh` account too small for the value it would now hold (AccountDidNotSerialize) |
@@ -32,7 +33,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
32
33
  | 3008 / 3009 | wrong program address / not executable (InvalidProgramId / InvalidProgramExecutable) |
33
34
  | 3010 | account must sign (AccountNotSigner; also a new keypair account a `create(payer, null, …)` makes) |
34
35
  | 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
35
- | 3012 | account not initialized: empty system account where a program account was expected (AccountNotInitialized) |
36
+ | 3012 | account not initialized: empty system account where a program account, a token account or a mint was expected (AccountNotInitialized; not for zero-copy accounts, which Anchor's AccountLoader reports as 3007) |
36
37
  | 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
37
38
  | 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
38
39
  | 4102 | cast overflow (InvalidNumericConversion) |
@@ -49,18 +50,28 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
49
50
  | 5113 | more accounts in one instruction (or one CPI) than the program takes: 32, or its `MAX_ACCOUNTS` |
50
51
  | 5114 | a function with a result ended without returning one |
51
52
  | 5115 | an optional account that was left out was used |
52
- | 6000+ | your error enums' members, in declaration order (imported files first), then one `RequireFailed<N>` error (code 6000 + N) per distinct `require(cond, "message")` string |
53
+ | 6000+ | your error enums' members, in declaration order (imported files first), then one `RequireFailed<N>` error (code 6000 + N, after the highest code) per distinct `require(cond, "message")` string |
54
+
55
+ A member's string is its message (the IDL's `msg`); `X = ""` leaves the message out, as an Anchor variant without
56
+ `#[msg]`. `/** @code 6200 */` before a member gives it that code, and the members after it continue from there (Anchor's
57
+ `Variant = 200`); codes only go up. `require(cond, "message")` errors come after the highest code.
53
58
 
54
59
  Any of Anchor's own codes can be raised directly: `require(cond, AnchorError.RequireKeysEqViolated)` fails with 2502,
55
60
  as `require_keys_eq!` does.
56
61
 
62
+ A code can also be computed at run time: `require(cond, code)` with a `u32` value fails with that code. This is how a
63
+ helper passes an error on as Rust's `?` does, when it returns the error as a value instead of failing (a price read
64
+ whose error the caller may record or ignore): `const r = price(feed); require(r.err === 0n, r.err);`. The code is
65
+ reported as it is (use one of your errors' codes, so clients can decode it); a zero code fails with 5100.
66
+
57
67
  ## Which error a transaction gets
58
68
 
59
69
  A transaction can break several checks; it fails with the first. Within each account's constraints the checks run in
60
70
  the order Anchor's generated code runs them, so a transaction gets the same code under both:
61
71
 
62
72
  1. The account count (3005), then each account in parameter order: its type, signer (3010), `Mut` (2000), owner,
63
- discriminator and size of a program account (3007 / 3012 / 3002 / 3003), token account or mint, program address.
73
+ discriminator and size of a program account (3007 / 3012 / 3002 / 3003; a zero-copy one as Anchor's AccountLoader:
74
+ 3007 / 3001 / 3002, then 3003), token account or mint, program address.
64
75
  2. Two writable parameters naming one account (2040).
65
76
  3. The instruction's arguments (102).
66
77
  4. Each account in parameter order, its constraints in Anchor's order: seeds (2006), associated token account (owner