@typesol/cli 0.45.0 → 0.46.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 +227 -0
- package/README.md +64 -17
- package/SECURITY.md +9 -7
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/cli.js +33 -15
- package/dist/compiler/analyze.js +57 -6
- package/dist/compiler/diagnostics.d.ts +4 -3
- package/dist/compiler/diagnostics.js +10 -6
- package/dist/compiler/emit/base.d.ts +1 -1
- package/dist/compiler/emit/calls.js +18 -5
- package/dist/compiler/emit/cpi-core.d.ts +3 -1
- package/dist/compiler/emit/cpi-core.js +8 -4
- package/dist/compiler/emit/expressions.d.ts +14 -0
- package/dist/compiler/emit/expressions.js +52 -4
- package/dist/compiler/emit/shared.d.ts +8 -1
- package/dist/compiler/emit/shared.js +8 -1
- package/dist/compiler/emit/statements.d.ts +8 -3
- package/dist/compiler/emit/statements.js +68 -3
- package/dist/compiler/emit/storage.js +5 -1
- package/dist/compiler/hints.d.ts +7 -0
- package/dist/compiler/hints.js +58 -9
- package/dist/compiler/index.d.ts +5 -0
- package/dist/compiler/index.js +10 -1
- package/dist/compiler/model.js +3 -2
- package/dist/compiler/toolchain.d.ts +50 -2
- package/dist/compiler/toolchain.js +96 -11
- package/dist/node-version.d.ts +4 -0
- package/dist/node-version.js +12 -0
- package/dist/tools/doctor.d.ts +41 -0
- package/dist/tools/doctor.js +96 -14
- package/dist/workspace.d.ts +9 -2
- package/dist/workspace.js +13 -3
- package/docker/deps/0.46.0.lock.json +1206 -0
- package/docs/ai.md +2 -1
- package/docs/architecture.md +7 -3
- package/docs/audit.md +6 -6
- package/docs/case-study-phoenix.md +1 -1
- package/docs/case-study-raydium-amm.md +1 -1
- package/docs/case-study-spl-stake-pool.md +1 -1
- package/docs/cli.md +42 -4
- package/docs/errors.md +22 -8
- package/docs/glossary.md +210 -0
- package/docs/language-accounts.md +499 -0
- package/docs/language-basics.md +389 -0
- package/docs/language-builtins.md +411 -0
- package/docs/language-chain.md +198 -0
- package/docs/language-cpi.md +470 -0
- package/docs/language-errors-events.md +184 -0
- package/docs/language-native.md +493 -0
- package/docs/language-pdas.md +198 -0
- package/docs/language-statements.md +620 -0
- package/docs/language-types.md +601 -0
- package/docs/language.md +190 -467
- package/docs/mainnet.md +18 -3
- package/docs/migrate-from-anchor.md +7 -6
- package/docs/security-model.md +3 -3
- package/docs/stability.md +3 -1
- package/docs/test-your-program.md +52 -15
- package/docs/troubleshooting.md +222 -100
- package/lib/typesol.d.ts +67 -22
- package/llms-full.txt +4915 -634
- package/llms.txt +12 -1
- package/package.json +2 -2
- package/releases/0.45.0.json +732 -0
- package/ts-plugin/index.js +16 -5
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
# Porting a native program (advanced)
|
|
2
|
+
|
|
3
|
+
> This page is advanced. Programs written for TypeSOL from the start, and ports of Anchor programs, need none of it:
|
|
4
|
+
> they use instructions with typed accounts ([accounts](language-accounts.md)). Read on to port a program written
|
|
5
|
+
> without Anchor and keep its exact behaviour: the same instruction data, account bytes, errors and log lines.
|
|
6
|
+
|
|
7
|
+
A program written without Anchor (Raydium AMM v4, SPL programs, Phoenix) reads a tag byte and its arguments itself,
|
|
8
|
+
takes its accounts by position, stores accounts without discriminators and reports failures its own way. TypeSOL
|
|
9
|
+
ports one as it is: the showcase ports ([`showcase/mainnet/raydium-amm`](https://github.com/typesol-lang/typesol/tree/main/showcase/mainnet/raydium-amm), `spl-stake-pool`, `phoenix`) run beside the
|
|
10
|
+
original binaries, and [`test/fixtures/native.ts`](https://github.com/typesol-lang/typesol/blob/main/test/fixtures/native.ts) is a small one. Part of the [language guide](language.md).
|
|
11
|
+
|
|
12
|
+
## The fallback entry
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { type AccountInfo, type Mut, ProgramError, instructionData, remainingAccounts, require, u64, writeData } from "typesol";
|
|
16
|
+
|
|
17
|
+
/** @fallback */
|
|
18
|
+
export function entry(): void {
|
|
19
|
+
const data = instructionData();
|
|
20
|
+
require(data.length >= 9n, ProgramError.InvalidInstructionData);
|
|
21
|
+
const tag = data.readU8(0n);
|
|
22
|
+
const amount = data.readU64(1n);
|
|
23
|
+
const rest = remainingAccounts();
|
|
24
|
+
if (tag === 1n) {
|
|
25
|
+
const total = data.slice(1n, 9n).reduce((s, b) => s + u64(b), 0n);
|
|
26
|
+
require(total > 0n || amount === 0n, ProgramError.InvalidArgument);
|
|
27
|
+
}
|
|
28
|
+
require(rest.length >= 1n, ProgramError.NotEnoughAccountKeys);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function record(target: Mut<AccountInfo>, value: u64): void {
|
|
32
|
+
writeData<u64>(target, 0n, value);
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`record` is there to show that instructions and a fallback coexist: as written, anyone can overwrite the first 8 bytes
|
|
37
|
+
of any account this program owns.
|
|
38
|
+
|
|
39
|
+
`/** @fallback */ export function name(): void` is Anchor's `fallback`: it runs when no instruction's discriminator
|
|
40
|
+
matches the data (short data too) instead of failing with 101. A program may have only a fallback, as a native
|
|
41
|
+
program does, or instructions and a fallback.
|
|
42
|
+
|
|
43
|
+
- It takes no parameters and reads `const data = instructionData()` (the whole data) and `remainingAccounts()` (the
|
|
44
|
+
accounts by position). It is not in the IDL.
|
|
45
|
+
- The data is a read-only list of u8: `data.length`, `data.get(i)`, `data.readU8/U16/U32/U64/U128/readPubkey(offset)`
|
|
46
|
+
(little-endian, bounds-checked: 5104), `for (const b of data)`, `map` / `filter` / `reduce` / `some` and the other
|
|
47
|
+
list methods.
|
|
48
|
+
- `data.slice(start, end?)` is a view, nothing copied. Unlike JavaScript it does not clamp: past the length it fails
|
|
49
|
+
with 5104. `out.pushAll(data.slice(a, b))` copies into a local FixedVec (a memcpy).
|
|
50
|
+
- A helper takes the data, or a slice of it, as an `InstructionBytes` parameter; bind it to a const first
|
|
51
|
+
(`const data = instructionData()`) and pass `data`.
|
|
52
|
+
- Calls to System, Token and Stake go through `programAt<P>(acct)` and the typed methods, with remaining accounts, not
|
|
53
|
+
hand-encoded `invoke` data ([programs passed as remaining
|
|
54
|
+
accounts](language-cpi.md#programs-and-sysvars-passed-as-remaining-accounts)).
|
|
55
|
+
|
|
56
|
+
## Accounts without a discriminator
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { type AccountInfo, type Mut, type Pubkey, type u64, ProgramError, loadRaw, loadRawMut, require } from "typesol";
|
|
60
|
+
|
|
61
|
+
export interface Header {
|
|
62
|
+
version: u64;
|
|
63
|
+
admin: Pubkey;
|
|
64
|
+
total: u64;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function bump(market: Mut<AccountInfo>, admin: AccountInfo, amount: u64): void {
|
|
68
|
+
require(admin.isSigner, ProgramError.MissingRequiredSignature);
|
|
69
|
+
require(market.dataLen === 48n, ProgramError.InvalidAccountData);
|
|
70
|
+
require(loadRaw<Header>(market).version === 1n, ProgramError.InvalidAccountData);
|
|
71
|
+
const header = loadRawMut<Header>(market);
|
|
72
|
+
require(header.admin === admin.key, ProgramError.IllegalOwner);
|
|
73
|
+
header.total += amount;
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view an account as a fixed-layout struct from byte 0: owned by this
|
|
78
|
+
program (3007), at least the struct's size (3003); `loadRawMut` also writable (3006) and loaded once. Structs are
|
|
79
|
+
packed, as `#[repr(C, packed)]`.
|
|
80
|
+
- Make the original's own checks (an exact size, its error codes) before the load.
|
|
81
|
+
- An `AccountInfo` is not checked at all, so a key compared with a stored one proves nothing until the account signed:
|
|
82
|
+
`bump` checks `admin.isSigner` first, as a native program does (`MissingRequiredSignature`).
|
|
83
|
+
- A read-only view can be read where it is made, `loadRaw<Header>(market).inner.b` or `loadRawAt<Prefix>(market,
|
|
84
|
+
576n).tick` (its checks made there). A writable one claims its account once per instruction, so it is bound to a
|
|
85
|
+
const first.
|
|
86
|
+
- The owner check of these views (and of `loadRawAt`, `rawArrayAt`, `rbTreeAt` below) is made every time, but the last
|
|
87
|
+
account found to be this program's passes again with one pointer compare instead of 32 bytes until a CPI or an owner
|
|
88
|
+
write (`assignOwner`, `closeRaw`, `close`). Helpers that each view the market again, and views in loops, pay about
|
|
89
|
+
3 compute units for it instead of about 14.
|
|
90
|
+
|
|
91
|
+
### Borsh accounts
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { type AccountInfo, type Mut, type Option, type Pubkey, type u64, ProgramError, loadBorsh, programId, require, storeBorsh } from "typesol";
|
|
95
|
+
|
|
96
|
+
/** @layout borsh */
|
|
97
|
+
export interface StakePool {
|
|
98
|
+
manager: Pubkey;
|
|
99
|
+
totalLamports: u64;
|
|
100
|
+
fee: Option<u64>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function deposit(pool: Mut<AccountInfo>, amount: u64): void {
|
|
104
|
+
require(pool.owner === programId(), ProgramError.IllegalOwner);
|
|
105
|
+
const state = loadBorsh<StakePool>(pool);
|
|
106
|
+
state.totalLamports += amount;
|
|
107
|
+
if (state.fee === null) state.fee = 0n;
|
|
108
|
+
storeBorsh(pool, state);
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`deposit` shows the decoding and encoding only: the owner is checked, but as written any caller raises
|
|
113
|
+
`totalLamports`, and the original also checks that the pool is initialized.
|
|
114
|
+
|
|
115
|
+
SPL Stake Pool's `StakePool` is read with `try_from_slice_unchecked` and written with `serialize`.
|
|
116
|
+
`const pool = loadBorsh<StakePool>(acct)` decodes the data from byte 0 into a local struct (a copy: fields updated,
|
|
117
|
+
Options narrowed and set to null or a value, data enums switched, copied, passed to helpers), and `storeBorsh(acct,
|
|
118
|
+
pool)` encodes it back from byte 0.
|
|
119
|
+
|
|
120
|
+
- As in Rust: no owner check and no discriminator; check the owner first, as the original does and `deposit` does.
|
|
121
|
+
Bytes after the value are ignored when reading and left as they were when writing (an Option that became None
|
|
122
|
+
leaves its old bytes behind it).
|
|
123
|
+
- Data too short, an Option tag or boolean other than 0/1, an enum tag out of range, a String that is not UTF-8 or
|
|
124
|
+
longer than its `FixedString<N>`, or an account too small for the encoding fail with `ProgramError.BorshIoError`.
|
|
125
|
+
- `acct` is a remaining account, a `RemainingAccount` helper parameter or an `AccountInfo` parameter (`Mut<AccountInfo>`
|
|
126
|
+
for `storeBorsh`; a remaining account must be writable, 3006).
|
|
127
|
+
- `T` may hold integers, booleans, Pubkeys, enums, FixedArrays, `FixedString<N>`, `FixedVec<T, N>`, Options, data enums
|
|
128
|
+
with fixed-size payloads and nested structs of those, with or without `@layout borsh`; not `Vec<T>` or `string`
|
|
129
|
+
(they would need the heap or a view).
|
|
130
|
+
- Each struct gets its own straight-line decoder and encoder (no heap): about 280 CU to read a 611-byte `StakePool`
|
|
131
|
+
and 610 CU to read and write it back. The local lives on the stack (4 KiB per function).
|
|
132
|
+
|
|
133
|
+
## Lists over the rest of an account: BigVec
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { type BigVec, type Mut, type AccountInfo, type Pubkey, type u64, loadRawMut } from "typesol";
|
|
137
|
+
|
|
138
|
+
export interface ValidatorInfo {
|
|
139
|
+
vote: Pubkey;
|
|
140
|
+
lamports: u64;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface ValidatorList {
|
|
144
|
+
maxValidators: u64;
|
|
145
|
+
validators: BigVec<ValidatorInfo>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function add(list: Mut<AccountInfo>, vote: Pubkey, skip: u64): void {
|
|
149
|
+
const l = loadRawMut<ValidatorList>(list);
|
|
150
|
+
if (l.validators.findIndex((v) => v.vote === vote) < 0n) l.validators.push({ vote, lamports: 0n });
|
|
151
|
+
l.validators.retain((v) => v.lamports > 0n || v.vote === vote);
|
|
152
|
+
for (const v of l.validators.slice(skip, l.validators.length)) v.lamports += 1n;
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`add` shows the list operations only: as written, anyone can push to any account this program owns.
|
|
157
|
+
|
|
158
|
+
`validators: BigVec<ValidatorInfo>` is SPL's `big_vec` (the stake pool's validator list): the last field of a
|
|
159
|
+
fixed-layout struct read with `loadRaw` / `loadRawMut`, a u32 length then the elements, in an account allocated up
|
|
160
|
+
front. Its room is the account's (`.capacity`: (size − fixed fields − 4) / size(T)), and it is never resized.
|
|
161
|
+
|
|
162
|
+
- Loading checks that the length fits (ProgramError::AccountDataTooSmall), and every access afterwards is bounded by
|
|
163
|
+
the room as well: a length written again after the load (`writeData`, another view, `storeBorsh`) is read as at most
|
|
164
|
+
`.capacity`, so `.length`, `get` / `set`, the loops, `slice` and `retain` never reach past the account. The load fails
|
|
165
|
+
where the Rust would only panic on reaching such an element: check the length first (`readData<u32>(acct, offset)`)
|
|
166
|
+
where the original returns an error of its own before that.
|
|
167
|
+
- `get` / `set` (5104 past the length), `push(v)` (AccountDataTooSmall when full, as `BigVec::push`), `retain((x) =>
|
|
168
|
+
keep)` (in place, one pass, kept runs moved with the memmove syscall; bytes past the new end keep what they held, as
|
|
169
|
+
`BigVec::retain`), `for … of`, the list callbacks (`findIndex`, `find(f)!.field` on struct elements), `.length`.
|
|
170
|
+
- `list.slice(start, end?)` is `BigVec::deserialize_mut_slice(start, end − start)`, used where it is written
|
|
171
|
+
(`for (const v of l.validators.slice(skip, skip + n))`, `.slice(a, b).forEach(…)`, `.get(i)`, `.length`). Out of
|
|
172
|
+
range fails with AccountDataTooSmall instead of clamping.
|
|
173
|
+
- Elements are references into the account.
|
|
174
|
+
- Not an account parameter, an argument, a local, nested, or in a `@layout borsh` struct.
|
|
175
|
+
|
|
176
|
+
## Views at run-time offsets
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import { type AccountInfo, type Mut, type u64, ProgramError, loadRawAt, rawArrayMutAt, require } from "typesol";
|
|
180
|
+
|
|
181
|
+
export interface Prefix {
|
|
182
|
+
tick: u64;
|
|
183
|
+
count: u64;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function fill(market: Mut<AccountInfo>, at: u64, n: u64): void {
|
|
187
|
+
require(market.dataLen >= 576n, ProgramError.InvalidAccountData);
|
|
188
|
+
const prefix = loadRawAt<Prefix>(market, at);
|
|
189
|
+
const slots = rawArrayMutAt<u64>(market, at + 16n, n);
|
|
190
|
+
for (let i = 0n; i < slots.length; i++) slots.set(i, prefix.tick + i);
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
`fill` shows the views only: as written, anyone can overwrite slots of any account this program owns.
|
|
195
|
+
|
|
196
|
+
A native account whose parts start where its header says (Phoenix's market at byte 576, trees sized by
|
|
197
|
+
`market_size_params`, Serum's slabs):
|
|
198
|
+
|
|
199
|
+
- `loadRawAt<T>(acct, offset)` / `loadRawMutAt<T>(acct, offset)` are `loadRaw` / `loadRawMut` at a byte offset known
|
|
200
|
+
only at run time.
|
|
201
|
+
- `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt<T>(…)` are `capacity` elements of a fixed-size type
|
|
202
|
+
(integers, booleans, Pubkeys, enums, `FixedString<N>`, structs) packed in place from there, the count a run-time u64:
|
|
203
|
+
`get` / `set` (5104 past the count), `.length` (the capacity), `for … of` and the list methods, structs by
|
|
204
|
+
reference.
|
|
205
|
+
- The bounds are checked once, when the view is made (`offset + size`, with overflow, within the data:
|
|
206
|
+
ProgramError::AccountDataTooSmall; `loadRaw`'s fixed size check stays 3003, the error of a view whose size is known
|
|
207
|
+
when the program is compiled), as Phoenix slices `&data[576..]` after checking the account's size itself. Element
|
|
208
|
+
access is pointer arithmetic.
|
|
209
|
+
- Owner (3007), writability and the one-mutable-view claim (2040) are `loadRaw` / `loadRawMut`'s, so several mutable
|
|
210
|
+
views of one account need `NATIVE_ACCOUNT_WRITES` ([below](#writes-as-the-original-makes-them)), as a native port
|
|
211
|
+
declares.
|
|
212
|
+
- Bind them with const; they are not helper parameters. `rbTreeAt(…).length` and `.capacity` read a tree made for the
|
|
213
|
+
one read; anything else on a tree or a raw array is done on a const bound to it.
|
|
214
|
+
- A view (and anything read through it) is not used after `closeRaw` or `resizeAccount` of an account it may view, or
|
|
215
|
+
after a helper that may close or resize one it is given: its bounds were checked against the old length, so it is a
|
|
216
|
+
compile error saying to take the view again.
|
|
217
|
+
|
|
218
|
+
## lib-sokoban's red-black tree
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { type AccountInfo, type Mut, type i8, type u64, ProgramError, rbTreeMutAt, require } from "typesol";
|
|
222
|
+
|
|
223
|
+
export interface OrderId {
|
|
224
|
+
price: u64;
|
|
225
|
+
seq: u64;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export interface Resting {
|
|
229
|
+
trader: u64;
|
|
230
|
+
lots: u64;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function byPrice(a: OrderId, b: OrderId): i8 {
|
|
234
|
+
if (a.price !== b.price) return a.price < b.price ? -1n : 1n;
|
|
235
|
+
return a.seq < b.seq ? -1n : a.seq > b.seq ? 1n : 0n;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function place(market: Mut<AccountInfo>, capacity: u64, price: u64, seq: u64, trader: u64, lots: u64): void {
|
|
239
|
+
const asks = rbTreeMutAt<OrderId, Resting>(market, 8n, capacity, byPrice);
|
|
240
|
+
const at = asks.insert({ price, seq }, { trader, lots });
|
|
241
|
+
require(at !== null, ProgramError.InvalidArgument);
|
|
242
|
+
const best = asks.min();
|
|
243
|
+
if (best !== null && best.value.lots > 100n) best.value.lots -= 1n;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function cancel(market: Mut<AccountInfo>, capacity: u64, price: u64, seq: u64, trader: u64): void {
|
|
247
|
+
const asks = rbTreeMutAt<OrderId, Resting>(market, 8n, capacity, byPrice);
|
|
248
|
+
const at = asks.addrOf({ price, seq });
|
|
249
|
+
if (at !== 0n && asks.nodeAt(at).value.trader === trader) asks.removeAt(at);
|
|
250
|
+
let total = 0n;
|
|
251
|
+
for (const e of asks) total += e.value.lots;
|
|
252
|
+
require(total < 1000000n, ProgramError.InvalidArgument);
|
|
253
|
+
}
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
`rbTreeMutAt<K, V>(acct, offset, capacity, compare?)` (or `rbTreeAt` to read) is lib-sokoban 0.3's
|
|
257
|
+
`RedBlackTree<K, V, N>` over account bytes, byte for byte (root, allocator, 1-based nodes of registers + key + value;
|
|
258
|
+
freed nodes keep their key and value; a LIFO free list ending at the bump index), checked against the crate after every
|
|
259
|
+
operation of recorded traces ([`test/verification/rbtree-trace.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/verification/rbtree-trace.test.ts)). Every write is the crate's own, so the account
|
|
260
|
+
matches the original after every instruction (Phoenix's order books and trader seats).
|
|
261
|
+
|
|
262
|
+
`place` and `cancel` show the tree operations only: `trader` is an argument, so as written anyone can rest an order
|
|
263
|
+
under any trader or cancel any trader's order. Phoenix takes the trader from an account that signed and looks up its
|
|
264
|
+
seat in the market's trader tree before it touches the book.
|
|
265
|
+
|
|
266
|
+
- `length`, `capacity`, `initialize()`, `get(k)` (the value in place, or null), `insert(k, v)` (the node index, or null
|
|
267
|
+
when a new key finds it full; an equal key takes the value), `remove(k)` (the value, read in the freed node, or null),
|
|
268
|
+
`removeAt(i)` (the node at index `i` from `addrOf` or a node's `.index`, removed with `remove`'s writes without
|
|
269
|
+
searching again: 144 CU less per cancel in [`test/language/phx-costs.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/phx-costs.test.ts); null for 0 or a node in no tree),
|
|
270
|
+
`min()` / `max()` (a node: `.key`, `.value`, `.index`, or null), `addrOf(k)` (0 when absent), `nodeAt(i)` (Phoenix
|
|
271
|
+
keeps a trader's node index), `for (const e of tree)` / `tree.reversed()` with `break` / `continue`.
|
|
272
|
+
- **The comparator** is a function of the program, `(a: K, b: K) => i8` (any signed integer result; an unsigned one is
|
|
273
|
+
refused, as it could never say "less"), called as `compare(searchedKey, nodeKey)` (Phoenix's FIFOOrderId orders by
|
|
274
|
+
the left key's side). Without one, keys are ordered as Rust derives Ord (fields in order, integers by value, Pubkeys
|
|
275
|
+
bytewise).
|
|
276
|
+
- **References.** A reference into the tree (`get`, `min`, a node, however it is bound: `c ? t.min() : t.max()`,
|
|
277
|
+
`t.get(k)!`; a node is bound with const) cannot be used after an `insert` (it may reuse a freed node). A `for … of`
|
|
278
|
+
body cannot insert, remove or initialize on the tree it walks, nor on any tree view of an account that may be the
|
|
279
|
+
walked one's (another view of the same tree; under `NATIVE_ACCOUNT_WRITES` any account may be), nor call a helper
|
|
280
|
+
that takes accounts and makes an `rbTreeMutAt` view. These are compile errors, as Rust's borrows are.
|
|
281
|
+
- **Cost.** The C runs sokoban's get_addr / _insert / _remove / rotations / allocator statement for statement, with the
|
|
282
|
+
node stride a constant. With 512 entries: get 166 CU, insert 493, remove 294, min 94; with 4096: 215 / 595 / 355 /
|
|
283
|
+
112, against 300 / 604 / 497 / 191 and 384 / 742 / 618 / 225 for lib-sokoban built with cargo-build-sbf. A walk
|
|
284
|
+
costs about 34 compute units per node, a sum in its body included (each node's index checked once, when the walk
|
|
285
|
+
reaches it).
|
|
286
|
+
- **Iteration** keeps its stack on the program's stack (64 nodes, more than any red-black tree a u32 index can address
|
|
287
|
+
holds on one path); a deeper, damaged tree panics where the Rust's heap stack would grow.
|
|
288
|
+
- A tree is a const of the function that makes it, not a helper parameter (make it again in the helper from the
|
|
289
|
+
account).
|
|
290
|
+
- **Panics.** sokoban's panics are Rust panics in the original; the tree reproduces each as solana-program up to 1.17
|
|
291
|
+
reports one (Phoenix's build): the log line `panicked at '<message>', <file>:<line>:<column>`, then the runtime's
|
|
292
|
+
abort ("SBF program panicked", ProgramFailedToComplete), with sokoban's messages and source lines as Phoenix's binary
|
|
293
|
+
holds them (`src/…`):
|
|
294
|
+
- `initialize()` on an allocator that is not all zero: "Cannot reinitialize NodeAllocator"
|
|
295
|
+
(src/node_allocator.rs:249:13);
|
|
296
|
+
- an empty tree's insert with no room (capacity 0, or a damaged allocator): "Buffer is full, size N" (:269:17);
|
|
297
|
+
- on damaged registers only: "Nodes are not connected" (src/red_black_tree.rs:429:13), "assertion failed:
|
|
298
|
+
self.is_root(parent)" (:503:17), "assertion failed: self.is_leaf(max_left)" (:598:17), a size going below zero
|
|
299
|
+
("attempt to subtract with overflow", src/node_allocator.rs:291:9);
|
|
300
|
+
- a node index outside 1..capacity, from `nodeAt` or a damaged register, panics as Rust's `nodes[i - 1]` would
|
|
301
|
+
("index out of bounds: the len is N but the index is I", src/node_allocator.rs:255:10; index 0, "attempt to
|
|
302
|
+
subtract with overflow", :255:21: locations read from the source, not from a binary), so a damaged tree never
|
|
303
|
+
reads outside the account.
|
|
304
|
+
|
|
305
|
+
A port makes the original's checks in the original's order before the tree call, and these lines follow on their own.
|
|
306
|
+
|
|
307
|
+
## Writes as the original makes them
|
|
308
|
+
|
|
309
|
+
`export const NATIVE_ACCOUNT_WRITES = true` (anywhere in the program; opt-in, for native ports).
|
|
310
|
+
|
|
311
|
+
A native program writes account data in place and the runtime judges afterwards: a read-only account whose data
|
|
312
|
+
actually changed fails the instruction (`ReadonlyDataModified`, or an access violation at the write under account-data
|
|
313
|
+
direct mapping), one that was only read (or written with the bytes it held) is fine, and an account passed twice is two
|
|
314
|
+
`AccountInfo`s over one buffer.
|
|
315
|
+
|
|
316
|
+
- **By default** `loadRawMut` and `storeBorsh` check writability up front (3006), `loadRawMut` claims the account once
|
|
317
|
+
and `storeBorsh` refuses an account passed more than once (2040, as a write to a remaining account's lamports). So a
|
|
318
|
+
port fails where the original succeeds (a read-only validator list that is only read; the list passed again as a
|
|
319
|
+
stake account, which the original skips by its address checks).
|
|
320
|
+
- **With the flag**, `loadRawMut`, `storeBorsh` and the BigVec writes through a `loadRawMut` view skip both, and both
|
|
321
|
+
take a plain `AccountInfo` parameter (no `Mut<…>` needed). Owner and size checks stay.
|
|
322
|
+
- **The trade-off:** a write to a read-only account is reported by the runtime at the end, not at the write, and two
|
|
323
|
+
loads of one account are two views of the same bytes (a write through one is read through the other), where Rust's
|
|
324
|
+
`RefCell` would fail a second `borrow_mut()` while the first is held (a panic, or `AccountBorrowFailed` through
|
|
325
|
+
`try_borrow_mut_data`). The original's own address and type checks normally refuse such a pair before it is loaded
|
|
326
|
+
(SPL Stake Pool's PDA checks); make them in the same order, before the load.
|
|
327
|
+
- Only data writes are affected: with or without the flag every view reads the account's bytes in place, so a
|
|
328
|
+
`loadRaw` of an account also loaded with `loadRawMut` (or written with `storeBorsh`) reads what was written, BigVec
|
|
329
|
+
pushes included. The flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position
|
|
330
|
+
or another, is 2040 without it).
|
|
331
|
+
- `.lamports` on remaining accounts, `loadAccountMut`, CPI account metas and the checks of `Mut<…>` parameters stay as
|
|
332
|
+
they are, and programs without the flag compile exactly as before.
|
|
333
|
+
|
|
334
|
+
### Inout places that may be one account
|
|
335
|
+
|
|
336
|
+
An `Inout<T>` argument ([Inout parameters](language-statements.md#inout-parameters)) must not share storage with
|
|
337
|
+
another argument during the call. In every program, places in accounts that only the transaction can tell apart are
|
|
338
|
+
compared before the call and fail with 2040 when they overlap ([two parameters, one
|
|
339
|
+
account](language-accounts.md#two-parameters-one-account)). Under `NATIVE_ACCOUNT_WRITES` the native views are
|
|
340
|
+
compared the same way: places in two `loadRawMut` or `loadRawMutAt` views, `rawArrayMutAt` elements and `rbTreeMutAt`
|
|
341
|
+
nodes, which may be views of one account.
|
|
342
|
+
|
|
343
|
+
One pair is left to run time: a place in a `loadRawMut` view passed with the `RemainingAccount` it was loaded from.
|
|
344
|
+
Without `NATIVE_ACCOUNT_WRITES` a second `loadRawMut` of it in the helper fails with 2040; with the flag the helper can
|
|
345
|
+
load and write the same bytes, the flag's trade-off.
|
|
346
|
+
|
|
347
|
+
## Accounts closed, reassigned and resized by hand
|
|
348
|
+
|
|
349
|
+
On remaining accounts and `AccountInfo` parameters:
|
|
350
|
+
|
|
351
|
+
- `closeRaw(account, receiver)` is what Phoenix's Tombstone writes, in its order: `receiver.lamports +=
|
|
352
|
+
account.lamports` (checked), `account.lamports = 0`, `assign(&system_program::id())`, `realloc(0, false)`. Unlike
|
|
353
|
+
`close` the data is not zeroed first (a realloc to 0 drops it, and the runtime then accepts the new owner), so it
|
|
354
|
+
costs a few compute units whatever the account's size, and the account ends as the original's does (gone, its
|
|
355
|
+
lamports in the receiver; [`test/language/native-close.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/native-close.test.ts) compares it with Phoenix's own Tombstone).
|
|
356
|
+
- `assignOwner(account, owner)` is `AccountInfo::assign` (the runtime accepts it for a writable account of this program
|
|
357
|
+
whose data is empty or zeroed).
|
|
358
|
+
- `resizeAccount(account, size)` also takes a remaining account (`realloc(size, true)`: new bytes zeroed, at most
|
|
359
|
+
10 KiB past the size it had when the instruction started, 3016). That size is the one the entrypoint records in the
|
|
360
|
+
account's record, as solana_program 1.14's does, only in programs that resize a remaining account.
|
|
361
|
+
- A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node or a struct read
|
|
362
|
+
through one) is a compile error to use after it: its bounds were checked against the old length, so take the view
|
|
363
|
+
again.
|
|
364
|
+
- Without `NATIVE_ACCOUNT_WRITES` the accounts are checked as other writes the compiler cannot see are: writable (3006;
|
|
365
|
+
a parameter must be `Mut<AccountInfo>`), passed once (2040), the closed or reassigned account this program's (3007),
|
|
366
|
+
and not closed into itself (2040). With it nothing is checked and the runtime judges, as for the original
|
|
367
|
+
(`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`), and plain
|
|
368
|
+
`AccountInfo` parameters are enough.
|
|
369
|
+
|
|
370
|
+
## Errors and panics as the original reports them
|
|
371
|
+
|
|
372
|
+
```ts
|
|
373
|
+
import { type u64, ProgramError, instructionData, panic, panicsAt, require } from "typesol";
|
|
374
|
+
|
|
375
|
+
export enum PoolError {
|
|
376
|
+
/** @code 0 */
|
|
377
|
+
AlreadyInUse = "Pool account already in use",
|
|
378
|
+
Deserialization = "Failed to deserialize",
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** @fallback */
|
|
382
|
+
export function entry(): void {
|
|
383
|
+
const data = instructionData();
|
|
384
|
+
require(data.length > 0n, ProgramError.InvalidInstructionData);
|
|
385
|
+
require(data.readU8(0n) !== 9n, PoolError.AlreadyInUse);
|
|
386
|
+
if (data.readU8(0n) === 7n) panic("unsupported instruction", "program/src/lib.rs:12:5");
|
|
387
|
+
const a = data.readU64(1n);
|
|
388
|
+
const total: u64 = panicsAt("src/quantities.rs:233:1", a + 1n);
|
|
389
|
+
require(total > 0n, PoolError.Deserialization);
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
- An error enum may start at code 0 (`/** @code 0 */`, Rust's `ProgramError::Custom(0)`, returned as Solana's
|
|
394
|
+
CUSTOM_ZERO).
|
|
395
|
+
- `require(c, ProgramError.InvalidInstructionData)` fails with a built-in error.
|
|
396
|
+
- `panic(message, "program/src/lib.rs:12:5")` is a Rust panic (ProgramFailedToComplete, the runtime reporting that
|
|
397
|
+
location). `panic(null, "src/lib.rs:105:19")` logs no message, for an original whose panic handler writes none, so
|
|
398
|
+
only the runtime's "SBF program Panicked in src/lib.rs at 105:19" is left.
|
|
399
|
+
- `abort()` is Rust's abort (the allocator's out-of-memory error: `log("Error: memory allocation failed, out of
|
|
400
|
+
memory"); abort();`), the runtime's `abort` syscall, which logs "SBF program panicked" with no location.
|
|
401
|
+
- `const PANIC_ON_OVERFLOW = true` makes arithmetic overflow and division by zero panic as `checked_*().unwrap()` does
|
|
402
|
+
instead of failing with 5100 / 5101.
|
|
403
|
+
- **Panics as an older solana-program writes them.** `export const PANIC_STYLE = "solana-1.14"` (a program built with
|
|
404
|
+
solana-program 1.14 to 1.17, whose rustc formats a panic as it did before 1.73: Phoenix v1) makes `panic(message,
|
|
405
|
+
location)` log `panicked at '<message>', <location>` and then abort, so the runtime's last line is "SBF program
|
|
406
|
+
panicked" with no location, as that panic handler leaves it. `panic(null, …)` is refused there (the handler always
|
|
407
|
+
logs); without a location the TypeScript line and column are used. `PANIC_ON_OVERFLOW`'s panics abort too.
|
|
408
|
+
- **Overflow panics with Rust's message and location.** `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
|
|
409
|
+
checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
|
|
410
|
+
"attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with
|
|
411
|
+
a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow" and "attempt to shift left /
|
|
412
|
+
right with overflow" for a shift amount past the width), logged as `panic` logs (`PANIC_STYLE` above, else the
|
|
413
|
+
message and `sol_panic_` at the location), instead of failing with 5100 / 5101; with or without `PANIC_ON_OVERFLOW`,
|
|
414
|
+
which applies outside it.
|
|
415
|
+
- Rust reports the location of the expression the operator belongs to, so the wrapper goes around that expression:
|
|
416
|
+
only the operators written inside it take the location (not those of the helpers it calls), an inner `panicsAt`
|
|
417
|
+
gives its operators their own (`panicsAt(A, x + panicsAt(B, y * z))`), and as a statement it takes an assignment,
|
|
418
|
+
`panicsAt(LOC, total += fee);`.
|
|
419
|
+
- A Rust newtype's operator panics at its `impl` (Phoenix's `QuoteLots + QuoteLots` at the macro line in
|
|
420
|
+
quantities.rs, wherever the addition is written): give the port a helper, `function addQuoteLots(a: u64, b: u64):
|
|
421
|
+
u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`.
|
|
422
|
+
- The bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks
|
|
423
|
+
them differently, or with other messages).
|
|
424
|
+
- [`test/language/rust-panics.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/rust-panics.test.ts) checks the lines against the Phoenix binary's own panics.
|
|
425
|
+
|
|
426
|
+
## Log lines as the original writes them
|
|
427
|
+
|
|
428
|
+
- `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "` replace the
|
|
429
|
+
compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`).
|
|
430
|
+
- `null` logs no failure line at all, as a native program returns an error its own checks already explained (Phoenix):
|
|
431
|
+
the program's errors and codes its helpers return (`ERROR_LOG_PREFIX = null`), built-in ProgramErrors and
|
|
432
|
+
`programAt`'s check (`PROGRAM_ERROR_LOG_PREFIX = null`), each about 110 CU cheaper than a logged one (constraint
|
|
433
|
+
errors and the compiler's own checks still log).
|
|
434
|
+
- `logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record).
|
|
435
|
+
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
|
|
436
|
+
- `logComputeUnits()` is `sol_log_compute_units()`: the runtime writes "Program consumption: N units remaining" at that
|
|
437
|
+
point, as for the original (Phoenix's cancel and withdraw paths log it).
|
|
438
|
+
|
|
439
|
+
## Byte strings built by hand
|
|
440
|
+
|
|
441
|
+
```ts
|
|
442
|
+
import { type FixedVec, type Pubkey, type u64, type u8, fixedVec, setReturnData, u16 } from "typesol";
|
|
443
|
+
|
|
444
|
+
export interface Header {
|
|
445
|
+
kind: u8;
|
|
446
|
+
owner: Pubkey;
|
|
447
|
+
amount: u64;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function encode(owner: Pubkey, amount: u64, count: u64): void {
|
|
451
|
+
const data: FixedVec<u8, 128> = fixedVec([15n]);
|
|
452
|
+
data.pushLE<u16>(1n);
|
|
453
|
+
data.pushKey(owner);
|
|
454
|
+
data.pushBorsh<Header>({ kind: 2n, owner, amount });
|
|
455
|
+
data.pushLE(amount);
|
|
456
|
+
data.setLE(1n, u16(count));
|
|
457
|
+
setReturnData(data);
|
|
458
|
+
data.truncate(3n);
|
|
459
|
+
}
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
Instruction data for a self-CPI, a log record or return data is built in a `FixedVec<u8, N>` (a local list or one in
|
|
463
|
+
account data):
|
|
464
|
+
|
|
465
|
+
- `buf.pushLE(x)` appends an integer's little-endian bytes at its width (u8 … u128, i8 … i128; a literal needs one:
|
|
466
|
+
`buf.pushLE<u16>(1n)` or `buf.pushLE(u16(1n))`).
|
|
467
|
+
- `buf.pushKey(key)` appends a Pubkey's 32 bytes.
|
|
468
|
+
- `buf.pushBorsh(value)` appends a value's Borsh encoding with the codecs `invoke`, events and `storeBorsh` use: a
|
|
469
|
+
struct, or an object literal given its type (`buf.pushBorsh<Header>({ … })`); a data enum, its tag then the
|
|
470
|
+
variant's fields; a FixedArray; a list, its u32 count then the elements; integers, booleans, Pubkeys, strings and
|
|
471
|
+
Options. A data-enum literal of a fixed-size variant costs what the same bytes cost with `pushLE`: its fields
|
|
472
|
+
evaluated in order, then one room check and a store of each.
|
|
473
|
+
- `buf.setLE(offset, x)` (or `setLE<u16>(offset, x)`) overwrites bytes within the length, as Rust's
|
|
474
|
+
`data[a..b].copy_from_slice(…)`, and `buf.truncate(n)` keeps the first `n`.
|
|
475
|
+
- Past the room (or, for `setLE` and `truncate`, past the length) fails with 5104 and the length does not move.
|
|
476
|
+
|
|
477
|
+
Phoenix's event recorder is built this way, and the showcase checks it byte for byte against the Phoenix binary's
|
|
478
|
+
batches.
|
|
479
|
+
|
|
480
|
+
## Return data as the original sets it
|
|
481
|
+
|
|
482
|
+
`setReturnData(bytes)` is `set_return_data(&bytes)`, the bytes as they are, from the `@fallback` entry, a helper or a
|
|
483
|
+
void instruction (Phoenix's Borsh `Vec<FIFOOrderId>` of the orders that rested, built in a local `FixedVec<u8, N>`).
|
|
484
|
+
|
|
485
|
+
- `bytes` is a list of u8: a local FixedVec, a Vec or FixedVec in account data, or the instruction data or a slice of
|
|
486
|
+
it.
|
|
487
|
+
- The last call wins and an empty list clears it; a CPI made afterwards replaces it with the callee's (call it after the
|
|
488
|
+
last CPI, as Rust must).
|
|
489
|
+
- More than 1024 bytes fails as the Rust call does: the runtime refuses it ("Return data too large (1025 > 1024)").
|
|
490
|
+
- An instruction that returns a value cannot call it (a compile error: its return value is its return data); a helper
|
|
491
|
+
it calls may, and the instruction's return value, set last, replaces what the helper set.
|
|
492
|
+
|
|
493
|
+
**Next:** [Built-ins](language-builtins.md): every name `"typesol"` exports.
|