@typesol/cli 0.48.0 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +556 -1
- package/NOTICE +17 -1
- package/README.md +122 -43
- package/SECURITY.md +6 -0
- package/dist/compiler/analyze.d.ts +2 -0
- package/dist/compiler/analyze.js +7 -1
- package/dist/compiler/emit/base.d.ts +7 -4
- package/dist/compiler/emit/base.js +17 -5
- package/dist/compiler/emit/borsh.js +8 -8
- package/dist/compiler/emit/calls.d.ts +6 -0
- package/dist/compiler/emit/calls.js +110 -11
- package/dist/compiler/emit/cpi-core.js +3 -3
- package/dist/compiler/emit/cpi.js +2 -2
- package/dist/compiler/emit/expressions.d.ts +1 -0
- package/dist/compiler/emit/expressions.js +15 -1
- package/dist/compiler/emit/function.js +12 -8
- package/dist/compiler/emit/program.js +10 -4
- package/dist/compiler/emit/rbtree.js +1 -1
- package/dist/compiler/emit/shared.d.ts +12 -2
- package/dist/compiler/emit/shared.js +26 -6
- package/dist/compiler/emit/statements.d.ts +8 -1
- package/dist/compiler/emit/statements.js +53 -5
- package/dist/compiler/emit/storage.js +20 -13
- package/dist/compiler/emit/views.js +1 -1
- package/dist/compiler/hints.js +3 -0
- package/dist/compiler/index.d.ts +15 -1
- package/dist/compiler/index.js +50 -9
- package/dist/keys.d.ts +12 -1
- package/dist/keys.js +57 -7
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.js +90 -15
- package/docker/deps/0.49.0.lock.json +1206 -0
- package/docker/deps/0.50.0.lock.json +1206 -0
- package/docs/architecture.md +3 -3
- package/docs/audit.md +33 -16
- package/docs/case-study-escrow.md +7 -5
- package/docs/case-study-jito-mev.md +14 -14
- package/docs/case-study-marginfi.md +142 -129
- package/docs/case-study-multisig.md +18 -5
- package/docs/case-study-raydium-amm.md +2 -1
- package/docs/case-study-raydium-clmm.md +44 -28
- package/docs/case-study-raydium-cp-swap.md +18 -18
- package/docs/case-study-spl-stake-pool.md +4 -3
- package/docs/cli.md +4 -3
- package/docs/language-accounts.md +21 -16
- package/docs/language-basics.md +4 -1
- package/docs/language-builtins.md +6 -2
- package/docs/language-cpi.md +34 -0
- package/docs/language-errors-events.md +1 -1
- package/docs/language-native.md +73 -7
- package/docs/language-statements.md +5 -3
- package/docs/language-types.md +13 -3
- package/docs/language.md +2 -2
- package/docs/mainnet.md +1 -1
- package/docs/runtime.md +25 -1
- package/docs/security-model.md +12 -4
- package/docs/stability.md +10 -4
- package/docs/testing.md +22 -6
- package/docs/troubleshooting.md +1 -1
- package/lib/typesol.d.ts +43 -3
- package/llms-full.txt +190 -51
- package/llms.txt +2 -1
- package/package.json +3 -3
- package/releases/0.48.0.json +847 -0
- package/releases/0.49.0.json +857 -0
- package/runtime/typesol_builtins.c +47 -2
- package/runtime/typesol_rt.h +131 -4
|
@@ -107,9 +107,15 @@ and the port into another. Both use the same program id and the same clock, and
|
|
|
107
107
|
from earlier swaps, a reward stream, a dynamic fee, limit orders on a tick, the pool status bits.
|
|
108
108
|
|
|
109
109
|
**Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
|
|
110
|
-
code)
|
|
110
|
+
code); the same lamports, owner and data for the fee payer and every account an instruction names (programs left out:
|
|
111
|
+
they are different binaries); the same inner instructions (each CPI's program, accounts, data and stack height) apart
|
|
112
|
+
from the one pinned below; the same return data; and the same log lines, the events (`Program data:`) byte for byte,
|
|
113
|
+
apart from the runtime's compute-unit lines, Anchor's `Instruction: <Name>` line (the port does not write it) and, on a
|
|
114
|
+
failure, the error message the program logs itself (Anchor's text against TypeSOL's; the code is compared). Where the
|
|
115
|
+
original panics, the test requires that it fails with `ProgramFailedToComplete` and the port with a numbered error,
|
|
116
|
+
and compares the accounts it names (see *Where they differ*).
|
|
111
117
|
|
|
112
|
-
There are
|
|
118
|
+
There are 308 transactions:
|
|
113
119
|
|
|
114
120
|
- **Configs and pools.**
|
|
115
121
|
- `create_pool` with SPL Token and Token-2022 transfer-fee mints, the mainnet config and a pre-funded vault.
|
|
@@ -165,27 +171,27 @@ Compute units per transaction, mainnet original against the port, from one run o
|
|
|
165
171
|
|
|
166
172
|
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
167
173
|
| --- | ---: | ---: | ---: |
|
|
168
|
-
| `create_pool` |
|
|
169
|
-
| `create_customizable_pool_v2` | 51,673 | 23,
|
|
170
|
-
| `open_position_with_token22_nft`, in range |
|
|
171
|
-
| `open_position` (Metaplex NFT) |
|
|
172
|
-
| `increase_liquidity_v2` | 39,759 |
|
|
173
|
-
| `decrease_liquidity_v2` | 40,615 |
|
|
174
|
-
| `decrease_liquidity_v2`, with a reward paid | 58,
|
|
175
|
-
| `close_position`, Metaplex NFT | 11,032 | 3,
|
|
176
|
-
| `close_position`, Token-2022 NFT (its mint closed too) |
|
|
177
|
-
| `swap_v2` | 49,023 |
|
|
178
|
-
| `swap_v2`, across tick arrays | 55,837 |
|
|
179
|
-
| `swap_v2`, dynamic fee | 58,
|
|
180
|
-
| `swap_v2`, through limit orders | 74,
|
|
181
|
-
| `swap_v2`, the mainnet USDC/CC pool | 52,677 |
|
|
182
|
-
| `swap` | 51,009 |
|
|
183
|
-
| `swap_router_base_in`, two hops | 80,365 |
|
|
184
|
-
| `swap_router_base_in`, four hops through two pools twice | 159,246 |
|
|
185
|
-
| `open_limit_order` |
|
|
186
|
-
| `settle_limit_order` | 15,682 |
|
|
187
|
-
| `initialize_reward` |
|
|
188
|
-
| `collect_protocol_fee` | 13,626 | 2,
|
|
174
|
+
| `create_pool` | 54,318 | 23,601 | −57% |
|
|
175
|
+
| `create_customizable_pool_v2` | 51,673 | 23,153 | −55% |
|
|
176
|
+
| `open_position_with_token22_nft`, in range | 108,375 | 60,788 | −44% |
|
|
177
|
+
| `open_position` (Metaplex NFT) | 127,451 | 79,852 | −37% |
|
|
178
|
+
| `increase_liquidity_v2` | 39,759 | 14,417 | −64% |
|
|
179
|
+
| `decrease_liquidity_v2` | 40,615 | 15,253 | −62% |
|
|
180
|
+
| `decrease_liquidity_v2`, with a reward paid | 58,766 | 18,599 | −68% |
|
|
181
|
+
| `close_position`, Metaplex NFT | 11,032 | 3,237 | −71% |
|
|
182
|
+
| `close_position`, Token-2022 NFT (its mint closed too) | 17,895 | 9,279 | −48% |
|
|
183
|
+
| `swap_v2` | 49,023 | 19,380 | −60% |
|
|
184
|
+
| `swap_v2`, across tick arrays | 55,837 | 22,332 | −60% |
|
|
185
|
+
| `swap_v2`, dynamic fee | 58,955 | 24,577 | −58% |
|
|
186
|
+
| `swap_v2`, through limit orders | 74,448 | 31,195 | −58% |
|
|
187
|
+
| `swap_v2`, the mainnet USDC/CC pool | 52,677 | 20,778 | −61% |
|
|
188
|
+
| `swap` | 51,009 | 19,000 | −63% |
|
|
189
|
+
| `swap_router_base_in`, two hops | 80,365 | 33,838 | −58% |
|
|
190
|
+
| `swap_router_base_in`, four hops through two pools twice | 159,246 | 75,788 | −52% |
|
|
191
|
+
| `open_limit_order` | 32,304 | 9,435 | −71% |
|
|
192
|
+
| `settle_limit_order` | 15,682 | 4,813 | −69% |
|
|
193
|
+
| `initialize_reward` | 23,105 | 8,916 | −61% |
|
|
194
|
+
| `collect_protocol_fee` | 13,626 | 2,359 | −83% |
|
|
189
195
|
| `update_amm_config` | 3,028 | 491 | −84% |
|
|
190
196
|
|
|
191
197
|
Opening a position is mostly the token programs', the System Program's and (for a Metaplex NFT) Token Metadata's
|
|
@@ -193,14 +199,16 @@ work: the NFT mint, its metadata, the associated token account and the transfers
|
|
|
193
199
|
Pool and position creation also vary from run to run with the PDA bump searches of the random keys the test uses, in
|
|
194
200
|
both programs alike. Refusals cost far less; a swap of nothing costs 16,665 against 1,650.
|
|
195
201
|
|
|
196
|
-
On size, the port's binary is
|
|
202
|
+
On size, the port's binary is 546,080 bytes and the deployed original 1,700,160 bytes, for the same 37 instructions.
|
|
197
203
|
|
|
198
204
|
## Where they differ
|
|
199
205
|
|
|
200
206
|
- **Panics.** Where the original panics (an index out of range, an overflow under `overflow-checks`), it fails with
|
|
201
207
|
`ProgramFailedToComplete`; the port fails with a numbered error. Examples: a position past the pool's own bitmap
|
|
202
208
|
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).
|
|
209
|
+
(`copy_from_slice` of the wrong length). There the test requires the original's `ProgramFailedToComplete` and a
|
|
210
|
+
numbered error from the port, and compares the accounts the case names; it does not compare the rest of the
|
|
211
|
+
accounts, the inner instructions or the logs.
|
|
204
212
|
- **Check order on double faults.** Anchor creates `init` accounts (a position, an order) before it checks the other
|
|
205
213
|
accounts' constraints. TypeSOL does the same with the creates a body starts with (since the Marginfi port, whose
|
|
206
214
|
fuzzer found a case), so a transaction breaking both gets Anchor's code there. A body that checks something before
|
|
@@ -219,8 +227,16 @@ On size, the port's binary is 552,656 bytes and the deployed original 1,700,160
|
|
|
219
227
|
seed. The port's lists the `token_program` account (fixed to that address) in `open_position`, and nothing in
|
|
220
228
|
`open_position_v2`.
|
|
221
229
|
- `CollectPersonalFeeEvent`, which no instruction emits, is not in the port's IDL.
|
|
222
|
-
- **Logs.** The original
|
|
223
|
-
`
|
|
224
|
-
|
|
230
|
+
- **Logs.** The deployed original writes none of the `msg!` lines its source puts behind the `enable-log` feature
|
|
231
|
+
(`exact_swap_internal, …`, `amount_0:…, transfer_fee_0:…`, the dynamic fee's `state.tick:…`, `current block
|
|
232
|
+
timestamp:…`): its binary has none of those strings, and the port does not write them either. The ungated ones
|
|
233
|
+
(`collect reward index: …`, the close_position reasons) are in both; no compared transaction reaches them. Anchor's
|
|
234
|
+
`Instruction: <Name>` line is not written by the port. Error messages are TypeSOL's; codes and events are the
|
|
235
|
+
original's.
|
|
236
|
+
- **The Associated Token program's Create.** Where a position NFT's token account is created (`open_position*`), the
|
|
237
|
+
original calls the Associated Token program with data `[0]` (Create's Borsh tag); the port, through TypeSOL's
|
|
238
|
+
`Ata<Init<…>>`, with empty data, that program's older form of the same instruction. The accounts and the result are
|
|
239
|
+
the same. The test maps exactly that case (a CPI with Create's six accounts and no data) and compares every other
|
|
240
|
+
inner instruction as it is.
|
|
225
241
|
- **Clients and big-endian seeds.** The IDL records tick array seeds as Anchor does, without the byte order, so a client
|
|
226
242
|
that derives them from the IDL alone gets them wrong (with either program). Pass tick arrays explicitly.
|
|
@@ -135,30 +135,30 @@ Compute units per transaction, mainnet original against the port, from that test
|
|
|
135
135
|
|
|
136
136
|
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
137
137
|
| --- | ---: | ---: | ---: |
|
|
138
|
-
| `initialize` |
|
|
139
|
-
| `initialize`, Token-2022 transfer fees |
|
|
140
|
-
| `initialize_v2`, creator fee on |
|
|
141
|
-
| `initialize_with_permission` |
|
|
142
|
-
| `swap_base_input` | 24,
|
|
143
|
-
| `swap_base_output` | 24,
|
|
138
|
+
| `initialize` | 85,059 | 39,091 | −54% |
|
|
139
|
+
| `initialize`, Token-2022 transfer fees | 100,547 | 55,660 | −45% |
|
|
140
|
+
| `initialize_v2`, creator fee on | 90,786 | 41,785 | −54% |
|
|
141
|
+
| `initialize_with_permission` | 93,721 | 41,622 | −56% |
|
|
142
|
+
| `swap_base_input` | 24,176 | 5,591 | −77% |
|
|
143
|
+
| `swap_base_output` | 24,605 | 5,846 | −76% |
|
|
144
144
|
| `deposit` | 25,007 | 6,194 | −75% |
|
|
145
|
-
| `withdraw` | 25,214 | 6,
|
|
146
|
-
| `collect_protocol_fee` | 20,205 | 4,
|
|
147
|
-
| `collect_creator_fee`, creating the creator's two token accounts |
|
|
148
|
-
| `collect_creator_fee_permissionless` |
|
|
149
|
-
| `create_permission_pda` |
|
|
150
|
-
| `create_creator_fee_share` |
|
|
151
|
-
| `create_support_mint_associated` |
|
|
152
|
-
| `close_creator_fee_share` |
|
|
145
|
+
| `withdraw` | 25,214 | 6,228 | −75% |
|
|
146
|
+
| `collect_protocol_fee` | 20,205 | 4,200 | −79% |
|
|
147
|
+
| `collect_creator_fee`, creating the creator's two token accounts | 70,644 | 36,531 | −48% |
|
|
148
|
+
| `collect_creator_fee_permissionless` | 34,165 | 7,249 | −79% |
|
|
149
|
+
| `create_permission_pda` | 9,025 | 1,965 | −78% |
|
|
150
|
+
| `create_creator_fee_share` | 12,921 | 3,093 | −76% |
|
|
151
|
+
| `create_support_mint_associated` | 9,337 | 2,338 | −75% |
|
|
152
|
+
| `close_creator_fee_share` | 9,669 | 1,718 | −82% |
|
|
153
153
|
| `collect_excess_lamports`, wrapped SOL | 10,798 | 3,764 | −65% |
|
|
154
|
-
| `swap_base_input`, Token-2022 transfer fees | 31,
|
|
155
|
-
| `swap_base_output`, Token-2022 transfer fees | 32,
|
|
156
|
-
| `deposit`, Token-2022 transfer fees | 33,
|
|
154
|
+
| `swap_base_input`, Token-2022 transfer fees | 31,354 | 11,668 | −63% |
|
|
155
|
+
| `swap_base_output`, Token-2022 transfer fees | 32,531 | 13,140 | −60% |
|
|
156
|
+
| `deposit`, Token-2022 transfer fees | 33,209 | 13,670 | −59% |
|
|
157
157
|
|
|
158
158
|
The Token-2022 rows include the token program's own work, which is the same in both. Refusals cost far less. For
|
|
159
159
|
example, a swap through the wrong config costs 17,193 against 1,656.
|
|
160
160
|
|
|
161
|
-
On size, the port's binary is
|
|
161
|
+
On size, the port's binary is 216,960 bytes and the deployed original is 749,848 bytes, for the same 21 instructions.
|
|
162
162
|
|
|
163
163
|
Pool creation is mostly the token programs' and the System Program's own work (account creation, initialization,
|
|
164
164
|
transfers), which costs the same in both. The difference is the program's part. Its cost also varies from run to run
|
|
@@ -58,9 +58,10 @@ to the same C as before):
|
|
|
58
58
|
The mainnet binary and the port run in two LiteSVMs under the same program id, with the same clock and the same
|
|
59
59
|
StakeHistory written into both by one `StakeCluster`. Every transaction must give the same outcome, the same log
|
|
60
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
|
|
61
|
+
bytes in every account it names. There are 2,107 such transactions in five files (the random walk below comes on
|
|
62
|
+
top):
|
|
62
63
|
|
|
63
|
-
- **The instructions** (`spl-stake-pool.test.ts
|
|
64
|
+
- **The instructions** (`spl-stake-pool.test.ts` 505, `-stake` 274, `-rebalance` 360, `-metadata` 267; 1,406): every instruction's
|
|
64
65
|
success paths and every refusal that can be built, account by account (wrong signers, PDAs, owners, mints and
|
|
65
66
|
Token-2022 extensions, sysvars, short account lists), fee limits, slippage, preferred validators, funding
|
|
66
67
|
authorities, read-only and repeated accounts (the original's RefCell panics included), pools of 50 to 60 validators,
|
|
@@ -71,7 +72,7 @@ bytes in every account it names. There are 2,107 such transactions in six files:
|
|
|
71
72
|
- **A random walk over epochs** (`spl-stake-pool-fuzz.test.ts`): validators added and removed, users depositing and
|
|
72
73
|
withdrawing SOL and stake, rebalancing, updates in random chunks, fee and authority changes, rewards, slow warmup,
|
|
73
74
|
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
|
+
3,700 transactions) found no difference. Each run is 1,000 steps by default, with a new seed each time, and requires every main kind of
|
|
75
76
|
instruction (SOL and stake deposits and withdrawals, increases, decreases, both updates, adding a validator) to
|
|
76
77
|
succeed at least once.
|
|
77
78
|
|
package/docs/cli.md
CHANGED
|
@@ -7,9 +7,9 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
|
|
|
7
7
|
| Command | What it does |
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow] [--no-agent-files]` | Create a project ([below](#typesol-init)). |
|
|
10
|
-
| `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name. |
|
|
10
|
+
| `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name, and to write through a symbolic link inside the project (a linked `programs/` or `tests/`, or a link where a new file goes). |
|
|
11
11
|
| `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools (and a `toolchain` row: the tested ones, or untested with both versions), the Solana CLI, Docker (optional: only `--docker` builds need it; it says when they run emulated), its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. The last line says what is ready (building and testing, or also deploying) and what the warnings concern. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
|
|
12
|
-
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. `--docker` builds in the pinned container instead ([below](#build---docker-and-verify---docker)). |
|
|
12
|
+
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). Each source's sha256 is that of the bytes the compiler read, and the build fails without a manifest when a source or the runtime changes while it runs (an editor saving a file mid-build), so a manifest never pairs a binary with sources that did not make it. With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. First builds may run at once (several programs, or several processes): the keypair is created exclusively (a process that loses the race uses the winner's key) and `typesol.json` is updated one process at a time and replaced whole, so each address is kept. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. `--docker` builds in the pinned container instead ([below](#build---docker-and-verify---docker)). |
|
|
13
13
|
| `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--docker …] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
|
|
14
14
|
| `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`, always (a missing file or unreadable `--files` input is a diagnostic too, exit 1 or 2); `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
|
|
15
15
|
| `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
|
|
@@ -47,7 +47,8 @@ process on stderr. `TYPESOL_TOOLCHAIN=strict` makes it an error everywhere, `war
|
|
|
47
47
|
`<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the
|
|
48
48
|
program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above
|
|
49
49
|
rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). `init` refuses to
|
|
50
|
-
overwrite files
|
|
50
|
+
overwrite files, and to write through a symbolic link inside `<dir>` (a linked `.cursor/`, say, whose files would
|
|
51
|
+
land wherever it points; `<dir>` itself may be a link). It warns, with the install commands, when the platform-tools that building needs are missing, and
|
|
51
52
|
says whether the Agave CLI is missing or only its platform-tools (on Linux arm64, where there is no Agave CLI, the
|
|
52
53
|
commands that set up the platform-tools' `linux-aarch64` package).
|
|
53
54
|
|
|
@@ -188,8 +188,8 @@ export interface Log {
|
|
|
188
188
|
entries: u64;
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
-
export function grow(
|
|
192
|
-
realloc(log, size,
|
|
191
|
+
export function grow(owner: Mut<Signer>, log: HasOne<Mut<Log>, "owner">, systemProgram: SystemProgram, size: u64): void {
|
|
192
|
+
realloc(log, size, owner);
|
|
193
193
|
}
|
|
194
194
|
|
|
195
195
|
export function remove(owner: Mut<Signer>, log: HasOne<Mut<Log>, "owner">): void {
|
|
@@ -197,19 +197,21 @@ export function remove(owner: Mut<Signer>, log: HasOne<Mut<Log>, "owner">): void
|
|
|
197
197
|
}
|
|
198
198
|
```
|
|
199
199
|
|
|
200
|
-
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
200
|
+
- `close(account, destination)` closes a program account: its lamports go to `destination` (another writable account)
|
|
201
|
+
and its data is zeroed (by the memset syscall when the account's type takes 64 bytes or more, by stores below). The
|
|
202
|
+
account is not used after it in the function, except its `key` (compile errors, or 2040 at run time in a helper
|
|
203
|
+
given one account twice). `CloseTo<A, "dest">` does the same when the instruction succeeds
|
|
204
|
+
([constraints](#constraints)).
|
|
205
|
+
- Who may call them: `HasOne` above lets only the log's owner close it (the lamports of a closed account are value)
|
|
206
|
+
or resize it. Without that check anyone could pay to grow, or shrink, another user's account.
|
|
207
207
|
- `realloc(account, newSize, payer)` on a `Mut<Struct>`: growing charges the payer the extra rent (at most 10 KiB per
|
|
208
|
-
instruction, 3016); shrinking keeps the lamports in the account; never below the struct.
|
|
209
|
-
|
|
208
|
+
instruction, 3016); shrinking keeps the lamports in the account; never below the struct (3016). For a `@layout borsh`
|
|
209
|
+
struct that is its discriminator and smallest Borsh form (an empty `FixedString<64>` takes 4 bytes, not 68), the size
|
|
210
|
+
its load accepts; the value written back when the instruction returns must still fit (3004). Refused on a struct
|
|
211
|
+
with a growable `Vec` (its push / pop / clear size the account).
|
|
210
212
|
- `resizeAccount(account, newSize)` on a `Mut<AccountInfo>` of this program is Rust's `AccountInfo::resize`: the
|
|
211
|
-
length only, new bytes zeroed
|
|
212
|
-
(3016).
|
|
213
|
+
length only, new bytes zeroed (64 or more by the memset syscall, as `realloc` zeroes them too), no rent moved (fund
|
|
214
|
+
it first: `rentExempt(newSize)`), at most 10 KiB of growth (3016).
|
|
213
215
|
- An account grows at most 10 KiB per instruction, counted from its length when the instruction started (Solana's
|
|
214
216
|
limit): realloc again in the next instruction.
|
|
215
217
|
- `account.lamports` can be read on any account and written on a `Mut` one.
|
|
@@ -272,7 +274,8 @@ the body, in Anchor's order, and recorded in the IDL (`relations`, `pda`, `addre
|
|
|
272
274
|
among its types, not its accounts (an error named on such an `Owner` is not used: the load fails with 3007). Such a
|
|
273
275
|
struct may carry a shorter discriminator, `/** @discriminator 0x01 */` (1 to 8 bytes, as Anchor's
|
|
274
276
|
`discriminator = &[1]`; Solend's reserve), its fields then starting right after it; this program's own accounts
|
|
275
|
-
keep 8.
|
|
277
|
+
keep 8. A `@layout borsh` struct's Borsh bytes start there too, and the account must hold the discriminator and the
|
|
278
|
+
struct's smallest Borsh form (3003).
|
|
276
279
|
- `Address<InstructionsSysvar, "Sysvar1nstructions1111111111111111111111111">` checks the address as Anchor's
|
|
277
280
|
`address = sysvar::instructions::ID` on an `UncheckedAccount` does (2012, with the constraints).
|
|
278
281
|
|
|
@@ -305,7 +308,9 @@ are compared too ([native programs](language-native.md#inout-places-that-may-be-
|
|
|
305
308
|
|
|
306
309
|
At most 32 accounts per instruction; more is refused with 5113. `export const MAX_ACCOUNTS = 128n` (up to 255; Anchor
|
|
307
310
|
takes what the runtime allows) raises it for programs that take many remaining accounts. The CPI scratch lists are
|
|
308
|
-
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before.
|
|
311
|
+
then kept on the heap instead of the stack; programs that do not declare it compile exactly as before. 255 is also
|
|
312
|
+
the runtime's limit: an instruction naming more accounts (repeats count) fails with MaxAccountsExceeded before any
|
|
313
|
+
program runs.
|
|
309
314
|
|
|
310
315
|
## Optional accounts
|
|
311
316
|
|
|
@@ -398,7 +403,7 @@ export function count(tally: Mut<Tally>): void {
|
|
|
398
403
|
`remainingAccounts()` gives the accounts passed after the declared ones, in order.
|
|
399
404
|
|
|
400
405
|
- `.length`, `.get(i)` (5104 past the end) → `key`, `owner`, `lamports` (writes check writability, 3006), `isSigner`,
|
|
401
|
-
`isWritable`, the data length and data.
|
|
406
|
+
`isWritable`, `executable`, the data length and data.
|
|
402
407
|
- `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)` give checked struct views (owner, discriminator and size, as
|
|
403
408
|
`Account<T>` / `Mut<T>`), also of an `AccountInfo` parameter (Anchor's `AccountLoader::try_from` on an
|
|
404
409
|
`UncheckedAccount`).
|
package/docs/language-basics.md
CHANGED
|
@@ -271,9 +271,12 @@ export function setup(config: Mut<Config>): void {
|
|
|
271
271
|
- Constants are inlined where they are used, and may be seeds; when a seed is a constant, the IDL records its value.
|
|
272
272
|
- A constant with an integer type is computed in that type, every step checked: `const X: u64 = 1n - 2n + 5n` is an
|
|
273
273
|
error (`1n - 2n is -1, which does not fit in u64`), and `const M: u8 = ~1n` is 254 (`~` within the width).
|
|
274
|
-
Division by zero, a negative exponent or a shift past the width are compile errors
|
|
274
|
+
Division by zero, a negative exponent or a shift past the width are compile errors, and so is a signed type's
|
|
275
|
+
minimum divided by or reduced modulo -1 (`const X: i8 = -128n % -1n`: the quotient does not fit, and at run time
|
|
276
|
+
that remainder fails with 5100 too), where JavaScript's bigint gives 0.
|
|
275
277
|
- An untyped integer constant is inlined as its value and takes the type of the place it is used in, as a literal
|
|
276
278
|
does: `const FEE = 30n` stores into a `u16` field, and `const FEE = 300n` into a `u8` one is `300 does not fit in u8`.
|
|
279
|
+
It is computed as a JavaScript bigint, without a width: `const R = -128n % -1n` is 0.
|
|
277
280
|
- Top-level `let` and `var` are refused: `top-level variables must be const literals`. A program has no global state
|
|
278
281
|
other than its accounts.
|
|
279
282
|
- A few names configure the compiler: `HEAP_SIZE_KIB` ([below](#memory-stack-and-heap)), `MAX_ACCOUNTS`
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<!-- Generated by scripts/language-builtins.ts from lib/typesol.d.ts; do not edit by hand. -->
|
|
4
4
|
|
|
5
|
-
Every name `"typesol"` exports (
|
|
5
|
+
Every name `"typesol"` exports (222 names, 235 declarations), grouped, with its declaration and the first sentence of its doc
|
|
6
6
|
comment in `lib/typesol.d.ts`. Each group links to the part of the [language guide](language.md) that explains it;
|
|
7
7
|
your editor shows the full doc comment on hover. Methods of account and program types (`systemProgram.transfer`,
|
|
8
8
|
`acct.create`, …) are described with their types in the guide.
|
|
@@ -140,7 +140,7 @@ Explained in [Accounts: Closing and resizing](language-accounts.md#closing-and-r
|
|
|
140
140
|
| --- | --- | --- |
|
|
141
141
|
| `close` | `function close(account: AccountMeta, destination: AccountMeta): void` | Close a program-owned account: move all lamports to `destination` and wipe it. |
|
|
142
142
|
| `realloc` | `function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void` | Resize an account of this program (Anchor `realloc`, struct accounts only): growing charges `payer` the extra rent (never the account's own lamports, which may be deposits); shrinking keeps every lamport in the account — move freed rent out yourself if your program allows it. |
|
|
143
|
-
| `resizeAccount` | `function resizeAccount(account: RemainingAccount \| Mut<AccountInfo>, newSize: u64): void` | Resize a `Mut<AccountInfo>` or a remaining account of this program to `newSize` bytes (Rust's `AccountInfo::resize` / `realloc(newSize, true)`): the data length only, the new bytes zeroed. |
|
|
143
|
+
| `resizeAccount` | `function resizeAccount(account: RemainingAccount \| Mut<AccountInfo>, newSize: u64): void` | Resize a `Mut<AccountInfo>` or a remaining account of this program to `newSize` bytes (Rust's `AccountInfo::resize` / `realloc(newSize, true)`): the data length only, the new bytes zeroed (64 or more by the memset syscall). |
|
|
144
144
|
|
|
145
145
|
## Accounts created by hand
|
|
146
146
|
|
|
@@ -220,6 +220,7 @@ Explained in [Calling other programs: invoke](language-cpi.md#invoke).
|
|
|
220
220
|
| `sighash` | `function sighash(name: string): Bytes` | The 8-byte Anchor instruction discriminator for `name` (sha256("global:<snake_case name>")[..8]). |
|
|
221
221
|
| `hex` | `function hex(literal: string): Bytes` | Bytes from a hex string literal, e.g. hex("0a0b"). |
|
|
222
222
|
| `returnData` | `function returnData<T>(program: AccountMeta): T` | Read the return data the last invoke() left behind, checking it came from `program` and has exactly the size of T: `const n = returnData<u64>(counterProgram)`. |
|
|
223
|
+
| `getReturnData` | `function getReturnData(): [program: Pubkey, data: InstructionBytes]` | The return data as the runtime holds it, of any length and from any program (Rust's `get_return_data()`), for a port that checks it itself: `const [program, data] = getReturnData()`. |
|
|
223
224
|
| `invokeInstruction` | `function invokeInstruction(programId: Pubkey, accounts: IndexedList<InstructionAccountMeta>, data: IndexedList<u8>, infos: RemainingAccounts \| RemainingSlice, signerSeeds?: Seed[] \| SignerSeeds \| (Seed[] \| SignerSeeds)[]): void` | A CPI decided at run time, e.g. one stored in account data (Rust's `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`). |
|
|
224
225
|
| `InstructionAccountMeta` | `interface InstructionAccountMeta` | One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. |
|
|
225
226
|
| `programAt` | `function programAt<P>(account: RemainingAccount \| AccountInfo): P` | A remaining account (or an AccountInfo parameter) as a typed program: `const stake = programAt<StakeProgram>(rest.get(12n))`, then `stake.split(…)`, `token.mintTo(…)`, `system.transfer(…)` as on a declared program parameter, and passed to helpers that take that program type. |
|
|
@@ -403,11 +404,14 @@ Explained in [Porting a native program (advanced)](language-native.md).
|
|
|
403
404
|
| `RbEntry` | `interface RbEntry<K, V>` | A node of a RedBlackTree: its key (read-only), its value (in place) and its index in the tree's node array (1-based). |
|
|
404
405
|
| `closeRaw` | `function closeRaw(account: RemainingAccount \| Mut<AccountInfo>, receiver: RemainingAccount \| Mut<AccountInfo>): void` | Close an account of this program as a native program does it by hand (Phoenix's Tombstone), in this order: `receiver.lamports += account.lamports`, `account.lamports = 0`, the owner set to the System Program, the data length set to 0 (`realloc(0, false)`: the bytes are not zeroed, the runtime drops them with the length). |
|
|
405
406
|
| `assignOwner` | `function assignOwner(account: RemainingAccount \| Mut<AccountInfo>, owner: Pubkey): void` | Set an account's owner in place (Rust's `AccountInfo::assign`). |
|
|
407
|
+
| `zeroData` | `function zeroData(account: RemainingAccount \| Mut<AccountInfo>, offset: u64, length: u64): void` | Zero `length` bytes of an account's data from `offset`, as a native program's `for b in data[offset..offset + length].iter_mut() { *b = 0; }` (a memset): the memset syscall, about constant compute units whatever the length. |
|
|
408
|
+
| `copyData` | `function copyData(account: RemainingAccount \| Mut<AccountInfo>, from: u64, to: u64, length: u64): void` | Copy `length` bytes of an account's data from offset `from` to offset `to`, as a native program's `data.copy_within(from..from + length, to)` (or a struct copied out of the account and written back at another offset): the memmove syscall, about constant compute units whatever the length; the ranges may overlap. |
|
|
406
409
|
| `setReturnData` | `function setReturnData(bytes: IndexedList<u8>): void` | Set this instruction's return data to `bytes` as they are (Rust's `set_return_data(&bytes)`): a list of u8 such as a local `FixedVec<u8, N>`, a Vec or FixedVec in account data, or the instruction data or a slice of it. |
|
|
407
410
|
| `panic` | `function panic(message?: string \| null, location?: string): never` | Stop the program as a Rust `panic!` / `unwrap()` on `None` / `unreachable!()` does: the message is logged and the instruction fails with ProgramFailedToComplete (no error code). |
|
|
408
411
|
| `panicsAt` | `function panicsAt<T>(location: string, value: T): T` | `value`, with its checked arithmetic panicking as Rust's overflow checks do at `location` ("file:line:column", where the original's expression is): `panicsAt("src/quantities.rs:233:1", a + b)` logs "attempt to add with overflow" there (also "attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow", "attempt to shift left / right with overflow" for a shift amount past the width), as `panic` logs (see `PANIC_STYLE`), instead of failing with 5100 / 5101. |
|
|
409
412
|
| `abort` | `function abort(): never` | Stop the program as Rust's `abort` does on SBF (the allocator's out-of-memory error, `std::process::abort`): the runtime's `abort` syscall, which fails the instruction with ProgramFailedToComplete and logs "SBF program panicked" (no location, nothing else). |
|
|
410
413
|
| `logBase64` | `function logBase64(prefix: string, value: object): void` | Log `prefix` followed by the base64 (standard, padded) of a struct value's bytes, as a native program's `msg!("ray_log: {}", base64(bincode(log)))` does. |
|
|
411
414
|
| `logComputeUnits` | `function logComputeUnits(): void` | Log the compute units left (Rust's `sol_log_compute_units()`): the runtime writes "Program consumption: <N> units remaining", as the original's line, at the same place. |
|
|
415
|
+
| `log64` | `function log64(a: u64, b: u64, c: u64, d: u64, e: u64): void` | Log five u64 values as Rust's `sol_log_64(a, b, c, d, e)` does: the runtime writes "Program log: 0x<a>, 0x<b>, 0x<c>, 0x<d>, 0x<e>" (lowercase hex, no padding). |
|
|
412
416
|
|
|
413
417
|
**Next:** [Glossary](glossary.md): the Solana and TypeSOL terms the guide uses.
|
package/docs/language-cpi.md
CHANGED
|
@@ -319,6 +319,40 @@ Pubkeys, unit enums and arrays is read as its bytes (booleans and enums checked)
|
|
|
319
319
|
Vecs is declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106. The
|
|
320
320
|
type argument is required.
|
|
321
321
|
|
|
322
|
+
Return data of any length, checked by the program itself (Rust's `get_return_data()`, as a native program reads a
|
|
323
|
+
reply of several records), is `getReturnData()`:
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
import { getReturnData, instructionData, invoke, log, remainingAccounts, require, u8 } from "typesol";
|
|
327
|
+
|
|
328
|
+
export enum MatchError {
|
|
329
|
+
/** @code 0 */
|
|
330
|
+
NoReply = "NoReply",
|
|
331
|
+
BadReply = "BadReply",
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** @fallback */
|
|
335
|
+
export function entry(): void {
|
|
336
|
+
const matcher = remainingAccounts().get(0n);
|
|
337
|
+
const data = instructionData();
|
|
338
|
+
const legs = data.readU64(0n);
|
|
339
|
+
invoke(matcher, [], [u8(1n), legs]);
|
|
340
|
+
const [from, reply] = getReturnData();
|
|
341
|
+
// Rust's None: no return data (the runtime keeps no empty return data); `from` is then all zeros.
|
|
342
|
+
require(reply.length > 0n, MatchError.NoReply);
|
|
343
|
+
require(from === matcher.key && reply.length === legs * 64n, MatchError.BadReply);
|
|
344
|
+
log(reply.readU64(8n));
|
|
345
|
+
}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
- `from` is the program that set the return data (a Pubkey); `reply` its bytes, up to the runtime's 1,024, with the
|
|
349
|
+
methods of instruction data (`length`, `get`, `readU8` … `readU128`, `readPubkey`, `slice`; 5104 past the end).
|
|
350
|
+
- Nothing is checked and nothing fails: the program, the length and the contents are the caller's to check, with its
|
|
351
|
+
own errors. It reads whatever the runtime holds: the last CPI's callee's return data, or what this instruction set
|
|
352
|
+
with `setReturnData` after it.
|
|
353
|
+
- Bound with `const [program, data] = …` where it is called (either name may be left out: `const [, data]`). The bytes
|
|
354
|
+
are copied into 1 KiB of the calling function's stack frame.
|
|
355
|
+
|
|
322
356
|
## invokeInstruction
|
|
323
357
|
|
|
324
358
|
A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
|
|
@@ -69,7 +69,7 @@ it); a zero code fails with 5100.
|
|
|
69
69
|
- `require(cond, "message")` errors come after the highest code.
|
|
70
70
|
|
|
71
71
|
When the program fails, the logs show the error and the source line, `Error 6000 NotOwner (vault.ts:21)`, and
|
|
72
|
-
TypeSOL's own failures say what failed, `TypeSOL: arithmetic overflow (vault.ts:
|
|
72
|
+
TypeSOL's own failures say what failed, `TypeSOL: arithmetic overflow (vault.ts:44)`. Native ports can change or drop
|
|
73
73
|
that line ([log lines](language-native.md#log-lines-as-the-original-writes-them)).
|
|
74
74
|
|
|
75
75
|
## log
|
package/docs/language-native.md
CHANGED
|
@@ -215,6 +215,16 @@ A native account whose parts start where its header says (Phoenix's market at by
|
|
|
215
215
|
after a helper that may close or resize one it is given: its bounds were checked against the old length, so it is a
|
|
216
216
|
compile error saying to take the view again.
|
|
217
217
|
|
|
218
|
+
### Struct copies between views that overlap
|
|
219
|
+
|
|
220
|
+
Two views of one account at run-time offsets (`loadRawAt`, `loadRawMutAt`, an account passed twice under
|
|
221
|
+
`NATIVE_ACCOUNT_WRITES`) can overlap, and `d.v = s.v` then copies between overlapping bytes. The destination ends with
|
|
222
|
+
the source's old bytes, in either direction and at any size, as Rust's `copy_within` or a struct copied out and
|
|
223
|
+
written back leaves it: below 80 bytes every byte is loaded before any is stored (a load and then a store per 8
|
|
224
|
+
bytes), from 80 bytes the memmove syscall copies them. A copy through a local (`const c: T = s.v; d.v = c;`) and
|
|
225
|
+
`copyData` give the same bytes
|
|
226
|
+
([`test/language/bulk-copies.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/bulk-copies.test.ts)).
|
|
227
|
+
|
|
218
228
|
## lib-sokoban's red-black tree
|
|
219
229
|
|
|
220
230
|
```ts
|
|
@@ -314,7 +324,7 @@ direct mapping), one that was only read (or written with the bytes it held) is f
|
|
|
314
324
|
`AccountInfo`s over one buffer.
|
|
315
325
|
|
|
316
326
|
- **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
|
|
327
|
+
and `storeBorsh` refuses an account passed more than once (2040, as a write to a remaining account's lamports does without the flag). So a
|
|
318
328
|
port fails where the original succeeds (a read-only validator list that is only read; the list passed again as a
|
|
319
329
|
stake account, which the original skips by its address checks).
|
|
320
330
|
- **With the flag**, `loadRawMut`, `storeBorsh` and the BigVec writes through a `loadRawMut` view skip both, and both
|
|
@@ -328,8 +338,14 @@ direct mapping), one that was only read (or written with the bytes it held) is f
|
|
|
328
338
|
`loadRaw` of an account also loaded with `loadRawMut` (or written with `storeBorsh`) reads what was written, BigVec
|
|
329
339
|
pushes included. The flag only lifts the up-front checks (a second `loadRawMut` of one account, at the same position
|
|
330
340
|
or another, is 2040 without it).
|
|
331
|
-
-
|
|
332
|
-
|
|
341
|
+
- A write to a remaining account's `.lamports` (`a.lamports = v`, `+=`, `-=`) is `**a.lamports.borrow_mut() = v`
|
|
342
|
+
under the flag: no writability check (3006) and no refusal of an account passed more than once (2040). An account
|
|
343
|
+
passed twice is one record, as Rust's two `AccountInfo`s share one `RefCell`, so a write through either position is
|
|
344
|
+
read through the other; the runtime refuses a read-only account's change, or lamports created or destroyed, when the
|
|
345
|
+
instruction ends (`ReadonlyLamportChange`, `UnbalancedInstruction`). Percolator's CloseSlab moves the slab's
|
|
346
|
+
lamports to the admin this way while the admin (or the slab) is also named in an unused position.
|
|
347
|
+
- `loadAccountMut`, CPI account metas and the checks of `Mut<…>` parameters stay as they are, and programs without the
|
|
348
|
+
flag compile exactly as before.
|
|
333
349
|
|
|
334
350
|
### Inout places that may be one account
|
|
335
351
|
|
|
@@ -355,9 +371,26 @@ On remaining accounts and `AccountInfo` parameters:
|
|
|
355
371
|
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
372
|
- `assignOwner(account, owner)` is `AccountInfo::assign` (the runtime accepts it for a writable account of this program
|
|
357
373
|
whose data is empty or zeroed).
|
|
358
|
-
- `
|
|
359
|
-
|
|
360
|
-
|
|
374
|
+
- `zeroData(account, offset, length)` zeroes that range of the data, as a native program's `for b in
|
|
375
|
+
data.iter_mut() { *b = 0; }`, which compiles to a memset: the memset syscall, about constant compute units whatever
|
|
376
|
+
the length (Percolator clears its 1.5 MB slab this way at InitMarket and CloseSlab). Past the end of the data fails
|
|
377
|
+
with 3003 and writes nothing; without `NATIVE_ACCOUNT_WRITES` the account must be writable (3006). It does not check
|
|
378
|
+
the account's owner: check that it is this program's first (the runtime would fail the instruction after it returns,
|
|
379
|
+
having changed another program's account). The length does not change, so views made before stay valid and read the
|
|
380
|
+
zeros.
|
|
381
|
+
- `copyData(account, from, to, length)` copies `length` bytes of the data from offset `from` to offset `to`, as a
|
|
382
|
+
native program's `data.copy_within(from..from + length, to)` or a struct copied out and written back at another
|
|
383
|
+
offset (a memcpy in Rust): the memmove syscall from 32 bytes, about constant compute units whatever the length (a
|
|
384
|
+
whole-struct assignment `a.p = b.p` between views uses it too, from 80 bytes: [overlapping
|
|
385
|
+
views](#struct-copies-between-views-that-overlap)). The ranges may overlap. A range past the end of the data fails
|
|
386
|
+
with 3003 and copies nothing; without `NATIVE_ACCOUNT_WRITES` the account must be writable (3006). Like `zeroData`
|
|
387
|
+
it does not check the owner, and views made before stay valid and read the copied bytes (Percolator v16's InitMarket
|
|
388
|
+
copies asset 0's 424-byte oracle profile into every slot of the market this way;
|
|
389
|
+
[`test/language/native-copy-data.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/native-copy-data.test.ts)).
|
|
390
|
+
- `resizeAccount(account, size)` also takes a remaining account (`realloc(size, true)`: new bytes zeroed, 64 or more
|
|
391
|
+
by the memset syscall as Rust's realloc zeroes them, fewer by stores; at most 10 KiB past the size it had when the
|
|
392
|
+
instruction started, 3016). That size is the one the entrypoint records in the account's record, as solana_program
|
|
393
|
+
1.14's does, only in programs that resize a remaining account.
|
|
361
394
|
- A view of the account made before either (`loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt`, a node or a struct read
|
|
362
395
|
through one) is a compile error to use after it: its bounds were checked against the old length, so take the view
|
|
363
396
|
again.
|
|
@@ -367,6 +400,7 @@ On remaining accounts and `AccountInfo` parameters:
|
|
|
367
400
|
(`ReadonlyLamportChange`, `ExternalAccountLamportSpend`, `UnbalancedInstruction`, `ModifiedProgramId`), and plain
|
|
368
401
|
`AccountInfo` parameters are enough.
|
|
369
402
|
|
|
403
|
+
|
|
370
404
|
## Errors and panics as the original reports them
|
|
371
405
|
|
|
372
406
|
```ts
|
|
@@ -405,6 +439,35 @@ export function entry(): void {
|
|
|
405
439
|
location)` log `panicked at '<message>', <location>` and then abort, so the runtime's last line is "SBF program
|
|
406
440
|
panicked" with no location, as that panic handler leaves it. `panic(null, …)` is refused there (the handler always
|
|
407
441
|
logs); without a location the TypeScript line and column are used. `PANIC_ON_OVERFLOW`'s panics abort too.
|
|
442
|
+
- **Panics as solana-program 1.18 writes them.** `export const PANIC_STYLE = "solana-1.18"` (a program built with
|
|
443
|
+
solana-program 1.18, whose rustc formats a panic as it has since 1.73: Percolator v12.20) makes `panic(message,
|
|
444
|
+
location)` log one line, `panicked at <location>:` and the message after a newline, and then abort ("SBF program
|
|
445
|
+
panicked"), as that panic handler does: `panicked at src/wide_math.rs:1554:30:\nmul_div_floor_u128: a*b overflow`.
|
|
446
|
+
As under "solana-1.14", a message is required and `PANIC_ON_OVERFLOW`'s panics abort.
|
|
447
|
+
- **Panics as pinocchio's entrypoint writes them.** `export const PANIC_STYLE = "pinocchio"` (a program built with
|
|
448
|
+
pinocchio's `entrypoint!`, whose `default_panic_handler!` hook runs under std: Percolator v16) makes `panic(message,
|
|
449
|
+
location)` log two lines, the location's file exactly as Rust records it and then `** PANICKED **`, and abort ("SBF
|
|
450
|
+
program panicked"):
|
|
451
|
+
|
|
452
|
+
```
|
|
453
|
+
Program log: src/v16.rs
|
|
454
|
+
Program log: ** PANICKED **
|
|
455
|
+
Program <id> failed: SBF program panicked
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
- The file is `Location::file()` verbatim: the path rustc was given, which cargo makes relative to the crate
|
|
459
|
+
(`src/v16.rs`, `src/account_info.rs` inside solana-program) and which is the toolchain's absolute path for a panic
|
|
460
|
+
inside the standard library that is not reported at its caller (Percolator v16's binary holds
|
|
461
|
+
`/home/runner/work/platform-tools/platform-tools/out/rust/library/alloc/src/raw_vec/mod.rs`). Give it as the
|
|
462
|
+
location, alone or with its line and column (`"src/v16.rs:812:9"`, logged as `src/v16.rs`), so the port's source
|
|
463
|
+
keeps the original's place. Index, `unwrap`, `RefCell::borrow_mut` and `Vec::with_capacity`'s capacity panics are
|
|
464
|
+
reported at their caller (`#[track_caller]`), so their file is the caller's.
|
|
465
|
+
- No message is logged (the hook ignores it): the message may be `null` or a note for the reader. Without a
|
|
466
|
+
location this source file's name is logged.
|
|
467
|
+
- `panicsAt(location, expression)` logs its location's file the same way. `PANIC_ON_OVERFLOW` is refused with this
|
|
468
|
+
style: its panics have no file; wrap the arithmetic in `panicsAt`.
|
|
469
|
+
- Every panic site calls one shared helper (the two log calls and the abort), so a port with many panic sites stays
|
|
470
|
+
small.
|
|
408
471
|
- **Overflow panics with Rust's message and location.** `panicsAt("src/quantities.rs:233:1", a + b)` is `a + b` whose
|
|
409
472
|
checked arithmetic panics as Rust's overflow checks do at that location ("attempt to add with overflow"; also
|
|
410
473
|
"attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with
|
|
@@ -420,7 +483,8 @@ export function entry(): void {
|
|
|
420
483
|
quantities.rs, wherever the addition is written): give the port a helper, `function addQuoteLots(a: u64, b: u64):
|
|
421
484
|
u64 { return panicsAt(QUOTE_LOTS_ADD, a + b); }`.
|
|
422
485
|
- The bits `<<` loses, `**`, `mulDiv` / `mulDivCeil`, casts and u256 arithmetic keep TypeSOL's failures (Rust checks
|
|
423
|
-
them differently, or with other messages)
|
|
486
|
+
them differently, or with other messages): `panicsAt(LOC, a ** 2n)` fails with 5100 when the square overflows,
|
|
487
|
+
while an operator in `**`'s operands (`(a + b) ** 2n`) still panics at the location.
|
|
424
488
|
- [`test/language/rust-panics.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/language/rust-panics.test.ts) checks the lines against the Phoenix binary's own panics.
|
|
425
489
|
|
|
426
490
|
## Log lines as the original writes them
|
|
@@ -435,6 +499,8 @@ export function entry(): void {
|
|
|
435
499
|
- `createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
|
|
436
500
|
- `logComputeUnits()` is `sol_log_compute_units()`: the runtime writes "Program consumption: N units remaining" at that
|
|
437
501
|
point, as for the original (Phoenix's cancel and withdraw paths log it).
|
|
502
|
+
- `log64(a, b, c, d, e)` is `sol_log_64(a, b, c, d, e)`: the runtime writes the five u64s as lowercase hex,
|
|
503
|
+
`Program log: 0x174778, 0x3e8, 0x0, 0x0, 0x0` (Percolator logs the slab length it wants and the one it got this way).
|
|
438
504
|
|
|
439
505
|
## Byte strings built by hand
|
|
440
506
|
|
|
@@ -115,7 +115,8 @@ export function edit(shape: Mut<Shape>): void {
|
|
|
115
115
|
refused.
|
|
116
116
|
- **Evaluation order**: operands and arguments are read left to right, as in JavaScript, even when a later one changes
|
|
117
117
|
account data (`v.length + v.pop()`) or a local (`x + bump()` with a closure `bump` doing `x += 1n`, or a list
|
|
118
|
-
callback writing it).
|
|
118
|
+
callback writing it). Built-ins too: `log64(a.count, bump(a), 0n, 0n, 0n)` logs the count before the bump, and
|
|
119
|
+
`require(a.count === n, codeOf(a))` tests the count before a helper computing the error code runs.
|
|
119
120
|
- **Ternaries** run only the chosen branch: `const fee = vip ? 0n : 30n`. Between accounts too:
|
|
120
121
|
`const source = ephemeral ? rest.get(5n) : reserve` picks a remaining account (`rest.get(i)`, a local or
|
|
121
122
|
`RemainingAccount` helper parameter bound to one) or an `AccountInfo` parameter, and the result goes wherever a
|
|
@@ -236,7 +237,7 @@ members`). A `switch` on a string is refused (`switch works on integers and enum
|
|
|
236
237
|
## Destructuring
|
|
237
238
|
|
|
238
239
|
```ts
|
|
239
|
-
import { type Account, type Mut, type Pubkey, type u64 } from "typesol";
|
|
240
|
+
import { type Account, type Mut, type Pubkey, type Signer, type u64, require } from "typesol";
|
|
240
241
|
|
|
241
242
|
export interface Point {
|
|
242
243
|
x: u64;
|
|
@@ -249,7 +250,8 @@ export interface Player {
|
|
|
249
250
|
score: u64;
|
|
250
251
|
}
|
|
251
252
|
|
|
252
|
-
export function read(player: Account<Player>, out: Mut<Player>): void {
|
|
253
|
+
export function read(signer: Signer, player: Account<Player>, out: Mut<Player>): void {
|
|
254
|
+
require(out.owner === signer.key, "only the owner of out can overwrite it");
|
|
253
255
|
const { owner, pos: p } = player;
|
|
254
256
|
let { score } = player;
|
|
255
257
|
score += p.x;
|