@typesol/cli 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +10 -9
  3. package/dist/cli.js +50 -5
  4. package/dist/compiler/analyze.js +187 -42
  5. package/dist/compiler/emit/alias.js +5 -1
  6. package/dist/compiler/emit/base.d.ts +5 -0
  7. package/dist/compiler/emit/base.js +24 -6
  8. package/dist/compiler/emit/calls.d.ts +5 -1
  9. package/dist/compiler/emit/calls.js +109 -15
  10. package/dist/compiler/emit/cpi-core.d.ts +8 -0
  11. package/dist/compiler/emit/cpi-core.js +17 -2
  12. package/dist/compiler/emit/cpi.js +10 -4
  13. package/dist/compiler/emit/create.d.ts +2 -0
  14. package/dist/compiler/emit/create.js +56 -13
  15. package/dist/compiler/emit/expressions.js +16 -6
  16. package/dist/compiler/emit/function.d.ts +3 -1
  17. package/dist/compiler/emit/function.js +21 -12
  18. package/dist/compiler/emit/statements.js +53 -3
  19. package/dist/compiler/emit/storage.js +8 -8
  20. package/dist/compiler/emit/token.js +43 -0
  21. package/dist/compiler/idl.js +47 -6
  22. package/dist/compiler/model.d.ts +19 -1
  23. package/dist/templates.js +13 -36
  24. package/dist/testing.d.ts +30 -0
  25. package/dist/testing.js +85 -3
  26. package/dist/workspace.d.ts +16 -1
  27. package/dist/workspace.js +49 -5
  28. package/docs/audit.md +1 -1
  29. package/docs/case-study-escrow.md +3 -3
  30. package/docs/case-study-multisig.md +3 -3
  31. package/docs/case-study-raydium-cp-swap.md +51 -21
  32. package/docs/cli.md +5 -3
  33. package/docs/errors.md +3 -1
  34. package/docs/language.md +17 -5
  35. package/docs/migrate-from-anchor.md +6 -0
  36. package/docs/test-your-program.md +12 -3
  37. package/docs/testing.md +1 -1
  38. package/lib/typesol.d.ts +51 -15
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -7
package/dist/workspace.js CHANGED
@@ -65,10 +65,14 @@ export function programForEntry(ws, file) {
65
65
  /**
66
66
  * The program's keypair (created on first use) checked against the address recorded in typesol.json, which is
67
67
  * recorded on first build. A mismatch means the keypair was lost or replaced: deploying would create a new program.
68
+ * Building and testing only need the address: without the keypair (a fresh clone, CI) they use the recorded one,
69
+ * and only deploying (`needKeypair`) refuses.
68
70
  */
69
- export function programAddress(ws, name) {
71
+ export function programAddress(ws, name, opts = {}) {
70
72
  const paths = programPaths(ws, name);
71
73
  const recorded = ws.programs[name].address;
74
+ if (recorded && !existsSync(paths.keypair) && !opts.needKeypair)
75
+ return { address: recorded, created: false, keyless: true };
72
76
  if (recorded && !existsSync(paths.keypair))
73
77
  throw new Error(`${name}: ${path.relative(ws.root, paths.keypair)} is missing, but ${CONFIG} records ${recorded}. Restore the keypair (it is the program's address); removing "address" from ${CONFIG} would give the program a new address.`);
74
78
  mkdirSync(path.dirname(paths.keypair), { recursive: true });
@@ -87,11 +91,11 @@ export function programAddress(ws, name) {
87
91
  export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {}) {
88
92
  return names.map((name) => {
89
93
  const paths = programPaths(ws, name);
90
- const { address, created } = programAddress(ws, name);
94
+ const { address, created, keyless } = programAddress(ws, name, { needKeypair: opts.needKeypair });
91
95
  const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile });
92
96
  // The TypeScript client (docs/client.md) is written with the build, from the same IDL.
93
97
  const clientPath = writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`)).path;
94
- return { paths, address, created, result, clientPath };
98
+ return { paths, address, created, keyless, result, clientPath };
95
99
  });
96
100
  }
97
101
  /** The `solana program deploy` arguments for one built program (deploying again upgrades it). */
@@ -132,7 +136,15 @@ export function scaffold(dir, name, template = "counter") {
132
136
  name,
133
137
  private: true,
134
138
  type: "module",
135
- scripts: { build: "typesol build", test: "vitest run", typecheck: "tsc -p tsconfig.json", deploy: "typesol deploy" },
139
+ scripts: {
140
+ build: "typesol build",
141
+ // The tests and the typecheck import the client the build writes: build first.
142
+ pretest: "typesol build --quiet",
143
+ test: "vitest run",
144
+ pretypecheck: "typesol build --quiet",
145
+ typecheck: "tsc -p tsconfig.json",
146
+ deploy: "typesol deploy",
147
+ },
136
148
  engines: { node: ">=22.12" },
137
149
  devDependencies: {
138
150
  // Published as @typesol/cli, installed under the name programs import ("typesol", "typesol/workspace").
@@ -149,7 +161,7 @@ export function scaffold(dir, name, template = "counter") {
149
161
  // VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
150
162
  ".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
151
163
  // target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
152
- ".gitignore": "node_modules/\n# target/deploy/*-keypair.json are the programs' addresses (and upgrade keys): never commit them, but BACK THEM UP.\n# A fresh clone cannot build or deploy a program whose address is recorded in typesol.json without its keypair.\ntarget/\n",
164
+ ".gitignore": "node_modules/\n# target/deploy/*-keypair.json are the programs' addresses (and upgrade keys): never commit them, but BACK THEM UP.\n# Without it, a fresh clone still builds and tests at the address recorded in typesol.json, but cannot deploy.\ntarget/\n",
153
165
  "tsconfig.json": JSON.stringify({
154
166
  compilerOptions: {
155
167
  target: "ES2022",
@@ -172,3 +184,35 @@ export function scaffold(dir, name, template = "counter") {
172
184
  }
173
185
  return Object.keys(files);
174
186
  }
187
+ /**
188
+ * Add a program to an existing project: programs/<name>.ts and tests/<name>.test.ts from a template, and its entry in
189
+ * typesol.json. Returns the files written and the template's extra devDependencies the package.json lacks.
190
+ */
191
+ export function addProgram(ws, name, template = "counter") {
192
+ if (!/^[a-z][a-z0-9_]*$/.test(name))
193
+ throw new Error(`program name "${name}" must be snake_case`);
194
+ if (ws.programs[name])
195
+ throw new Error(`${CONFIG} already has a program "${name}"`);
196
+ const t = TEMPLATES[template];
197
+ const files = { [`programs/${name}.ts`]: t.program, [`tests/${name}.test.ts`]: t.test(name) };
198
+ const existing = Object.keys(files).filter((f) => existsSync(path.join(ws.root, f)));
199
+ if (existing.length)
200
+ throw new Error(`refusing to overwrite: ${existing.join(", ")}`);
201
+ for (const [file, text] of Object.entries(files)) {
202
+ mkdirSync(path.dirname(path.join(ws.root, file)), { recursive: true });
203
+ writeFileSync(path.join(ws.root, file), text);
204
+ }
205
+ const raw = JSON.parse(readFileSync(ws.file, "utf8"));
206
+ raw.programs[name] = { path: `programs/${name}.ts` };
207
+ writeFileSync(ws.file, JSON.stringify(raw, null, 2) + "\n");
208
+ ws.programs[name] = { path: `programs/${name}.ts` };
209
+ const pkgFile = path.join(ws.root, "package.json");
210
+ const pkg = existsSync(pkgFile)
211
+ ? JSON.parse(readFileSync(pkgFile, "utf8"))
212
+ : {};
213
+ const have = { ...pkg.dependencies, ...pkg.devDependencies };
214
+ const missing = Object.entries(t.devDependencies ?? {})
215
+ .filter(([dep]) => !(dep in have))
216
+ .map(([dep, v]) => `${dep}@${v}`);
217
+ return { files: [...Object.keys(files), CONFIG], missing };
218
+ }
package/docs/audit.md CHANGED
@@ -67,7 +67,7 @@ Internal reviews, by the maintainers, in October 2026. Their findings and fixes
67
67
  sequences against state models with value conservation; account layout with two growable Vecs and aliasing through
68
68
  remaining accounts. Each run prints its seed (`FUZZ_SEED`), `pnpm fuzz` runs them wide.
69
69
  - **Ported programs**: all 46 programs of solana-developers/program-examples, run through their original tests' flows
70
- and failure paths ([test/ports/README.md](../test/ports/README.md)).
70
+ and failure paths ([test/ports/README.md](https://github.com/typesol/typesol/blob/main/test/ports/README.md)).
71
71
  - **Four-way comparison**: [typesol/benchmarks](https://github.com/typesol/benchmarks) runs 17 of those programs in
72
72
  TypeSOL, Anchor, native Rust and Pinocchio, requires the same outcome, and records how each refuses the hostile calls
73
73
  and with which error.
@@ -4,7 +4,7 @@ This page follows one complete Anchor program into TypeSOL: the token escrow fro
4
4
  [solana-developers/program-examples](https://github.com/solana-developers/program-examples/tree/de090195e4de698e150572c4f886c333323a64a5/tokens/escrow/anchor)
5
5
  (`tokens/escrow`, commit `de09019`). It shows the original and the port side by side, what changed, how the two were
6
6
  checked against each other, where they still differ, and what the port costs to run. The port is
7
- [`test/ports/tokens/escrow.ts`](../test/ports/tokens/escrow.ts); [Migrate from Anchor](migrate-from-anchor.md) is the
7
+ [`test/ports/tokens/escrow.ts`](https://github.com/typesol/typesol/blob/main/test/ports/tokens/escrow.ts); [Migrate from Anchor](migrate-from-anchor.md) is the
8
8
  general reference.
9
9
 
10
10
  ## The program
@@ -160,13 +160,13 @@ tokenProgram.closeAccount(vault, maker, offer, ["offer", maker.key, offer.id, of
160
160
  | `ErrorCode::CustomError` (unused upstream) | `enum ErrorCode`, the same code 6000 |
161
161
 
162
162
  Nothing in the program needed a construct TypeSOL lacks, and every account constraint has its TypeSOL form; the port
163
- is marked PORTED in [the ports table](../test/ports/README.md).
163
+ is marked PORTED in [the ports table](https://github.com/typesol/typesol/blob/main/test/ports/README.md).
164
164
 
165
165
  ## Same inputs, same results
166
166
 
167
167
  Two independent checks run the original and the port against each other.
168
168
 
169
- - **The port's own test** ([`test/porting/ports-tokens.test.ts`](../test/porting/ports-tokens.test.ts)) runs the upstream flow with SPL
169
+ - **The port's own test** ([`test/porting/ports-tokens.test.ts`](https://github.com/typesol/typesol/blob/main/test/porting/ports-tokens.test.ts)) runs the upstream flow with SPL
170
170
  Token mints and again with Token-2022 mints: make, take (creating the taker's and the maker's missing token accounts),
171
171
  make again, a refund attempt by someone other than the maker, and the refund. It checks balances, the decoded offer
172
172
  and that offer and vault are closed.
@@ -3,8 +3,8 @@
3
3
  This page ports a program that holds real authority on mainnet:
4
4
  [coral-xyz/multisig](https://github.com/coral-xyz/multisig) (`programs/multisig/src/lib.rs`, Anchor 0.25, Apache-2.0),
5
5
  deployed at `msigUdDBsR4zSUYqYEDrc1LcgtmuSDDM7KxpRUXNC6U`. The port is
6
- [`examples/multisig.ts`](../examples/multisig.ts). Instead of a twin built for the occasion, it is checked against the
7
- binary that runs on mainnet: [`test/examples/multisig.test.ts`](../test/examples/multisig.test.ts) runs both under the
6
+ [`examples/multisig.ts`](https://github.com/typesol/typesol/blob/main/examples/multisig.ts). Instead of a twin built for the occasion, it is checked against the
7
+ binary that runs on mainnet: [`test/examples/multisig.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/multisig.test.ts) runs both under the
8
8
  same program id and compares every outcome and every account byte. See
9
9
  [case-study-escrow.md](case-study-escrow.md) for a token program and [Migrate from Anchor](migrate-from-anchor.md) for
10
10
  the general reference.
@@ -99,7 +99,7 @@ existing clients and existing accounts work with the port unchanged.
99
99
  ## How it was checked
100
100
 
101
101
  `test/programs/coral_multisig.so` is the program dumped from mainnet on 2026-10-29 (sha256 in
102
- [`test/programs/SOURCES.md`](../test/programs/SOURCES.md)). The test loads it into one LiteSVM and the port into
102
+ [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)). The test loads it into one LiteSVM and the port into
103
103
  another, both at `msigUdDB…`, then sends each transaction to both. After each one it requires the same outcome (success,
104
104
  or the same error down to the code) and the same lamports, owner and data bytes for every account involved.
105
105
 
@@ -2,14 +2,15 @@
2
2
 
3
3
  This page ports the trading core of a production AMM: [Raydium CP-Swap](https://github.com/raydium-io/raydium-cp-swap)
4
4
  (`programs/cp-swap`, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
5
- `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`examples/raydium-cp-swap/`](../examples/raydium-cp-swap)
5
+ `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`examples/raydium-cp-swap/`](https://github.com/typesol/typesol/blob/main/examples/raydium-cp-swap)
6
6
  (`state.ts`, `curve.ts`, `raydium_cp_swap.ts`). As with [coral-xyz/multisig](case-study-multisig.md), it is checked
7
7
  against the binary that runs on mainnet, not a rebuild.
8
8
 
9
9
  ## What is ported
10
10
 
11
- The port covers 9 of the original's 24 instructions:
11
+ The port covers 10 of the original's 24 instructions:
12
12
 
13
+ - `initialize`, which creates a pool with its first liquidity;
13
14
  - the four trading instructions: `swap_base_input`, `swap_base_output`, `deposit` and `withdraw`;
14
15
  - `collect_protocol_fee` and `collect_fund_fee`;
15
16
  - the admin instructions `create_amm_config`, `update_amm_config` and `update_pool_status`.
@@ -24,9 +25,7 @@ It also keeps the original's names, argument order and error codes, and emits th
24
25
 
25
26
  These are not ported yet:
26
27
 
27
- - **`initialize` and `initialize_with_permission`.** They create a pool at either a PDA or a signer keypair, chosen at
28
- run time, and allocate a program account by hand: transfer, allocate and assign when the address was pre-funded.
29
- TypeSOL's `Init<T>` fixes the choice at compile time and reports an existing account with its own error.
28
+ - **`initialize_with_permission`.** It is `initialize` for a creator the admin authorized, with the creator fee on.
30
29
  - **The creator-fee instructions**: `collect_creator_fee`, `collect_creator_fee_permissionless`,
31
30
  `create_creator_fee_share` and `close_creator_fee_share`.
32
31
  - **The permission instructions**: `create_permission_pda` and `close_permission_pda`.
@@ -38,7 +37,19 @@ the creator fee on), so a pool the original created and configured is traded the
38
37
 
39
38
  ## What it needed
40
39
 
41
- Four Token-2022 reads, added to the compiler for this port (`test/integrations/t22ext.test.ts`):
40
+ Creating the pool by hand, as the original does, needed a few general features (`test/language/manual-init.test.ts`):
41
+
42
+ - `systemProgram.allocate` and `assign`, for an address someone pre-funded;
43
+ - `programId()` and `findProgramAddressBump(seeds, program)`, to sign as the pool PDA;
44
+ - `initAccount<T>(account)`, Anchor's `load_init`: a program account the body created becomes a struct to fill;
45
+ - `Pubkey.compare`, for the original's `token_0_mint < token_1_mint`;
46
+ - `ata.create(payer, tokenProgram)`, an associated token account under one of several token programs.
47
+
48
+ `Init` accounts also now fail on an address already in use as Anchor's do. TypeSOL used to check first and fail with
49
+ 3000; now the System Program refuses the address (`AccountAlreadyInUse`, custom 0). It also checks that the payer is
50
+ not the account being created (4101).
51
+
52
+ Four Token-2022 reads were added to the compiler for this port (`test/integrations/t22ext.test.ts`):
42
53
 
43
54
  - `transferFeeInverse(mint, amountReceived)`: spl-token-2022's `calculate_inverse_epoch_fee`, used for deposits and
44
55
  exact-output swaps.
@@ -54,8 +65,8 @@ The rest uses features TypeSOL already had:
54
65
 
55
66
  ## How it was checked
56
67
 
57
- [`test/examples/raydium-cp-swap.test.ts`](../test/examples/raydium-cp-swap.test.ts) loads the binary dumped from
58
- mainnet on 2026-10-30 (slot 452376460; sha256 in [`test/programs/SOURCES.md`](../test/programs/SOURCES.md)) into one
68
+ [`test/examples/raydium-cp-swap.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-cp-swap.test.ts) loads the binary dumped from
69
+ mainnet on 2026-10-30 (slot 452376460; sha256 in [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one
59
70
  LiteSVM and the port into another. Both use the same program id and the same clock.
60
71
 
61
72
  **Setup.**
@@ -67,8 +78,18 @@ LiteSVM and the port into another. Both use the same program id and the same clo
67
78
  **Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
68
79
  code), the same lamports, owner and data for every account involved, and the same events byte for byte.
69
80
 
70
- There are 59 transactions:
71
-
81
+ There are 70 transactions:
82
+
83
+ - **Pool creation.** These cases are covered:
84
+ - a pool at its PDA, at a signing keypair, and at a pre-funded address;
85
+ - a pool with the creation fee, paid in wrapped SOL;
86
+ - a pool of Token-2022 fee mints;
87
+ - creating the same pool twice;
88
+ - an address that did not sign (2501);
89
+ - mints in the wrong order (2003);
90
+ - an unsupported extension (6007);
91
+ - a disabled config (6000);
92
+ - too little liquidity (6009).
72
93
  - **Swaps.** Both directions, by input and by output; the observation ring advancing as the clock moves; slippage
73
94
  (6005); zero amounts.
74
95
  - **Liquidity.** Deposit, a partial withdrawal, slippage both ways, withdrawing more LP than held, zero.
@@ -92,20 +113,29 @@ Compute units per transaction, mainnet original against the port, from that test
92
113
 
93
114
  | Instruction | Raydium (mainnet) | TypeSOL | |
94
115
  | --- | ---: | ---: | ---: |
95
- | `swap_base_input` | 24,142 | 7,478 | −69% |
96
- | `swap_base_output` | 24,571 | 8,029 | −67% |
97
- | `deposit` | 25,004 | 6,594 | −74% |
98
- | `withdraw` | 25,211 | 6,451 | −74% |
99
- | `collect_protocol_fee` | 20,205 | 4,200 | −79% |
100
- | `swap_base_input`, Token-2022 transfer fees | 31,334 | 13,813 | −56% |
101
- | `swap_base_output`, Token-2022 transfer fees | 32,511 | 15,935 | −51% |
102
- | `deposit`, Token-2022 transfer fees | 33,206 | 14,834 | −55% |
116
+ | `initialize` | 83,474 | 39,352 | −53% |
117
+ | `initialize`, Token-2022 transfer fees | 101,962 | 55,795 | −45% |
118
+ | `swap_base_input` | 24,142 | 5,734 | −76% |
119
+ | `swap_base_output` | 24,571 | 5,941 | −76% |
120
+ | `deposit` | 25,004 | 6,190 | −75% |
121
+ | `withdraw` | 25,211 | 6,201 | −75% |
122
+ | `collect_protocol_fee` | 20,205 | 4,189 | −79% |
123
+ | `swap_base_input`, Token-2022 transfer fees | 31,365 | 12,083 | −61% |
124
+ | `swap_base_output`, Token-2022 transfer fees | 32,542 | 14,101 | −57% |
125
+ | `deposit`, Token-2022 transfer fees | 33,237 | 14,482 | −56% |
103
126
 
104
127
  The Token-2022 rows include the token program's own work, which is the same in both. Refusals cost far less. For
105
- example, a swap through the wrong config costs 17,190 against 1,628.
128
+ example, a swap through the wrong config costs 17,190 against 1,656.
129
+
130
+ On size, the port's binary is 143,560 bytes and the deployed original is 793,824 bytes. The original also contains the
131
+ 14 instructions not ported here, so the size ratio overstates the gain for the same feature set.
132
+
133
+ Pool creation is mostly the token programs' and the System Program's own work (account creation, initialization,
134
+ transfers), which costs the same in both. The difference is the program's part. Its cost also varies from run to run
135
+ with the PDA bump searches of the random keys the test uses, in both programs alike.
106
136
 
107
- On size, the port's binary is 105,952 bytes and the deployed original is 793,824 bytes. The original also contains the
108
- 15 instructions not ported here, so the size ratio overstates the gain for the same feature set.
137
+ Two general optimizations came out of profiling this port. u128 arithmetic now takes the native 64-bit instructions
138
+ when the values fit, and an instruction reads the Clock once. Together they took a swap from 7,478 to 5,734.
109
139
 
110
140
  ## Where they differ
111
141
 
package/docs/cli.md CHANGED
@@ -7,10 +7,11 @@ 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]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin) and `.gitignore`. `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
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
11
  | `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools, the Solana CLI, its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
11
- | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a missing or different keypair. |
12
+ | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. |
12
13
  | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile]` | Outside a project (or a file that is not one of its programs): build that file. A project program's `.ts` builds as that program. |
13
- | `typesol check <file.ts> [--json] [--stdin]` | Type-check and validate without building. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk). |
14
+ | `typesol check [<program>… \| <file.ts>] [--json] [--stdin]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk). |
14
15
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
15
16
  | `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …]` | Build, then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. Before sending anything it checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
16
17
  | `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`). |
@@ -33,7 +34,8 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
33
34
  ```
34
35
 
35
36
  `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
36
- safe and out of git: it is each program's address and its first upgrade authority must not lose it.
37
+ safe and out of git: it is each program's address and its first upgrade authority must not lose it. A clone without
38
+ it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
37
39
 
38
40
  ## Editor
39
41
 
package/docs/errors.md CHANGED
@@ -21,7 +21,8 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
21
21
  | 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
22
22
  | 2024–2039 | an existing mint `createIfNeeded` found lacks a Token-2022 extension it was given, or holds other keys in it: group pointer 2024–2026, group member pointer 2027–2029, metadata pointer 2030–2032, close authority 2033–2034, permanent delegate 2035–2036, transfer hook 2037–2039 (the first code of each: the extension is missing; the next: the authority / address differs) (ConstraintMint…Extension…) |
23
23
  | 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
24
- | 3000 | account already exists (AccountDiscriminatorAlreadySet; an `Init` account) |
24
+ | 0 (from the System Program) | an `Init` / `create` on an address already in use (AccountAlreadyInUse): the System Program refuses it, as under Anchor's `init` |
25
+ | 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
25
26
  | 3002 | discriminator mismatch (AccountDiscriminatorMismatch) |
26
27
  | 3003 | data too small, not an initialized token account / mint, a read past the end, or a `@layout borsh` account whose bytes are not a valid Borsh value (AccountDidNotDeserialize) |
27
28
  | 3004 | a `@layout borsh` account too small for the value it would now hold (AccountDidNotSerialize) |
@@ -33,6 +34,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
33
34
  | 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
34
35
  | 3012 | account not initialized: empty system account where a program account was expected (AccountNotInitialized) |
35
36
  | 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
37
+ | 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
36
38
  | 4102 | cast overflow (InvalidNumericConversion) |
37
39
  | 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
38
40
  | 5103 | sysvar unavailable |
package/docs/language.md CHANGED
@@ -12,7 +12,7 @@ The full reference. For a tour, start with the [README](../README.md).
12
12
  | Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
13
13
  | Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
14
14
  | Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+; `require(cond, "message")` makes an error of its own (`RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL); `require(cond, AnchorError.RequireKeysEqViolated)` fails with one of Anchor's own codes (2502 here; any anchor-lang `ErrorCode` can be raised this way). See [errors.md](errors.md) |
15
- | Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit |
15
+ | Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit. A cast is a value: import `u64`, not `type u64` (one import serves as both) |
16
16
  | Logging | `log("text")`, `log(value)`, `log(pubkey)` |
17
17
  | Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
18
18
  | Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack |
@@ -28,6 +28,7 @@ The full reference. For a tour, start with the [README](../README.md).
28
28
  | Anchor's account bytes | `/** @layout borsh */` on an account struct stores it as Anchor does (Borsh: a `FixedString<N>` is a String, a `FixedVec<T, N>` or `Vec<T>` a Vec, an `Option` one byte when empty, and the fields after them move), so a TypeSOL program can take over accounts an Anchor program wrote and the IDL lists Anchor's own types. The instruction unpacks it into the usual fixed layout when it starts (bad bytes fail with 3003) and packs it back when it returns (3004 when the account is too small for the new value), so everything else works on it unchanged. A `Vec<T>` field (any position; integers, booleans, Pubkeys, unit enums or fixed-size structs) is Anchor's own: held on the heap while the instruction runs, growing as Rust's Vec does, bounded only by the account when it is written back (3004); its elements move when it grows, so a reference into one cannot outlive a `push` or an assignment. `Init` of such a struct takes its space, `create(payer, seeds, space)`. Programs invoked from the body (CPIs) see the account's bytes as they were when the instruction started. Costs more compute than the fixed layout (the whole account is read and written each time; see the benchmarks); nested structs and list elements must be fixed-size (FixedString elements allowed). The same struct is Borsh as a whole instruction argument (checked like Borsh deserialization, UTF-8 included), as return data and as an event; as those (not as account data) it may also hold `string` fields and data enums carrying strings, Anchor's `String` and enums in argument structs (account data takes data enums without strings); not inside list or enum arguments or `loadAccount`, and a struct holding a `Vec<T>` is account data or a whole argument, not return data or an event |
29
29
  | Fixed-capacity lists | `owners: FixedVec<Pubkey, 8>` — any field, any number of them, in nested structs too: a u32 length and room for N elements (always 4 + N × size bytes), the same `get`, `set`, `push(v)`, `pop()`, `clear()`, `.length` and `for … of`; `push` on a full one fails (5104); `acct.owners = fixedVec([a, b])` writes a whole one (unused slots zeroed), and `acct.owners = owners` copies a `Vec` argument (or another list of the same elements) into it, Anchor's `multisig.owners = owners` (more than N fail with 5104). In account data, returned structs and events; as an argument (`ids: FixedVec<u64, 8>`) it is a Borsh Vec of at most N elements, read like a `Vec` argument (more fail with 102) |
30
30
  | Struct arguments | `order: Order`, `ids: FixedArray<u8, 4>`, `orders: Vec<Order>` — fixed layouts, Borsh-identical, validated on entry (bools, enums, option tags, string lengths, enum tags; 102) and read-only. A struct holding a FixedVec that is only ever an argument is read as Anchor sends it (its FixedVec a Borsh Vec, as `@layout borsh`) |
31
+ | Accounts created by hand | `systemProgram.createAccount(…)`, or `allocate(account, space, seeds?)` + `assign(account, owner, seeds?)` for an address someone pre-funded, then `const data = initAccount<T>(account)` (Anchor's `load_init`: owned by this program 3007, writable 3006, large enough 3003, no discriminator yet 3000) gives the struct to fill: for accounts whose address is decided at run time (a PDA or a signing keypair), as Raydium's pools are. `Init<T>` covers the usual case |
31
32
  | Remaining accounts | `remainingAccounts()` — `.length`, `.get(i)` → `key`, `owner`, `lamports` (writes check writability), `isSigner`, `isWritable`; `loadAccount<T>` / `loadAccountMut<T>` give checked struct views; pass them to `invoke`, one at a time or spread: `...remainingAccounts()` (each with the flags it was passed with), `...readonly(rest)` / `...writable(rest)` (all with that role), `rest.slice(a, b)` for part of them; a CPI lists at most as many accounts as an instruction takes (5113) |
32
33
  | Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
33
34
  | Struct references | `const o = side === Side.Bid ? book.bids.get(i) : book.asks.get(i)` — aliases account data like a JS object reference (no copy); replacing the referenced place (`book.bids.set(i, …)`, `pop()`, `clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JS would keep the old object |
@@ -38,7 +39,7 @@ The full reference. For a tour, start with the [README](../README.md).
38
39
  | Option of structs | `home: Option<Point>` in account data — `=== null`, `p.home.x` after narrowing, `p.home = null` / `{ x, y }` |
39
40
  | Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58) — built on the 32 KiB heap (5110 when full): a template is joined in one allocation, text known at compile time (literals, string and Pubkey constants) is folded in, and `s += …` grows the newest heap string in place |
40
41
  | `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
41
- | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash`; `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
42
+ | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash`; `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump; `programId()` → this program's address; `a.compare(b)` orders Pubkeys as Rust does (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
42
43
  | Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted) (mainnet program unless `SwitchboardFeed<"devnet">`) |
43
44
  | Multiple files | `import { Side, min } from "./math"` — structs, enums, constants and helpers can live in other files; only the entry file's exported functions are instructions; names are program-wide, so imports from TypeSOL files cannot be renamed; error codes number imported files first |
44
45
  | Loops | `for (let i = 0n; i < n; i++)`, `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
@@ -66,8 +67,10 @@ The full reference. For a tour, start with the [README](../README.md).
66
67
  | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable) |
67
68
  | `Init<T>` | writable; `create(payer, seeds)` derives the PDA, verifies it, funds rent, writes the discriminator (up to 10 KiB); `create(payer, null)` creates a new keypair account that signs the transaction instead (3010 if it did not; a signer in the IDL); a third argument is Anchor's `space = …` (discriminator included, at least 8 + the struct's size) |
68
69
  | `InitIfNeeded<T>` | `const created = acct.createIfNeeded(payer, seeds)` — creates once; afterwards re-derives the PDA and checks owner, discriminator and size (Anchor `init_if_needed`); `acct.pdaBump` after create. An existing account is used as it is: check the fields you rely on |
70
+ | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`); a group may not be optional, nest another group, or be a helper parameter. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
69
71
  | `constraint(acct, condition, error?)` | Anchor's `constraint = condition @ error` on `acct`: statements at the very start of the body, run with that account's checks (after its `has_one`, before the next account), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
70
72
  | `HasOne<A, "owner">`, `Seeds<A, ["vault", "@owner"], "bump">`, `CloseTo<A, "owner">` | declarative constraints like Anchor's `has_one`, `seeds`/`bump` and `close`: checked before the body (2001 / 2006), close runs when the instruction succeeds; `"@name"` = account key or argument bytes, `"@acct.field"` = a Pubkey, integer or unit enum field of a struct account parameter (also the account's own: `["offer", "@maker", "@offer.id"]`), other strings are literals; recorded as `relations` / `pda` in the IDL. a bump stored in another struct account is named `"@acct.field"` (Anchor `bump = multisig.nonce`); `acct.pdaBump` is the bump (Anchor `ctx.bumps.acct`): the stored field when one is named, else the canonical bump the check found — use it to sign as the PDA |
