@typesol/cli 0.41.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +319 -0
- package/README.md +11 -7
- package/dist/compiler/analyze.js +484 -13
- package/dist/compiler/diagnostics.d.ts +1 -0
- package/dist/compiler/diagnostics.js +13 -0
- package/dist/compiler/emit/alias.d.ts +44 -0
- package/dist/compiler/emit/alias.js +135 -4
- package/dist/compiler/emit/base.d.ts +65 -7
- package/dist/compiler/emit/base.js +91 -7
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +169 -2
- package/dist/compiler/emit/calls.js +1170 -81
- package/dist/compiler/emit/cpi-core.d.ts +28 -5
- package/dist/compiler/emit/cpi-core.js +238 -12
- package/dist/compiler/emit/cpi.js +16 -16
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +89 -9
- package/dist/compiler/emit/function.js +2 -2
- package/dist/compiler/emit/outline.d.ts +24 -0
- package/dist/compiler/emit/outline.js +100 -0
- package/dist/compiler/emit/program.js +37 -3
- package/dist/compiler/emit/rbtree.d.ts +7 -0
- package/dist/compiler/emit/rbtree.js +142 -0
- package/dist/compiler/emit/shared.d.ts +43 -1
- package/dist/compiler/emit/shared.js +18 -2
- package/dist/compiler/emit/statements.d.ts +58 -1
- package/dist/compiler/emit/statements.js +549 -22
- package/dist/compiler/emit/storage.d.ts +48 -1
- package/dist/compiler/emit/storage.js +220 -63
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/emit/views.d.ts +60 -0
- package/dist/compiler/emit/views.js +523 -0
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/idl.js +2 -1
- package/dist/compiler/model.d.ts +84 -4
- package/dist/compiler/model.js +19 -0
- package/dist/compiler/toolchain.d.ts +15 -0
- package/dist/compiler/toolchain.js +146 -11
- package/dist/testing-stake.d.ts +216 -0
- package/dist/testing-stake.js +526 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -0
- package/docs/architecture.md +9 -2
- package/docs/case-study-phoenix.md +226 -0
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +244 -20
- package/docs/migrate-from-anchor.md +1 -0
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +4 -0
- package/docs/stability.md +33 -1
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/docs/troubleshooting.md +5 -2
- package/lib/typesol.d.ts +462 -44
- package/llms-full.txt +338 -26
- package/llms.txt +1 -1
- package/package.json +2 -2
- package/runtime/typesol_rt.h +476 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# Case study: Phoenix v1
|
|
2
|
+
|
|
3
|
+
This page ports [Phoenix v1](https://github.com/Ellipsis-Labs/phoenix-v1), Ellipsis Labs' on-chain limit order book:
|
|
4
|
+
a central limit order book that matches and settles in the same instruction, price first and first in, first out
|
|
5
|
+
within a price, with no crank. Its repository now calls it Phoenix Legacy. The port is checked against the binary
|
|
6
|
+
that runs on mainnet as `PhoeNiXZ8ByJGLkxNfZRnkUfjvmuYqLR89jjFHGqdXY` (deployed in slot 231433470, 2023-11-21), not a
|
|
7
|
+
rebuild.
|
|
8
|
+
|
|
9
|
+
**Which source.** Commit c16694d rebuilt with `solana-verify build --library-name phoenix` (Solana 1.14.9) gives the
|
|
10
|
+
deployed executable's hash (`6877a5b732b3494b828a324ec846d526d962223959534dbaf4209e0da3b2d6a9`); OtterSec's
|
|
11
|
+
verification registry lists the program as verified from that commit. The repository was under BUSL 1.1 at c16694d;
|
|
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)).
|
|
14
|
+
|
|
15
|
+
Phoenix is a native program built with solana-program 1.14: a u8 tag, the instruction's Borsh arguments after it,
|
|
16
|
+
accounts by position. A market is one account: a 576-byte header, then a `FIFOMarket` whose bids, asks and traders are
|
|
17
|
+
three lib-sokoban `RedBlackTree`s laid out in the account's bytes (sized by the header: twelve size sets, up to 4,096
|
|
18
|
+
orders a side and 8,321 seats), read and written in place. Phoenix does not log its market events: it sends them to
|
|
19
|
+
itself in Log instructions, self-CPIs signed by a log-authority PDA, so clients read them from the inner instructions.
|
|
20
|
+
The order instructions return the ids of the orders that rested as return data, and the program's failures are often
|
|
21
|
+
Rust panics in solana-program 1.14's format, at the original's source locations.
|
|
22
|
+
|
|
23
|
+
| File | Holds |
|
|
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 |
|
|
30
|
+
| `orders.ts`, `cancel.ts`, `initialize.ts`, `governance.ts`, `seats.ts`, `funds.ts`, `fees.ts` | the instructions by subject |
|
|
31
|
+
|
|
32
|
+
## What is ported
|
|
33
|
+
|
|
34
|
+
All 28 tags: Swap and SwapWithFreeFunds (0, 1), PlaceLimitOrder and its free-funds form (2, 3), ReduceOrder (4, 5),
|
|
35
|
+
CancelAllOrders (6, 7), CancelUpTo (8, 9), CancelMultipleOrdersById (10, 11), WithdrawFunds (12), DepositFunds (13),
|
|
36
|
+
RequestSeat (14), Log (15), PlaceMultiplePostOnlyOrders (16, 17), and the authority's InitializeMarket,
|
|
37
|
+
ClaimAuthority, NameSuccessor, ChangeMarketStatus, ChangeSeatStatus, RequestSeatAuthorized, EvictSeat,
|
|
38
|
+
ForceCancelOrders, CollectFees and ChangeFeeRecipient (100 to 109). Every order type (PostOnly, Limit, ImmediateOrCancel
|
|
39
|
+
and fill-or-kill, with base or quote budgets, minimum fills, match limits, the three self-trade behaviours, time in
|
|
40
|
+
force, fail-silent orders), free funds, taker fees, eviction from a full book, the order packet decoder with its
|
|
41
|
+
zero-padding retries, the market's statuses down to Tombstone, and the events byte for byte.
|
|
42
|
+
|
|
43
|
+
## What it needed
|
|
44
|
+
|
|
45
|
+
TypeSOL gained these features for it (docs/language.md, "Porting a native program"); programs that use none of them
|
|
46
|
+
compile to the same C as before:
|
|
47
|
+
|
|
48
|
+
- **lib-sokoban's RedBlackTree** over account bytes, `rbTreeAt` / `rbTreeMutAt`: `get`, `insert`, `remove`, `min`,
|
|
49
|
+
`max`, `addrOf`, `nodeAt`, walks both ways, with a comparator of the program (Phoenix orders bids by inverted sequence
|
|
50
|
+
numbers). It runs sokoban's code statement for statement, so the bytes are the crate's: replayed against the real
|
|
51
|
+
crate with identical bytes after every operation, on the 21,650 recorded operations of the committed test (seeds
|
|
52
|
+
1–3, capacities 1 to 4096, strides 32, 64 and 144) and, with the previous trace generator, on a one-off run of
|
|
53
|
+
1,020,000 (capacities 1 to 512); sokoban's panics come out with its messages and source lines.
|
|
54
|
+
- **`removeAt(index)`**: the node `addrOf`, `min` or `max` found, removed with `remove(key)`'s writes and no second
|
|
55
|
+
search (the trace replay runs again with every `remove(key)` as `removeAt(addrOf(key))`). The port uses it where
|
|
56
|
+
Phoenix finds an order and then removes it: 62 to 103 compute units less per cancelled order (more in deeper books),
|
|
57
|
+
about 100 per order a match fills whole, 190 to 360 per eviction.
|
|
58
|
+
- **Cheaper tree walks** (one bounds check per node, the stack by pointer) and an **owner-check cache** for native
|
|
59
|
+
views (the market viewed again passes with a pointer compare): Phoenix's helpers each view the market again, often in
|
|
60
|
+
loops that write it.
|
|
61
|
+
- **Data enums by `pushBorsh`, straight-line**: `data.pushBorsh<PhoenixMarketEvent>({ kind: "Fill", … })` writes only
|
|
62
|
+
that variant, one room check and a store per field. Every event is appended to the batch this way: 47 compute units
|
|
63
|
+
less per Reduce event than the six `pushLE` calls it replaced, each of which checked the room of the batch (an
|
|
64
|
+
`Inout` parameter) on its own, and 55 to 70 less per Fill, Place, FillSummary, Evict or ExpiredOrder than serializing
|
|
65
|
+
the whole enum.
|
|
66
|
+
- **Struct arguments in place**: an owned struct (a local, a parameter passed on) goes to a helper that takes accounts by
|
|
67
|
+
pointer, so the book helpers take their MarketShape as a plain struct, not `Inout<T>`.
|
|
68
|
+
- **`Inout<T>`** helper parameters (Rust's `&mut`: the recorder and its 1,280-byte batch passed down the matching
|
|
69
|
+
engine), **`/** @noinline */`** and **`/** @heap */`** (room beyond one 4 KiB stack frame), local lists of 2 KiB
|
|
70
|
+
(asked for by a 2,052-byte list of collected order ids; the port keeps the 512 ids as u16 node indices).
|
|
71
|
+
- **Native-program foundations**: `loadRawAt` / `loadRawMutAt` (a struct at a run-time offset), `NATIVE_ACCOUNT_WRITES`
|
|
72
|
+
(views of one account written in place, judged by the runtime), byte builders (`pushLE`, `pushKey`, `pushBorsh`,
|
|
73
|
+
`setLE`, `truncate`) and `invokeInstruction` for the Log self-CPI, `setReturnData` and `logComputeUnits`, `closeRaw`
|
|
74
|
+
for Tombstone, `findProgramAddressWithBump`, errors from code 0 that log nothing (`ERROR_LOG_PREFIX = null`), and
|
|
75
|
+
panics as solana-program 1.14 writes them (`PANIC_STYLE = "solana-1.14"`, `panicsAt` for Rust's overflow messages at
|
|
76
|
+
the original's locations).
|
|
77
|
+
- **Source-level conveniences** the port reads better with: constant expressions (`EVENT_ROOM =
|
|
78
|
+
MAX_INNER_INSTRUCTION_SIZE - LOG_IX_ACCOUNT_META_SIZE`, the node sizes, `BIDS_OFFSET`), file-local structs for
|
|
79
|
+
helper-only types (left out of the IDL), comma-separated `for` updates, and read-only views read where they are made
|
|
80
|
+
(`loadRaw<MarketHeader>(m).status`).
|
|
81
|
+
|
|
82
|
+
## How it is checked
|
|
83
|
+
|
|
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
|
|
86
|
+
transaction must give:
|
|
87
|
+
|
|
88
|
+
- the same outcome;
|
|
89
|
+
- the same log lines, every one: the original's messages and numbers, panics with their locations, the batch lines of
|
|
90
|
+
the recorder (Phoenix's own "Program consumption" lines by count and position; only the runtime's "consumed N of M
|
|
91
|
+
compute units" lines are left out);
|
|
92
|
+
- the same inner instructions in order, each one's program, accounts and data bytes: the Log self-CPIs, so every event
|
|
93
|
+
batch is compared byte for byte, and the token transfers;
|
|
94
|
+
- the same return data;
|
|
95
|
+
- the same lamports, owner and bytes in every account the transaction names (the books and the traders tree byte for
|
|
96
|
+
byte, rotations and colours included).
|
|
97
|
+
|
|
98
|
+
There are 3,575 such transactions in five files, on markets of 512 orders and 128 seats and of 4,096 and 8,321 (each
|
|
99
|
+
file fails unless it compares exactly its own count):
|
|
100
|
+
|
|
101
|
+
- **The non-matching instructions** (`phoenix.test.ts`; 824): the entry's checks for all 28 tags, InitializeMarket with
|
|
102
|
+
each of the twelve sizes and every refusal, the authority's instructions, seats, deposits and withdrawals, fees.
|
|
103
|
+
- **Orders and matching** (`phoenix-orders.test.ts`; 1,117): every order type on both sides, crossings of many levels,
|
|
104
|
+
self trades, match limits, minimum fills, budgets, fees (100% included), free funds, multiple-order grouping and its
|
|
105
|
+
failure behaviours, a full book (eviction and rejection), time in force, the sequence number's limit, matches whose
|
|
106
|
+
events take several Log batches (300 fills), the packet decoder on cut and invalid packets.
|
|
107
|
+
- **Reductions and cancels** (`phoenix-cancel.test.ts`; 390): the orders are placed by the original and its bytes
|
|
108
|
+
copied into the port's VM, so both start from the trees Phoenix itself wrote; partial, whole and oversized reductions,
|
|
109
|
+
foreign and unknown orders, every cancel form with its limits, ForceCancelOrders and EvictSeat, 90 to 512 cancels in
|
|
110
|
+
one instruction, the out-of-memory abort at the 513th, books of up to 8,000 orders, the overflow and division panics.
|
|
111
|
+
- **The original's own tests** (`phoenix-upstream.test.ts`; 1,082): each of the 50 test functions at c16694d (the
|
|
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,
|
|
114
|
+
2 are not applicable (compile-time type checks of the quantity macros). Each refusal the upstream test expects is
|
|
115
|
+
pinned to the original's error and message, and the upstream test's own assertions (balances, the book, free lots,
|
|
116
|
+
the sequence number, fees) are made on chain.
|
|
117
|
+
- **The limits** (`phoenix-limits.test.ts`; 162): markets with a tick size or a base lot of 0 (the divisions' panics),
|
|
118
|
+
a negative clock, multiple-order packets longer than a transaction carries, and both sides of each of the heap's
|
|
119
|
+
boundaries, through a forwarding caller program where a CPI is needed (see Differences).
|
|
120
|
+
|
|
121
|
+
States no instruction reaches in a test's time (fees accrued, a sequence number near its maximum, a damaged lot size)
|
|
122
|
+
are written into both VMs' bytes, and each test checks the outcome too, so that every error path is really reached.
|
|
123
|
+
Every compared transaction's compute units are kept, and each file fails unless the port uses fewer on every
|
|
124
|
+
transaction that succeeds: 2,390 of the 3,575.
|
|
125
|
+
|
|
126
|
+
**A random walk over the order book** (`phoenix-fuzz.test.ts`, not in those counts) runs a 512/128 and a 4096/8321
|
|
127
|
+
market, each book started nearly full of orders far from the action: seated makers and unseated takers deposit and
|
|
128
|
+
withdraw, place every kind of order with tokens or free funds, reduce and cancel (with others', unknown, wrong-side and
|
|
129
|
+
bit-flipped ids), the authority changes seats, forces cancels, evicts, collects fees and changes the market's status,
|
|
130
|
+
the clock moves on so orders expire, and some packets are corrupted. Every step goes through the same comparison, and
|
|
131
|
+
an oracle checks after each that the registered traders' locked and free lots plus the uncollected fees are exactly
|
|
132
|
+
what the vaults hold. A walk's choices and every keypair come from its seed, so a seed reproduces it. By default the
|
|
133
|
+
test walks seeds 1, 2 and 3 on both markets, 300 steps each (1,801 transactions), and requires minimum counts of real
|
|
134
|
+
effects decoded from the event batches (fills, partial fills, orders rested, self trades, expiries, evictions, fees)
|
|
135
|
+
and a minimum share of successes for every kind of instruction. `FUZZ_SEED` walks another seed and
|
|
136
|
+
`PHOENIX_FUZZ_STEPS` changes the length; a walk of 1,000 steps or more must also have every main kind of instruction
|
|
137
|
+
succeed and each book fill up and evict. Before the walk drew its keys from the seed, a one-off run of five seeds (1
|
|
138
|
+
and 1794299110079 at 1,000 steps, 2, 3 and 4 at 3,000; 21,593 transactions) found no difference.
|
|
139
|
+
|
|
140
|
+
## Cost
|
|
141
|
+
|
|
142
|
+
Compute units per transaction, mainnet original against the port, from those tests (the token CPIs are the same work
|
|
143
|
+
in both; the account checks that derive PDAs vary with the bumps the keys need, each further bump about 1,500 units
|
|
144
|
+
in the original and 341 in the port, and a few rows by a few dozen units from run to run: a range is what two runs of
|
|
145
|
+
the five files gave, and `InitializeMarket`'s covers its twelve sizes):
|
|
146
|
+
|
|
147
|
+
| Instruction | Original | TypeSOL | |
|
|
148
|
+
| --- | ---: | ---: | ---: |
|
|
149
|
+
| `InitializeMarket` | 79,146–97,353 | 10,940–15,035 | 14–15% |
|
|
150
|
+
| `RequestSeat` | 14,900 | 4,599 | 31% |
|
|
151
|
+
| `DepositFunds` | 20,441 | 6,176 | 30% |
|
|
152
|
+
| `WithdrawFunds` | 17,760 | 6,201 | 35% |
|
|
153
|
+
| `CollectFees` | 13,814 | 4,977 | 36% |
|
|
154
|
+
| `PlaceLimitOrder`, PostOnly | 20,577–25,077 | 6,452–7,475 | 30–31% |
|
|
155
|
+
| `PlaceLimitOrder`, Limit, resting | 21,971–23,471 | 7,066–7,407 | 32% |
|
|
156
|
+
| `Swap`, 2 fills | 22,809–22,886 | 8,178–8,196 | 36% |
|
|
157
|
+
| `Swap`, 30 fills | 61,313–61,390 | 26,344–26,362 | 43% |
|
|
158
|
+
| `PlaceLimitOrder`, Limit through 20 fills, then resting | 108,397–114,399 | 52,894–54,260 | 47–49% |
|
|
159
|
+
| `PlaceMultiplePostOnlyOrders`, 5 orders in 4 levels | 34,605–40,614 | 13,324–14,698 | 36–39% |
|
|
160
|
+
| `ReduceOrder` | 15,235 | 5,170 | 34% |
|
|
161
|
+
| `CancelMultipleOrdersById`, 1 order | 15,984 | 5,708 | 36% |
|
|
162
|
+
| `CancelMultipleOrdersByIdWithFreeFunds`, 50 orders | 67,793–67,871 | 38,527–38,547 | 57% |
|
|
163
|
+
| `CancelUpTo`, 3 orders | 18,349–18,367 | 7,312 | 40% |
|
|
164
|
+
| `CancelAllOrdersWithFreeFunds`, 90 orders | 115,366 | 69,762 | 60% |
|
|
165
|
+
| `EvictSeat` | 22,966–33,466 | 7,306–9,693 | 29–32% |
|
|
166
|
+
|
|
167
|
+
At the extremes: a match of 300 fills in three Log batches 443,217–443,295 against 217,847–217,867 (49%);
|
|
168
|
+
`CancelAllOrders` of 512 orders in a 4,096 book 760,087 against 434,446 (57%), and of 200 among 8,000 orders 1,184,623
|
|
169
|
+
against 471,050 (40%); `CancelUpTo` searching 1,500 orders 1,002,398–1,002,399 against 456,958–456,960 (46%); the
|
|
170
|
+
513th collected id runs both out of memory after 90,220 and 30,363.
|
|
171
|
+
|
|
172
|
+
The binary is 256,360 bytes against the original's 1,344,472.
|
|
173
|
+
|
|
174
|
+
## Differences
|
|
175
|
+
|
|
176
|
+
What the port does not reproduce, and how a transaction would reach it:
|
|
177
|
+
|
|
178
|
+
- **Compute.** The port spends 13–61% of the original's units (up to 86% in `phoenix-limits.test.ts`, whose
|
|
179
|
+
transactions carry hundreds of account entries or go through a forwarding program), so a transaction that runs the
|
|
180
|
+
original out of its compute budget can complete in the port; the tests give both enough.
|
|
181
|
+
- **Memory, counted.** Phoenix allocates on solana-program 1.14.9's bump heap: 32 KiB from the top down, never freed,
|
|
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
|
|
184
|
+
Rust allocates: the entrypoint's 48 bytes per account entry and 72 per distinct account, the discriminant lines, the
|
|
185
|
+
event recorder, the status checks' messages (built even when they pass), each batch line, each SPL Token transfer's
|
|
186
|
+
instruction, the cancels' boxed tree iterators with their stacks and the ids they collect, CancelMultipleOrdersById's
|
|
187
|
+
decoded list and kept ids, the multiple-order packet's decoded lists, its sorts (the merge sort's buffer and stack of
|
|
188
|
+
runs) and the "Insufficient funds" lines of the orders it skips, the placed order ids and their Borsh bytes. So a
|
|
189
|
+
transaction that fills the heap (with up to 255 account entries, which Phoenix ignores past the ones it reads, or with
|
|
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
|
|
192
|
+
sides of it (one account entry fewer succeeds, the next aborts) for CancelAllOrders and its free-funds form (257 to
|
|
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
|
+
with a search limit, ForceCancelOrders, CancelMultipleOrdersById through a CPI (230 and 340 entries; 341 always runs
|
|
195
|
+
out), and PlaceMultiplePostOnlyOrders through a CPI (decoded lists past their first 85 orders, scrambled sides, 130
|
|
196
|
+
resting orders, token deposits, skipped orders).
|
|
197
|
+
- **More than a transaction carries.** A CPI passes up to 10,240 bytes of instruction data, so a multiple-order packet
|
|
198
|
+
is decoded whatever its length, as Phoenix decodes it: past 170 orders a side always runs out of memory at its sort,
|
|
199
|
+
and past 340 while decoding; from 64 resting orders set_return_data refuses the ids (1,028 bytes and up), after every
|
|
200
|
+
order is placed and every batch sent, in both.
|
|
201
|
+
- **Memory, not counted.** What Phoenix formats only when it fails is not charged: assert_with_msg's line with its
|
|
202
|
+
location, the formatted failure lines (an IOC's minimum fill, "Market is not active, …"), the String of a Borsh
|
|
203
|
+
decoding error, the panic handler's line. Phoenix builds each on the heap before it reports the failure, so when the
|
|
204
|
+
heap no longer has room for it Phoenix aborts with the out-of-memory line (ProgramFailedToComplete) where the port
|
|
205
|
+
logs the failure and returns its error. A transaction gets there only by failing after it has nearly filled the
|
|
206
|
+
heap. For instance a forwarded multiple-order packet of 300 bids whose asks are cut short fails with BorshIoError in
|
|
207
|
+
both with few account entries and runs out of memory in both (its decoded Vec's last growth) with many; in between,
|
|
208
|
+
at one account count, Phoenix runs out of memory building the error's message (about 100 bytes) while the port
|
|
209
|
+
returns BorshIoError. A formatted failure line after a long match would need the same kind of near-full heap.
|
|
210
|
+
Neither are InitializeMarket's, CollectFees' and the seat and governance
|
|
211
|
+
instructions' own lines and vectors charged (only their batches): with at most 128 distinct accounts, the most a
|
|
212
|
+
transaction locks, they stay far below the heap. A Limit order's crossing check (a boxed iterator) and a match's
|
|
213
|
+
batches are counted, but no test reaches the limit with them: it takes a match of about a thousand fills and more
|
|
214
|
+
distinct accounts than a transaction holds without lookup tables.
|
|
215
|
+
- **Damaged trees.** A tree walk keeps its stack of 64 nodes on the program's stack, more than any red-black tree a u32
|
|
216
|
+
index can address holds on one path; only damaged registers go deeper, and the port panics where sokoban's heap stack
|
|
217
|
+
would grow. The panics of a node index out of range (`nodeAt` on damaged registers) take their locations from
|
|
218
|
+
sokoban's source, not from the binary.
|
|
219
|
+
- **Paths v1 never takes.** An order of zero lots on a book (only bytes written by hand put one there) is removed as
|
|
220
|
+
the original removes it: a cancel meeting one is tested, the matching engine's two such paths ("Empty order found in
|
|
221
|
+
check_for_cross", a tombstone met while matching) are ported but not reached by a test. The unclean-division warning
|
|
222
|
+
of a bid's unlock, which no market InitializeMarket accepts can produce, is tested on written bytes.
|
|
223
|
+
|
|
224
|
+
The tests run on LiteSVM without account-data direct mapping; both programs write the market in place, so both would
|
|
225
|
+
fault at the same write. The runtime truncates a transaction's log at 10,000 bytes at a point that depends on the
|
|
226
|
+
compute-unit lines, which differ by design, so the harness lifts that limit to compare the whole log.
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Case study: SPL Stake Pool
|
|
2
|
+
|
|
3
|
+
This page ports [SPL Stake Pool](https://github.com/solana-program/stake-pool) (Apache-2.0), the program behind most
|
|
4
|
+
liquid staking tokens on Solana (JitoSOL's pool is one of its accounts). The port is checked against the binary that
|
|
5
|
+
runs on mainnet as `SPoo1Ku8WFXoNDMHPsrGSTSG1Y47rzgn41SLUNakuHy` (deployed in slot 429882117, 2026-06-30), not a
|
|
6
|
+
rebuild.
|
|
7
|
+
|
|
8
|
+
**Which source.** The binary's security.txt names `program@v2.0.3`, but that string is fixed in the source and the
|
|
9
|
+
deployed code carries a fee-cap message main only gained later. The tag `program@v2.1.0` (54cdced, on a release
|
|
10
|
+
branch) rebuilt with `solana-verify build --library-name spl_stake_pool --base-image
|
|
11
|
+
solanafoundation/solana-verifiable-build:3.1.14` gives the deployed executable's hash
|
|
12
|
+
(`8df58bc9f9428c02bf34fa845ae2961274156e7ff07a8dc1be0018dd765baeff`). The port follows that tag
|
|
13
|
+
([`test/programs/SOURCES.md`](../test/programs/SOURCES.md)).
|
|
14
|
+
|
|
15
|
+
Stake Pool is a native program: one entrypoint decodes a Borsh instruction (a tag byte, then the variant's fields,
|
|
16
|
+
every byte consumed), the processor takes its accounts by position, the pool account is plain Borsh with Options and
|
|
17
|
+
data enums, the validator list is a header and a `BigVec` of 73-byte entries over a preallocated account of up to
|
|
18
|
+
20,000 validators, and every stake move is a CPI into the Stake program across epochs.
|
|
19
|
+
|
|
20
|
+
| File | Holds |
|
|
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 |
|
|
25
|
+
| `admin.ts`, `validators.ts`, `update.ts`, `sol.ts`, `stake_deposit.ts`, `stake_withdraw.ts`, `rebalance.ts`, `metadata.ts` | the instructions by subject |
|
|
26
|
+
|
|
27
|
+
## What is ported
|
|
28
|
+
|
|
29
|
+
All 27 instructions: Initialize; adding, removing and cleaning up validators and the preferred validators; the epoch
|
|
30
|
+
update of the list and of the pool; SOL and stake deposits and withdrawals with their slippage forms; increasing and
|
|
31
|
+
decreasing validator stake (the deprecated decrease, the additional forms with ephemeral stake, the decrease funded
|
|
32
|
+
from the reserve); the manager's and staker's setters and the funding authorities; the Metaplex token metadata; and
|
|
33
|
+
Redelegate, which the deployed program refuses ("will not be enabled"), as the port does.
|
|
34
|
+
|
|
35
|
+
## What it needed
|
|
36
|
+
|
|
37
|
+
TypeSOL gained these features for it (docs/language.md, "Porting a native program"; every other program compiles
|
|
38
|
+
to the same C as before):
|
|
39
|
+
|
|
40
|
+
- `loadBorsh<T>` / `storeBorsh`: a Borsh account without a discriminator, read into a local struct and written back
|
|
41
|
+
as `try_from_slice_unchecked` and `serialize` do, the bytes after a shrunk value left as they were (about 280 CU to
|
|
42
|
+
read the 611-byte pool, 610 to read and write it).
|
|
43
|
+
- `BigVec<T>`: SPL's `big_vec`, a list over the rest of an account with `push`, `retain`, `slice` and the list
|
|
44
|
+
methods, its loops emitted as functions of their own so they keep their registers (16 CU per entry for the pool's
|
|
45
|
+
update sum, against the original's 27).
|
|
46
|
+
- `programAt<P>` / `sysvarAt<S>` and typed CPIs that take remaining accounts, the Stake program's `split`, `merge`,
|
|
47
|
+
`getMinimumDelegation` and lockups, and `named(account, address)`: a sysvar named by address as solana_program's
|
|
48
|
+
builders name it, with the slot's account passed as Rust's `invoke_signed` passes it.
|
|
49
|
+
- `NATIVE_ACCOUNT_WRITES`: account data written in place and judged by the runtime afterwards, as a native program's
|
|
50
|
+
is; `epochRewards()`; `panic(null, location)` and `abort()`; local lists, the instruction data as a list and
|
|
51
|
+
`invokeInstruction` in helpers (the Metaplex CPI); a ternary between accounts.
|
|
52
|
+
- In `typesol/testing`: `warpToEpoch`, `StakeCluster` (the StakeHistory a cluster writes, so stake warms up and cools
|
|
53
|
+
down over epochs as on mainnet, matched to the runtime's Stake program to the lamport), and vote and stake account
|
|
54
|
+
builders.
|
|
55
|
+
|
|
56
|
+
## How it is checked
|
|
57
|
+
|
|
58
|
+
The mainnet binary and the port run in two LiteSVMs under the same program id, with the same clock and the same
|
|
59
|
+
StakeHistory written into both by one `StakeCluster`. Every transaction must give the same outcome, the same log
|
|
60
|
+
lines (the "Instruction: …" lines, every message with its numbers, the error lines, panic locations) and the same
|
|
61
|
+
bytes in every account it names. There are 2,107 such transactions in six files:
|
|
62
|
+
|
|
63
|
+
- **The instructions** (`spl-stake-pool.test.ts`, `-stake`, `-rebalance`, `-metadata`; 1,406): every instruction's
|
|
64
|
+
success paths and every refusal that can be built, account by account (wrong signers, PDAs, owners, mints and
|
|
65
|
+
Token-2022 extensions, sysvars, short account lists), fee limits, slippage, preferred validators, funding
|
|
66
|
+
authorities, read-only and repeated accounts (the original's RefCell panics included), pools of 50 to 60 validators,
|
|
67
|
+
warmup and cooldown over several epochs.
|
|
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
|
|
70
|
+
were covered already, 78 are added there, none is left out. huge_pool.rs runs at 3,000 and 20,000 validators.
|
|
71
|
+
- **A random walk over epochs** (`spl-stake-pool-fuzz.test.ts`): validators added and removed, users depositing and
|
|
72
|
+
withdrawing SOL and stake, rebalancing, updates in random chunks, fee and authority changes, rewards, slow warmup,
|
|
73
|
+
and invalid inputs at a low rate (`FUZZ_SEED`, `STAKE_POOL_FUZZ_STEPS`). Five seeds of 600 steps (215 epochs, about
|
|
74
|
+
3,700 transactions) found no difference. Each run is 1,000 steps by default and requires every main kind of
|
|
75
|
+
instruction (SOL and stake deposits and withdrawals, increases, decreases, both updates, adding a validator) to
|
|
76
|
+
succeed at least once.
|
|
77
|
+
|
|
78
|
+
The random walk found one: a stake withdrawal that searched the list in one pass where the original searches twice
|
|
79
|
+
ran out of the default compute budget at 3,550 validators, where the original does not. The port now searches as the
|
|
80
|
+
original does, and a regression case runs at 3,550 validators.
|
|
81
|
+
|
|
82
|
+
## Cost
|
|
83
|
+
|
|
84
|
+
Compute units per transaction, mainnet original against the port, from those tests (the stake, token and Metaplex
|
|
85
|
+
CPIs are the same work in both; the port's own part is about a third of the original's):
|
|
86
|
+
|
|
87
|
+
| Instruction | Original | TypeSOL | |
|
|
88
|
+
| --- | ---: | ---: | ---: |
|
|
89
|
+
| `Initialize` | 16,535 | 6,311 | 38% |
|
|
90
|
+
| `DepositSol` | 16,090 | 7,090 | 44% |
|
|
91
|
+
| `WithdrawSol` | 21,247 | 12,236 | 58% |
|
|
92
|
+
| `AddValidatorToPool` | 41,117 | 31,518 | 77% |
|
|
93
|
+
| `RemoveValidatorFromPool` | 21,027 | 14,868 | 71% |
|
|
94
|
+
| `UpdateValidatorListBalance`, 12 validators | 104,835 | 29,605 | 28% |
|
|
95
|
+
| `UpdateStakePoolBalance` | 10,080 | 3,554 | 35% |
|
|
96
|
+
| `CleanupRemovedValidatorEntries` | 4,847 | 944 | 19% |
|
|
97
|
+
| `DepositStake` | 86,950 | 64,353 | 74% |
|
|
98
|
+
| `WithdrawStake` | 67,809 | 52,184 | 77% |
|
|
99
|
+
| `IncreaseValidatorStake` | 42,088 | 33,109 | 79% |
|
|
100
|
+
| `DecreaseValidatorStakeWithReserve` | 59,340 | 47,497 | 80% |
|
|
101
|
+
| `SetFee` | 3,624 | 1,628 | 45% |
|
|
102
|
+
| `UpdateTokenMetadata` (without Metaplex's part) | 10,250 | 5,285 | 52% |
|
|
103
|
+
|
|
104
|
+
At 20,000 validators (huge_pool.rs, with a 1.4M CU budget): `UpdateStakePoolBalance` 547,385 against 321,997 (59%),
|
|
105
|
+
the cleanup 184,870 against 101,025 (55%), `DepositStake` 611,313 against 153,300 (25%), `WithdrawStake` 783,846
|
|
106
|
+
against 310,716 (40%). Within the default 200,000 the port updates a pool of 6,800 validators in 110,647 and cleans up
|
|
107
|
+
19,000 in 95,875, as the original does in 190,835 and 175,720.
|
|
108
|
+
|
|
109
|
+
The binary is 202,240 bytes against the original's 338,912.
|
|
110
|
+
|
|
111
|
+
## Differences
|
|
112
|
+
|
|
113
|
+
None that a transaction can reach. Two need the pool's bytes rewritten by hand, which no instruction allows:
|
|
114
|
+
|
|
115
|
+
- The validator list given again in the place of an account the pool stores (the reserve, the mint, the fee account):
|
|
116
|
+
the original would panic on a second borrow of the list there; the port does not model that borrow.
|
|
117
|
+
- A withdraw authority whose stored bump is not the canonical one: the metadata instructions sign with the stored bump,
|
|
118
|
+
the original finds the canonical one again.
|
|
119
|
+
|
|
120
|
+
The tests run on LiteSVM, whose Stake program computes warmup with the f64 formula; `StakeCluster` follows it
|
|
121
|
+
(`math: "integer"` when the runtime moves to the integer one). Account-data direct mapping is not enabled there; both
|
|
122
|
+
programs write in place, so both would fault at the same write.
|
package/docs/errors.md
CHANGED
|
@@ -39,7 +39,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
|
|
|
39
39
|
| 4102 | cast overflow (InvalidNumericConversion) |
|
|
40
40
|
| 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
|
|
41
41
|
| 5103 | sysvar unavailable |
|
|
42
|
-
| 5104 | index out of bounds (arrays, Vecs, remaining accounts, `pop()` on an empty Vec, `push` on a full FixedVec, a stored `map` / `filter` result one element too small) |
|
|
42
|
+
| 5104 | index out of bounds (arrays, Vecs, remaining accounts, `pop()` on an empty Vec, `push` on a full FixedVec or `pushAll` past its room, a `slice` of the instruction data out of range, a stored `map` / `filter` result one element too small) |
|
|
43
43
|
| 5105 | string longer than the FixedString capacity |
|
|
44
44
|
| 5106 | missing or mismatched return data |
|
|
45
45
|
| 5107 | event larger than 1024 bytes |
|