73
+ | `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` | one of your errors instead of Anchor's code, as Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the constraints Anchor lets you name an error for); a member of one of the program's error enums. For several `HasOne` fields with different errors, nest them: `HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>` |
71
74
  | `HasOne<TokenAccount, "mint" \| "owner">`, `HasOne<Mint, "mintAuthority" \| "freezeAuthority">` | token constraints (2014 / 2015 / 2016 / 2017) against the parameter with that name; `TokenOf<TokenAccount, "mintParam", "authorityParam", "tokenProgramParam">` / `MintOf<Mint, "authorityParam", "freezeParam", "tokenProgramParam">` name the parameters, as Anchor's `token::mint = …` / `mint::authority = …` / `…::token_program = …` do (`never` leaves one out; the token program one: owned by that token program, 2021 / 2022) |
72
75
  | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
73
76
  | `Ata<Init<TokenAccount>, "owner", "mint">`, `Ata<InitIfNeeded<TokenAccount>, "owner", "mint">` | Anchor `init` / `init_if_needed` with `associated_token::…`: `acct.create(payer)` creates the ATA (fails if it exists); `const created = acct.createIfNeeded(payer)` creates it only when missing, otherwise checks it is that ATA (2009). Then it is a `TokenAccount` of that mint and owner (2014 / 2015). Needs `AssociatedTokenProgram`, `SystemProgram` and a token program parameter; call it at the top level before using the account |
@@ -107,11 +110,14 @@ with `i == j`) is refused with 2040 too, since the two views would alias.
107
110
 
108
111
  ## Built-ins
109
112
 
110
- - `systemProgram.transfer(from: Mut<Signer>, to, lamports)`, `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
113
+ - `systemProgram.transfer(from, to, lamports, signerSeeds?)` (`from` is a `Mut<Signer>`, or a system-owned PDA of this
114
+ program, a SOL vault, with its seeds), `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
111
115
  (the new account signs: a keypair `Mut<Signer>` or this program's PDA), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
112
116
  - Token programs (`TokenProgram`, `Token2022Program`, `TokenInterface`) — pass `signerSeeds` (with the bump) when the authority is a PDA:
113
117
  `transfer`, `transferChecked(from, mint, to, authority, amount)` (required by Token-2022 mints with fees/hooks), `mintTo` (the mint may be one this instruction just created), `burn`, `closeAccount` (a token account, or a Token-2022 mint with a close authority),
114
- `approve(source, delegate, owner, amount)`, `revoke`, `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
118
+ `approve(source, delegate, owner, amount)`, `revoke`, the checked forms `mintToChecked(mint, to, authority, amount)`,
119
+ `burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
120
+ come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
115
121
  `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
116
122
  `initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`. Each takes optional signerSeeds
117
123
  - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
@@ -150,8 +156,14 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
150
156
  - data (Borsh): integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
151
157
  Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
152
158
  `sighash("name")` (Anchor discriminator), `hex("0a0b")`. Up to 1024 bytes.
153
- - `signerSeeds` (with the bump) signs for this program's PDA.
159
+ - `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
160
+ lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
161
+ - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
162
+ wherever signerSeeds go.
154
163
  - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
164
+ A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
165
+ unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
166
+ declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106.
155
167
 
156
168
  A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
157
169
  `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`):
@@ -30,6 +30,7 @@ and error codes. Its notes (on stderr) list what an existing Anchor client would
30
30
  | Anchor | TypeSOL |
31
31
  | --- | --- |
32
32
  | `#[derive(Accounts)] struct Ctx` + `ctx.accounts.x` | the instruction's parameters, in the same order |
33
+ | a composite field, `pub pool: PoolAccounts<'info>` + `ctx.accounts.pool.vault` | an account group: `export interface PoolAccounts { vault: Mut<TokenAccount>; … }`, the parameter `pool: PoolAccounts`, and `pool.vault` |
33
34
  | `Signer<'info>` / `#[account(mut)] Signer` | `Signer` / `Mut<Signer>` |
34
35
  | `Account<'info, T>` / `#[account(mut)]` | `Account<T>` / `Mut<T>` |
35
36
  | `#[account(init, payer = p, space = …, seeds = […], bump)]` | `Init<T>`, then `const bump = acct.create(p, ["seed", other.key])` (space is computed; `acct.create(p, […], 8n + 64n)` keeps an explicit `space`) |
@@ -38,6 +39,7 @@ and error codes. Its notes (on stderr) list what an existing Anchor client would
38
39
  | `seeds = [b"vault", owner.key().as_ref()], bump = vault.bump` | `Seeds<Mut<Vault>, ["vault", "@owner"], "bump">` |
39
40
  | `seeds = [b"offer", offer.maker.as_ref(), offer.id.to_le_bytes().as_ref()]` | `Seeds<…, ["offer", "@offer.maker", "@offer.id"], "bump">` |
40
41
  | `has_one = owner` | `HasOne<Mut<T>, "owner">` |
42
+ | `has_one = owner @ ErrorCode::NotOwner` (also `address`, `owner`, `signer`, `mut` with `@ …`) | `HasOne<Mut<T>, "owner", ErrorCode.NotOwner>`; `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` |
41
43
  | `close = destination` | `CloseTo<Mut<T>, "destination">`, or `close(acct, destination)` in the body |
42
44
  | `address = ADMIN` | `Address<AccountInfo, "Admin1111…">` |
43
45
  | `owner = program`, `executable` | `Owner<A, "…">`, `Executable<A>` |
@@ -110,6 +112,10 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
110
112
  | `Rent::get()?.minimum_balance(n)` | `rentExempt(n)`, `minimumBalance(acct)` |
111
113
  | `system_program::transfer(CpiContext::new(…), lamports)` | `systemProgram.transfer(from, to, lamports)` |
112
114
  | `token::transfer_checked(CpiContext::new_with_signer(…, seeds), amount, decimals)` | `tokenProgram.transferChecked(from, mint, to, authority, amount, ["seed", key, bump])` |
115
+ | `token::mint_to_checked` / `burn_checked` / `approve_checked` | `tokenProgram.mintToChecked(mint, to, authority, amount)` / `burnChecked(from, mint, authority, amount)` / `approveChecked(source, mint, delegate, owner, amount)` |
116
+ | `system_program::transfer(CpiContext::new_with_signer(…, &[vault_seeds]), lamports)` | `systemProgram.transfer(vault, to, lamports, ["vault", owner.key, bump])` |
117
+ | `invoke_signed(&ix, infos, &[seeds_a, seeds_b])` | `invoke(program, accounts, data, [seedsA, seedsB])` |
118
+ | `let (_, data) = get_return_data().unwrap(); Quote::try_from_slice(&data)?` | `const quote = returnData<Quote>(program)` (a `@layout borsh` struct when it holds Options, strings or Vecs) |
113
119
  | `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
114
120
  | `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
115
121
  | `multisig.owners = owners` (a `Vec` argument into account data) | the same |
@@ -43,15 +43,24 @@ instruction that takes the bump as an argument.
43
43
 
44
44
  | Helper | Gives |
45
45
  | --- | --- |
46
- | `t.ok(res)` | the successful result, or throws with the program's logs |
46
+ | `t.ok(res)` | the successful result, or throws with the error, its name (`NotAdmin`) and the program's logs |
47
47
  | `t.errorCode(res)` | the custom error code of a failed transaction: 6000 + the member's index in your error enum, or a framework code ([errors.md](errors.md)) |
48
48
  | `t.account(type, address)` | the account decoded by its IDL type (bigints, address strings), or `null` once closed. TypeSOL fixed layouts come back as their IDL structs: a `FixedString<N>` as `{ len, bytes }`, a `FixedVec<T, N>` as `{ len, items }` (the generated client gives strings and arrays) |
49
49
  | `t.returned(instruction, res)` | the instruction's return data: an integer, boolean, Pubkey or struct |
50
50
  | `t.balance(address)` | lamports |
51
+ | `t.errorName(code)` | the name of an error code: your program's, TypeSOL's or Anchor's |
51
52
  | `t.connection` | `{ rpc, rpcSubscriptions }` answered by this LiteSVM, for the generated client: `counter.sendInstructions(t.connection, alice, [ix])`, `counter.accounts.Counter.fetch(t.connection.rpc, address)`, views, `resolve`, `watch` and `watchEvents` (as on a cluster: `watch` yields when a later transaction changes the account, not at once; `watchEvents` gets transactions sent after it subscribed, failed ones included in the stream and skipped by the client) |
52
53
 
53
- `t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else, e.g. writing a mint straight into the VM
54
- with `t.svm.setAccount` (see the escrow template). `programHarness(svm, programId, idl)` gives the same helpers for a
54
+ ## Tokens and time
55
+
56
+ | Helper | Does |
57
+ | --- | --- |
58
+ | `t.mint({ authority, decimals?, supply?, freezeAuthority?, tokenProgram?, address? })` | writes a mint straight into the VM, as CreateAccount + InitializeMint2 leave it (SPL Token unless `tokenProgram` is Token-2022; no extensions), and returns its address |
59
+ | `t.tokenAccount({ mint, owner, amount?, tokenProgram?, address? })` | writes a token account holding `amount`; pass `address` for an associated token account |
60
+ | `t.tokenBalance(address)` | the amount a token account holds, or `null` when it does not exist |
61
+ | `t.warp({ unixTimestamp?, slot?, seconds? })` | moves the Clock: to a timestamp or slot, or forward by `seconds` |
62
+
63
+ `t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else. `programHarness(svm, programId, idl)` gives the same helpers for a
55
64
  program you loaded yourself, and `svmConnection(svm)` the RPC pair alone (for any LiteSVM, e.g. one with an Anchor
56
65
  program loaded). Transactions sent through it run at once; `getProgramAccounts` (`fetchAll`) sees the accounts those
57
66
  transactions named, plus any you `track(...)`.
package/docs/testing.md CHANGED
@@ -9,7 +9,7 @@ run prints its seed; reproduce with `FUZZ_SEED=<n>`, widen with `FUZZ_RUNS` / `F
9
9
  | `test/verification/fuzz-state.test.ts` | TypeScript state model | random honest + hostile actions on vault and escrow: every outcome as predicted, balances equal the model, SOL conserved up to fees, token supply exactly conserved; random filings/decisions/resets on ledgerbook: Vec contents, account size and rent exemption equal the model |
10
10
  | `test/verification/fuzz-layout.test.ts` | TypeScript model | random pushes, pops, sets, in-place additions, moves and clears on an account with two growable Vecs (honest, out of range and by a stranger): the decoded account equals the model after every step; random `loadAccountMut` index pairs over remaining-account lists that repeat accounts: every alias refused (2040), balances conserved |
11
11
  | `test/verification/differential.test.ts` | Anchor twins in `test/anchor-twins` | identical transactions to TypeSOL and Anchor programs: same outcomes, same account contents, same wallet and token balances after every step |
12
- | `test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `test/ports/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([test/ports/README.md](../test/ports/README.md)) |
12
+ | `test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `test/ports/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([test/ports/README.md](https://github.com/typesol/typesol/blob/main/test/ports/README.md)) |
13
13
 
14
14
  Compute-unit and binary-size comparisons with Anchor, native Rust and Pinocchio are in the README
15
15
  ([Numbers](../README.md#numbers)).