@typesol/cli 0.37.0 → 0.38.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 CHANGED
@@ -6,6 +6,32 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.38.0 — 2026-11-01
10
+
11
+ Raydium CLMM ported in full, and Jito's three MEV programs ported, each checked against its mainnet binary. The
12
+ compiler gained what the Jito programs needed: stored bumps in nested struct fields, Anchor's names for arguments
13
+ that share an account's name, and error members without messages. Programs that use none of these compile to the
14
+ same binaries as in 0.37.0.
15
+
16
+ - Examples: examples/raydium-clmm now ports all 37 of Raydium CLMM's instructions. Added: the customizable pools,
17
+ the v1 and v2 positions with Metaplex NFTs, `close_position`, `swap` and the multi-hop `swap_router_base_in`, the
18
+ five limit order instructions, the reward instructions, and the admin instructions (configs, operators, dynamic fee
19
+ configs, support mints, pool status, `collect_excess_lamports`). The differential test runs the admin instructions
20
+ too, with Raydium's admin key swapped for a test key in both programs: 300 transactions, the same outcomes, account
21
+ bytes and events, 33–84% fewer compute units.
22
+ - Examples: examples/jito-mev, ports of Jito's three MEV programs (tip payment, tip distribution, priority fee
23
+ distribution; all 24 instructions), checked against the mainnet binaries (test/programs/jito_*.so) on 150
24
+ transactions: the same outcomes, account bytes, events and log lines, with 58–95% fewer compute units. The tip
25
+ payment port follows the binary on mainnet, which is the program of Jito's #143 (no `claim_tips`). See
26
+ docs/case-study-jito-mev.md.
27
+ - New: a `Seeds<…>` bump stored in a struct field of another account, `"@config.bumps.vault"` (Anchor's
28
+ `bump = config.bumps.vault`).
29
+ - New: an error enum member with an empty message, `X = ""`, has no `msg` in the IDL (an Anchor variant without
30
+ `#[msg]`).
31
+ - IDL: an instruction argument named like one of its accounts plus a trailing underscore (`authority_` next to an
32
+ `authority` account) keeps the account's name in the IDL, as Anchor names such an argument.
33
+ - Typings: `Hash.compare(other)`, the byte order of two hashes (-1, 0 or 1), which the compiler already supported.
34
+
9
35
  ## 0.37.0 — 2026-10-31
10
36
 
11
37
  Raydium CLMM ported and checked against the mainnet binary, with what it needed: `u256`, big-endian seeds,
package/README.md CHANGED
@@ -179,8 +179,10 @@ program through the port; [docs/case-study-multisig.md](docs/case-study-multisig
179
179
  checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units), and
180
180
  [docs/case-study-raydium-cp-swap.md](docs/case-study-raydium-cp-swap.md) does the same for Raydium CP-Swap's swaps and liquidity
181
181
  (pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units), and
182
- [docs/case-study-raydium-clmm.md](docs/case-study-raydium-clmm.md) for Raydium CLMM's pools, positions and swaps
183
- (dynamic fees, limit orders and the tick array bitmap extension included: the same on 166 transactions; 43–83% fewer
182
+ [docs/case-study-raydium-clmm.md](docs/case-study-raydium-clmm.md) for all 37 instructions of Raydium CLMM
183
+ (pools, positions, swaps and routes, limit orders, rewards, admin: the same on 300 transactions; 33–84% fewer
184
+ compute units), and [docs/case-study-jito-mev.md](docs/case-study-jito-mev.md) for Jito's three MEV programs (tip
185
+ payment, tip distribution with Merkle claims, priority fee distribution: the same on 150 transactions; 58–95% fewer
184
186
  compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
185
187
  mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
186
188
 
@@ -332,7 +334,8 @@ Details are in [docs/testing.md](docs/testing.md).
332
334
  | [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
333
335
  | [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
334
336
  | [`raydium-cp-swap/`](examples/raydium-cp-swap) | Raydium CP-Swap's trading core: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle |
335
- | [`raydium-clmm/`](examples/raydium-clmm) | Raydium CLMM: concentrated-liquidity positions as Token-2022 NFTs, swaps across tick arrays, u256 math, rewards, dynamic fees |
337
+ | [`raydium-clmm/`](examples/raydium-clmm) | Raydium CLMM in full: concentrated-liquidity positions as NFTs, swaps and multi-hop routes across tick arrays, limit orders, rewards, dynamic fees, u256 math |
338
+ | [`jito-mev/`](examples/jito-mev) | Jito's tip payment, tip distribution and priority fee distribution: tips paid out per leader, Merkle-proof claims, epochs and expiry |
336
339
  | [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
337
340
 
338
341
  ## Status
@@ -46,6 +46,12 @@ export interface TypeScope {
46
46
  }>;
47
47
  }
48
48
  export declare function snakeCase(name: string): string;
49
+ /**
50
+ * An argument's IDL name. Anchor keeps arguments and accounts apart, so an instruction may take an account and an
51
+ * argument of one name (`authority`); TypeScript cannot, so the argument is written with a trailing underscore
52
+ * (`authority_`) and recorded without it.
53
+ */
54
+ export declare function argIdlName(name: string, accountNames: readonly string[]): string;
49
55
  export declare function discriminator(preimage: string): number[];
50
56
  /** Source text by absolute path: an editor's unsaved buffers, read instead of the files on disk. */
51
57
  export type SourceOverrides = ReadonlyMap<string, string>;
@@ -141,6 +141,17 @@ export function snakeCase(name) {
141
141
  .replace(/([A-Z])([A-Z][a-z])/g, "$1_$2")
142
142
  .toLowerCase();
143
143
  }
144
+ /**
145
+ * An argument's IDL name. Anchor keeps arguments and accounts apart, so an instruction may take an account and an
146
+ * argument of one name (`authority`); TypeScript cannot, so the argument is written with a trailing underscore
147
+ * (`authority_`) and recorded without it.
148
+ */
149
+ export function argIdlName(name, accountNames) {
150
+ const base = snakeCase(name);
151
+ if (base.length > 1 && base.endsWith("_") && !base.endsWith("__") && accountNames.some((a) => snakeCase(a) === base.slice(0, -1)))
152
+ return base.slice(0, -1);
153
+ return base;
154
+ }
144
155
  /**
145
156
  * An account struct's discriminator: Anchor's sha256("account:<Name>")[..8], or the one a `/** @discriminator … *\/` tag
146
157
  * gives (a sha256 preimage such as `account:Counter`, or 0x and 8 bytes), e.g. for an old version of a struct kept under
@@ -1761,15 +1772,24 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1761
1772
  reporter.fail(a.node, `HasOne<…, "${f}">: ${struct.name} needs a Pubkey field "${f}"`);
1762
1773
  }
1763
1774
  if (c.seeds?.bump?.startsWith("@")) {
1764
- // "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`).
1765
- const [owner, field, ...rest] = c.seeds.bump.slice(1).split(".");
1775
+ // "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`), or in a struct
1776
+ // field of it ("@config.bumps.vault", Anchor `bump = config.bumps.vault`).
1777
+ const [owner, ...path] = c.seeds.bump.slice(1).split(".");
1766
1778
  const o = accounts.find((x) => x.name === owner);
1767
- const os = o?.kind.kind === "account" ? o.kind.struct : undefined;
1768
- if (!os || !field || rest.length)
1779
+ let os = o?.kind.kind === "account" ? o.kind.struct : undefined;
1780
+ if (!os || !path.length)
1769
1781
  reporter.fail(a.node, `Seeds bump: "${c.seeds.bump}" must name a u8 field of a struct account parameter ("@config.bump")`);
1770
- const bf = os.fields.find((x) => x.name === field);
1771
- if (!bf || bf.type.kind !== "int" || bf.type.name !== "u8")
1772
- reporter.fail(a.node, `Seeds bump: ${os.name} needs a u8 field "${field}"`);
1782
+ for (let i = 0; i < path.length; i++) {
1783
+ const bf = os.fields.find((x) => x.name === path[i]);
1784
+ if (i < path.length - 1) {
1785
+ const inner = bf?.type.kind === "struct" ? structs.get(bf.type.name) : undefined;
1786
+ if (!inner)
1787
+ reporter.fail(a.node, `Seeds bump: ${os.name}.${path[i]} must be a struct field`);
1788
+ os = inner;
1789
+ }
1790
+ else if (!bf || bf.type.kind !== "int" || bf.type.name !== "u8")
1791
+ reporter.fail(a.node, `Seeds bump: ${os.name} needs a u8 field "${path[i]}"`);
1792
+ }
1773
1793
  }
1774
1794
  else if (c.seeds?.bump) {
1775
1795
  if (!struct)
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { snakeCase } from "../analyze.js";
2
+ import { argIdlName, snakeCase } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
4
4
  import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
5
5
  import { CallEmitter } from "./calls.js";
@@ -115,7 +115,10 @@ export class CpiCoreEmitter extends CallEmitter {
115
115
  }
116
116
  // Only the argument itself, not a local that shadows its name.
117
117
  if (ts.isIdentifier(el) && this.ix?.args.some((a) => a.name === el.text) && this.lookup(el.text) === this.args.get(el.text))
118
- return { kind: "arg", path: snakeCase(el.text) };
118
+ return {
119
+ kind: "arg",
120
+ path: argIdlName(el.text, this.ix.accounts.map((o) => o.name)),
121
+ };
119
122
  if (ts.isIdentifier(el) && !this.lookup(el.text)) {
120
123
  const k = this.model.constants.get(el.text);
121
124
  if (k && typeof k.value === "string")
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { snakeCase } from "../analyze.js";
2
+ import { snakeCase, argIdlName } from "../analyze.js";
3
3
  import { decodeAddress } from "../../keys.js";
4
4
  import { INT_INFO, isScalar, isWritable, scalarSize, typeName, } from "../model.js";
5
5
  import { borshIdentical, borshMinSize } from "./borsh.js";
@@ -670,7 +670,10 @@ export class FunctionEmitter extends StatementEmitter {
670
670
  parts.push(`{(const uint8_t *)&arg_${n}, ${scalarSize(t)}}`);
671
671
  else
672
672
  this.reporter.fail(a.node, `Seeds: argument "${n}" of type ${typeName(t)} cannot be a seed`);
673
- idl.push({ kind: "arg", path: snakeCase(n) });
673
+ idl.push({
674
+ kind: "arg",
675
+ path: argIdlName(n, ix.accounts.map((o) => o.name)),
676
+ });
674
677
  }
675
678
  else {
676
679
  notInt();
@@ -29,9 +29,9 @@ export declare function buildIdl(model: ProgramModel, address: string, version?:
29
29
  discriminator: number[];
30
30
  }[];
31
31
  errors: {
32
+ msg?: string | undefined;
32
33
  code: number;
33
34
  name: string;
34
- msg: string;
35
35
  }[];
36
36
  types: ({
37
37
  type: {
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { snakeCase } from "./analyze.js";
2
+ import { argIdlName, snakeCase } from "./analyze.js";
3
3
  import { decodeAddress } from "../keys.js";
4
4
  import { fixedVecName, isWritable, optionKey, typeName, } from "./model.js";
5
5
  const SYSTEM_PROGRAM = "11111111111111111111111111111111";
@@ -204,12 +204,16 @@ export function buildIdl(model, address, version = "0.1.0") {
204
204
  ...docsOf(ix.node),
205
205
  discriminator: ix.discriminator,
206
206
  accounts: nestGroups(ix, (a) => accountEntry(ix, a.name, a.kind, address)),
207
- args: ix.args.map((a) => ({ name: snakeCase(a.name), ...paramDocs(a.node), type: idlType(a.type, true) })),
207
+ args: ix.args.map((a) => ({
208
+ name: argIdlName(a.name, ix.accounts.map((o) => o.name)),
209
+ ...paramDocs(a.node),
210
+ type: idlType(a.type, true),
211
+ })),
208
212
  ...(ix.returns ? { returns: idlType(ix.returns) } : {}),
209
213
  })),
210
214
  accounts: structs.filter((s) => model.accountStructs.has(s.name)).map((s) => ({ name: s.name, discriminator: s.accountDiscriminator })),
211
215
  events: structs.filter((s) => model.events.has(s.name)).map((s) => ({ name: s.name, discriminator: s.eventDiscriminator })),
212
- errors: model.errors.map((e) => ({ code: e.code, name: e.name, msg: e.msg })),
216
+ errors: model.errors.map((e) => ({ code: e.code, name: e.name, ...(e.msg ? { msg: e.msg } : {}) })),
213
217
  types: [
214
218
  ...usedStructs.map((s) => ({
215
219
  name: s.name,
@@ -0,0 +1,167 @@
1
+ # Case study: Jito's MEV programs
2
+
3
+ This page ports the three on-chain programs behind Jito's MEV tips, from
4
+ [jito-foundation/jito-programs](https://github.com/jito-foundation/jito-programs) (`mev-programs/programs` at ce1dfb6,
5
+ Anchor 0.31.1, Apache-2.0). Each one is checked against the binary that runs on mainnet, not a rebuild:
6
+
7
+ | Program | Mainnet id | Port |
8
+ | --- | --- | --- |
9
+ | Tip payment | `T1pyyaTNZsKv2WcRAB8oVnk93mLJw2XzjtVYqCsaHqt` | [`tip_payment.ts`](https://github.com/typesol/typesol/blob/main/examples/jito-mev/tip_payment.ts) |
10
+ | Tip distribution | `4R3gSG8BpU4t19KYj8CfnbtRpnT8gtk4dvTHxVRwc2r7` | [`tip_distribution.ts`](https://github.com/typesol/typesol/blob/main/examples/jito-mev/tip_distribution.ts) |
11
+ | Priority fee distribution | `Priority6weCZ5HwDn29NxLFpb7TDp2iLZ6XKc5e8d3` | [`priority_fee_distribution.ts`](https://github.com/typesol/typesol/blob/main/examples/jito-mev/priority_fee_distribution.ts) |
12
+
13
+ Searchers pay tips into eight fixed tip payment accounts. When the leader changes, the tip payment program pays them
14
+ out to the current tip receiver and the block builder's commission to the block builder. The tip receiver is
15
+ usually the validator's tip distribution account for the epoch. After the epoch, an uploaded Merkle root says who may
16
+ claim how much from it. The priority fee distribution program does the same for the priority fees a validator shares.
17
+
18
+ ## What is ported
19
+
20
+ All 24 instructions of the three programs:
21
+
22
+ - **Tip payment.** `initialize`, which creates the config and the eight tip accounts, then `change_tip_receiver` and
23
+ `change_block_builder`. Each pays out the tips collected so far before it changes anything.
24
+ - **Tip distribution.**
25
+ - `initialize` and `update_config`;
26
+ - `initialize_tip_distribution_account`, signed by the vote account's node key;
27
+ - `upload_merkle_root` and `claim`, with a Merkle proof;
28
+ - `close_claim_status` and `close_tip_distribution_account`, once the account has expired;
29
+ - the merkle root upload config (`initialize_` / `update_merkle_root_upload_config`) and
30
+ `migrate_tda_merkle_root_upload_authority`.
31
+ - **Priority fee distribution.** The same ten instructions under its own names, and `transfer_priority_fee_tips`. That
32
+ instruction counts the fees a validator moves into its account, and moves them only from the go-live epoch on.
33
+
34
+ `merkle.ts` holds the Merkle proof check the two distribution programs share. Each file keeps its program's account
35
+ layouts, names, argument order and error codes. Each emits the same events and writes the same log lines.
36
+
37
+ The tip payment program on mainnet is not the one at the last commit before its deploy (b230b2b, which still has
38
+ `claim_tips`). Its binary has no `claim_tips` and logs the `WARN: did not transfer …` lines of #143, the "payments
39
+ patch". The repository merged #143 after that deploy, and ce1dfb6 has the same program. The port follows the binary.
40
+
41
+ ## What it needed
42
+
43
+ - **A bump stored inside another account's struct.** Anchor's `bump = config.bumps.tip_payment_account_0` reads the
44
+ bump from a nested field. `Seeds<…>` now takes that path: `"@config.bumps.tip_payment_account_0"`.
45
+ - **An argument named like an account.** `initialize_merkle_root_upload_config` has an `authority` account and an
46
+ `authority` argument. TypeSOL needs distinct names, so the port names the argument `authority_`. An argument whose
47
+ name is an account's plus one trailing underscore keeps the account's name in the IDL, so clients encode the same
48
+ arguments.
49
+ - **Errors without messages.** The tip payment errors have no `#[msg]`. A member written `X = ""` now leaves `msg`
50
+ out of the IDL, as Anchor does.
51
+ - **Hash ordering.** The proof check orders each pair of hashes before hashing them. `Hash.compare` was already
52
+ compiled; its typing was missing.
53
+ - **One account in two writable slots.** The original lets several of these accounts be the same account:
54
+ - right after `initialize`, the tip receiver and the block builder are both the payer;
55
+ - a claimant can pay for its own claim record;
56
+ - a cranker can sign as the expired funds account.
57
+
58
+ `Dup<…>` lifts TypeSOL's check for exactly those parameters.
59
+ - **A float in a log line.** Before it goes live, `transfer_priority_fee_tips` logs the amount in SOL to five
60
+ decimals. Rust formats the `f64` nearest to `lamports / 1e9` with `{:.5}`. The port works this out in integers:
61
+ - the 53-bit mantissa of that `f64`, rounded half to even;
62
+ - then that binary value rounded at five decimals, ties to even.
63
+
64
+ For example, 35,000 lamports prints `0.00003`, because the `f64` is just below 0.000035, while 15,625,000 lamports
65
+ (exactly 1/64 SOL) prints `0.01562`. Tests for the compiler parts are in `test/language/anchor-shapes.test.ts`.
66
+
67
+ The rest uses what TypeSOL already had:
68
+
69
+ - the Merkle root as an `Option<MerkleRoot>` in a `@layout borsh` account;
70
+ - lamports moved directly between accounts;
71
+ - the vote account's node key read at bytes 4..36;
72
+ - explicit account sizes where Anchor reserves the Rust struct's padded size (tip distribution's `Config` is 88
73
+ bytes, its `TipDistributionAccount` 168).
74
+
75
+ ## How it was checked
76
+
77
+ [`test/examples/jito-mev.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/jito-mev.test.ts) loads
78
+ the binaries dumped from mainnet on 2026-10-31 (sha256 in
79
+ [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)). A dump is padded
80
+ with zeros to its program account's size, 10 MB for tip distribution, so the files are cut where the ELF ends. Each
81
+ original runs in one LiteSVM and its port in another, under the same program id and with the same clock.
82
+
83
+ - **Vote accounts** are written in both: owned by the Vote program, with the node key at bytes 4..36.
84
+ - **Tips** are added to an account's lamports in both, as a searcher's transfer would add them.
85
+ - **Merkle trees** are built in the test as Jito's tooling builds them:
86
+ - leaves are `sha256(0x00 ‖ sha256(claimant ‖ amount))`;
87
+ - nodes are `sha256(0x01 ‖ lower ‖ higher)`.
88
+ - **Epochs** move by setting the clock in both.
89
+
90
+ For each transaction, the test requires the same outcome (success, or the same error down to the code). It also
91
+ requires the same lamports, owner and data for every account involved, the same events byte for byte, and the same
92
+ log lines the programs write themselves (the `WARN` lines and the not-live message).
93
+
94
+ There are 150 transactions:
95
+
96
+ - **Tip payment (26).**
97
+ - `initialize`; refused at the wrong PDA, over a tip account that already holds lamports, and a second time.
98
+ - Receivers and block builders changed, with tips paid out at commissions of 0, 7, 50 and 100%, including to one
99
+ account that is both receiver and builder.
100
+ - Refusals: the wrong old receiver or builder, a commission over 100%, a new receiver or builder that is a program,
101
+ a loader's account, a sysvar or a Config program account.
102
+ - A payout to an empty account that would stay below rent: its share goes back into tip account 0, with the
103
+ warning.
104
+ - Tip account 0 itself as the receiver; a tip account below rent.
105
+ - **Tip distribution (48).**
106
+ - The config: invalid ones (0 or 11 epochs, a commission cap over 100%, the default key), then created and updated.
107
+ - Validators' accounts: commission over the cap, not the node key, not a vote account.
108
+ - Roots: uploaded too early, by the wrong authority, replaced before any claim, refused after one.
109
+ - Claims: unsigned, the wrong amount or proof, claimed twice, over the root's total, expired; one paid by the
110
+ claimant.
111
+ - Claim records and accounts closed before and after they expire, to the wrong account, with the wrong epoch seed.
112
+ - The upload config created and changed, and an account migrated to the override authority (and not one with a
113
+ root).
114
+ - **Priority fee distribution (76).** The same, plus `transfer_priority_fee_tips`:
115
+ - 22 amounts before go-live, including exact binary ties and 1.8 × 10¹⁹ lamports, each logged as the original logs
116
+ it;
117
+ - a go-live epoch in the future, then the current one;
118
+ - a transfer into last epoch's account.
119
+
120
+ ## Cost
121
+
122
+ Compute units per transaction, mainnet original against the port, from one run of that test:
123
+
124
+ | Instruction | Jito (mainnet) | TypeSOL | |
125
+ | --- | ---: | ---: | ---: |
126
+ | tip payment `initialize` | 60,085 | 23,628 | −61% |
127
+ | `change_tip_receiver`, the receiver also the builder (both shares to one account) | 29,889 | 7,723 | −74% |
128
+ | `change_block_builder`, a 7% commission paid first | 29,911 | 7,736 | −74% |
129
+ | `change_tip_receiver`, a share kept in tip account 0 | 41,355 | 9,192 | −78% |
130
+ | tip distribution `initialize` | 7,284 | 1,946 | −73% |
131
+ | `initialize_tip_distribution_account` | 10,007 | 2,624 | −74% |
132
+ | `upload_merkle_root` | 3,943 | 977 | −75% |
133
+ | `claim` | 13,067 | 3,940 | −70% |
134
+ | `close_claim_status` | 4,302 | 1,036 | −76% |
135
+ | `close_tip_distribution_account` | 5,735 | 1,561 | −73% |
136
+ | `update_config` | 2,850 | 645 | −77% |
137
+ | `migrate_tda_merkle_root_upload_authority` | 6,467 | 1,342 | −79% |
138
+ | priority fee `claim` | 12,730 | 3,933 | −69% |
139
+ | `transfer_priority_fee_tips`, live | 6,059 | 2,014 | −67% |
140
+ | `transfer_priority_fee_tips`, not live (logs SOL) | 6,362 | 2,673 | −58% |
141
+
142
+ `claim` and the account openings vary from run to run with the PDA bump searches of the random keys the test uses,
143
+ in both programs alike.
144
+
145
+ | Binary | Jito (mainnet, ELF without the padding) | TypeSOL |
146
+ | --- | ---: | ---: |
147
+ | Tip payment | 297,848 bytes | 47,128 bytes |
148
+ | Tip distribution | 342,432 bytes | 46,848 bytes |
149
+ | Priority fee distribution | 387,440 bytes | 61,432 bytes |
150
+
151
+ ## Where they differ
152
+
153
+ - **A short vote account.** With fewer than 36 bytes of data, the original panics slicing the node key out. The port
154
+ fails with 3003 (AccountDidNotDeserialize).
155
+ - **Check order on double faults.** Anchor checks the accounts one at a time, in their order. The port checks every
156
+ account's owner, discriminator, signer and seeds first, then the constraints. A transaction that breaks one check
157
+ gets the same code. One that breaks two at once can be reported differently.
158
+ - **Other accounts passed twice.** `Dup<…>` lifts the check only for the accounts listed above, and only against
159
+ accounts read and written in place. Any other account passed twice is refused (2040) where the original would run
160
+ it: for example, a tip distribution account (a Borsh account, copied out and back) as its own claimant.
161
+ - **IDL.**
162
+ - `ValidatorCommissionBpsUpdatedEvent` and `MerkleRootUploadAuthorityUpdatedEvent`, which no instruction emits, are
163
+ not in the distribution ports' IDLs.
164
+ - The port's IDLs also list the PDA seeds and fixed addresses that the IDLs in Jito's repository leave out.
165
+ Names, discriminators, arguments, accounts and errors match.
166
+ - **Logs.** The original logs `Instruction: …` before each instruction and Anchor's error text on failure. The port
167
+ logs neither; its errors are TypeSOL's messages with the same codes. The programs' own lines are the same.
@@ -1,6 +1,6 @@
1
1
  # Case study: Raydium CLMM
2
2
 
3
- This page ports the core of a production concentrated-liquidity AMM: [Raydium CLMM](https://github.com/raydium-io/raydium-clmm)
3
+ This page ports a production concentrated-liquidity AMM in full: [Raydium CLMM](https://github.com/raydium-io/raydium-clmm)
4
4
  (`programs/amm` at 6d7a0f8, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
5
5
  `CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK`, and its on-chain IDL matches that commit. The port is
6
6
  [`examples/raydium-clmm/`](https://github.com/typesol/typesol/blob/main/examples/raydium-clmm). As with
@@ -8,12 +8,25 @@ This page ports the core of a production concentrated-liquidity AMM: [Raydium CL
8
8
 
9
9
  ## What is ported
10
10
 
11
- The port covers 8 of the original's 37 instructions, the ones a pool lives on:
12
-
13
- - `create_amm_config` and `create_pool`;
14
- - `open_position_with_token22_nft`, `increase_liquidity_v2` and `decrease_liquidity_v2`;
15
- - `swap_v2`;
16
- - `collect_protocol_fee` and `collect_fund_fee`.
11
+ All 37 of the original's instructions:
12
+
13
+ - **Pools.** `create_pool`, `create_customizable_pool` and `create_customizable_pool_v2`, which choose the fee mode,
14
+ a dynamic fee and a seed index.
15
+ - **Positions.** `open_position_with_token22_nft`, and `open_position` / `open_position_v2` with a Metaplex NFT;
16
+ `increase_liquidity` / `_v2`, `decrease_liquidity` / `_v2` and `close_position`.
17
+ - **Swaps.** `swap`, `swap_v2` and `swap_router_base_in`, a multi-hop route.
18
+ - **Limit orders.** `open_limit_order`, `increase_limit_order`, `decrease_limit_order`, `settle_limit_order` and
19
+ `close_limit_order`.
20
+ - **Rewards.** `initialize_reward`, `set_reward_params`, `update_reward_infos`, `collect_remaining_rewards` and
21
+ `transfer_reward_owner`.
22
+ - **Fees.** `collect_protocol_fee`, `collect_fund_fee` and `collect_excess_lamports`.
23
+ - **Admin.**
24
+ - `create_amm_config` and `update_amm_config`;
25
+ - `update_pool_status`;
26
+ - the operation account (`create_` / `update_operation_account`);
27
+ - the dynamic fee configs (`create_` / `update_dynamic_fee_config`);
28
+ - the support mints (`create_` / `close_support_mint_associated`);
29
+ - `close_protocol_position`.
17
30
 
18
31
  The files follow the original's modules:
19
32
 
@@ -22,37 +35,21 @@ The files follow the original's modules:
22
35
  | `math.ts` | `libraries/` | tick math, sqrt-price math, liquidity and token deltas, the swap step, in u128 and u256 |
23
36
  | `state.ts` | `states/` | every account and event, byte for byte |
24
37
  | `liquidity.ts` | `states/tick_array.rs`, `pool.rs`, `personal_position.rs`, `instructions/open_position.rs`, … | tick arrays, the tick array bitmap and its extension, rewards, positions' fees and rewards |
25
- | `swap.ts` | `instructions/swap.rs`, `states/pool_fee.rs`, `states/oracle.rs` | fee splitting, the dynamic fee, limit orders met during a swap, the bitmap searches, the oracle |
26
- | `raydium_clmm.ts` | `instructions/` | the 8 instructions |
38
+ | `swap.ts` | `instructions/swap.rs`, `states/pool_fee.rs`, `states/oracle.rs` | the swap loop over one tick array, fee splitting, the dynamic fee, limit orders met during a swap, the bitmap searches, the oracle |
39
+ | `limit_order.ts` | `states/limit_order.rs`, `instructions/limit_order/` | checks on an order, its share of what its tick filled |
40
+ | `raydium_clmm.ts` | `instructions/` | the 37 instructions |
27
41
 
28
42
  The port keeps the original's account layouts:
29
43
 
30
- - `PoolState`, `TickArrayState`, `TickArrayBitmapExtension` and `ObservationState` are zero-copy
44
+ - `PoolState`, `TickArrayState`, `TickArrayBitmapExtension`, `ObservationState` and `OperationState` are zero-copy
31
45
  `#[repr(C, packed)]` structs, which is TypeSOL's fixed layout.
32
- - `AmmConfig`, `PersonalPositionState` and `ProtocolPositionState` are Borsh accounts with only fixed-size fields, so
33
- their bytes are the same layout.
46
+ - `AmmConfig`, `PersonalPositionState`, `ProtocolPositionState`, `DynamicFeeConfig`, `SupportMintAssociated`,
47
+ `LimitOrderState` and `LimitOrderNonce` are Borsh accounts with only fixed-size fields, so their bytes are the same
48
+ layout.
34
49
 
35
50
  It also keeps the original's names, argument order and error codes, and emits the same events. The IDL it produces
36
- matches the on-chain IDL for these instructions: accounts, flags, addresses, PDA seeds, arguments and discriminators.
37
-
38
- A swap works the same on any pool the original runs, including features whose own instructions are not ported:
39
-
40
- - the dynamic fee (a pool with a `DynamicFeeInfo`: one tick spacing group at a time, the volatility accumulator, decay);
41
- - limit orders resting on a tick, filled as the price crosses it;
42
- - reward streams accruing, and fee modes that take the fee in token 0 only or token 1 only.
43
-
44
- These are not ported yet:
45
-
46
- - **The v1 instructions** (`open_position`, `open_position_v2` with a Metaplex NFT, `increase_liquidity`,
47
- `decrease_liquidity`, `swap`) and `swap_router_base_in`.
48
- - **`close_position`** and `close_protocol_position`.
49
- - **The limit order instructions**: `open_limit_order`, `increase_limit_order`, `decrease_limit_order`,
50
- `settle_limit_order` and `close_limit_order`.
51
- - **The reward instructions**: `initialize_reward`, `set_reward_params`, `update_reward_infos`,
52
- `collect_remaining_rewards` and `transfer_reward_owner`.
53
- - **The other admin instructions**: `update_amm_config`, `update_pool_status`, the operation account and dynamic-fee
54
- config instructions, `create_customizable_pool` (v1 and v2), the support-mint instructions and
55
- `collect_excess_lamports`.
51
+ matches the on-chain IDL: accounts, flags, addresses, PDA seeds, arguments and discriminators. Two details differ
52
+ (see the end of this page).
56
53
 
57
54
  ## What it needed
58
55
 
@@ -62,9 +59,9 @@ BigInt (`test/verification/fuzz-u256.test.ts`).
62
59
 
63
60
  The positions needed:
64
61
 
65
- - **Big-endian seeds.** Tick arrays are at `["tick_array", pool, start_index.to_be_bytes()]`. TypeSOL now has
66
- `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in seed lists. The IDL records the argument without the byte order,
67
- as Anchor's does.
62
+ - **Big-endian seeds.** Tick arrays are at `["tick_array", pool, start_index.to_be_bytes()]`, and dynamic fee configs
63
+ and limit orders use the same form. TypeSOL now has `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in seed
64
+ lists. The IDL records the argument without the byte order, as Anchor's does.
68
65
  - **Accounts loaded in the body.** A tick array may not exist yet, so the original takes it as an `UncheckedAccount`,
69
66
  creates it if needed, then loads it. `loadAccount` / `loadAccountMut` now take an `AccountInfo` parameter. The loaded
70
67
  struct is also its account (`.key`, `.lamports`), and it can be passed to helpers that take `Mut<T>`.
@@ -75,56 +72,81 @@ The positions needed:
75
72
 
76
73
  Tests for these are in `test/language/loaded-accounts.test.ts`.
77
74
 
78
- The swap loop needed nothing new. It is one instruction body:
75
+ The swap needed nothing new:
79
76
 
80
- - tick arrays are loaded from the remaining accounts one at a time, as the swap reaches them;
81
- - the swap state is a struct a helper returns, updated in place;
82
- - `apply_swap_amounts` is a local closure.
77
+ - **One tick array at a time.** `swapInArray` in `swap.ts` runs the original's loop over one array and returns the
78
+ new swap state, a struct the instruction stores whole into a local (`run.s = swapInArray(…)`).
79
+ - **Where the arrays come from.** Each instruction loads its tick arrays as the swap reaches them. `swap` takes the
80
+ first one as an account; `swap_v2` takes them all from the remaining accounts. `swap_router_base_in` reads every
81
+ hop's pool, config, vaults and token accounts from the remaining accounts, and moves tokens with `invoke`.
82
+ - **The router's account count.** It takes more accounts than TypeSOL's default 32, so the program declares
83
+ `MAX_ACCOUNTS = 255n`. That keeps its CPI account lists on the heap, which adds about 3% to a swap.
83
84
 
84
85
  ## How it was checked
85
86
 
86
87
  [`test/examples/raydium-clmm.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-clmm.test.ts)
87
88
  loads the binary dumped from mainnet on 2026-10-30 (sha256 in
88
89
  [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one LiteSVM
89
- and the port into another. Both use the same program id and the same clock.
90
+ and the port into another. Both use the same program id and the same clock, and both have Metaplex Token Metadata.
90
91
 
91
92
  **Setup.**
92
93
 
93
- - Mints and token accounts are made by the same token-program instructions in both.
94
- - `AmmConfig` accounts are written in both as the original lays them out, because creating one needs Raydium's admin
95
- key. The mainnet config of the USDC/CC pool is used as cloned.
96
- - Where a case needs state the ported instructions cannot make, it is written into the pool or a tick array in both
97
- VMs. This covers fee growth from earlier swaps, a reward stream, a dynamic fee, limit orders on a tick and the pool
98
- status bits.
94
+ - **The admin key.** Raydium's admin key (`GThUX1…`) gates the admin instructions. To run them, the test swaps it for
95
+ a test key in both programs:
96
+ - in the original, in the 26 places its code loads it (four 64-bit immediates each, `lddw`);
97
+ - in the port, in its source.
98
+
99
+ The other operator keys (lamport collection, limit order operator, support-mint operator) are not swapped. Each
100
+ check accepts the admin too, so those paths run as the admin.
101
+ - **Mints and token accounts** are made by the same token-program instructions in both.
102
+ - **State only swaps make.** Where a case needs it, it is written into the pool or a tick array in both VMs: fee growth
103
+ from earlier swaps, a reward stream, a dynamic fee, limit orders on a tick, the pool status bits.
99
104
 
100
105
  **Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
101
106
  code), the same lamports, owner and data for every account involved, and the same events byte for byte.
102
107
 
103
- There are 166 transactions:
104
-
105
- - **Configs and pools.** SPL Token and Token-2022 transfer-fee pools, the mainnet config, a pre-funded vault, and the
106
- refusals: mints out of order, a vault that is not the PDA, a price out of range, an open time ahead, the wrong
107
- token program, an unsupported extension, a config from anyone but the admin.
108
+ There are 300 transactions:
109
+
110
+ - **Configs and pools.**
111
+ - `create_pool` with SPL Token and Token-2022 transfer-fee mints, the mainnet config and a pre-funded vault.
112
+ - Customizable pools with each fee mode, a dynamic fee from a config, and seed indexes.
113
+ - A seeded pool used for a position, a swap and a decrease, signed with its seed index.
114
+ - Refusals: mints out of order, a vault that is not the PDA, a price out of range, an open time ahead, the wrong
115
+ token program, an unsupported extension, seed index 0, a dynamic fee without its config.
116
+ - **Admin.**
117
+ - Configs created and every `update_amm_config` flag (with the refusals).
118
+ - Operators added (sorted), added again and removed; a reward mint added and removed; more operators than fit.
119
+ - Dynamic fee configs, valid and not.
120
+ - A support mint that lets a pool take a Token-2022 mint with an extension pools refuse, then closed.
121
+ - Pool status, reward owner, a protocol position closed, lamports above rent collected.
122
+ - Each refused for anyone but the admin.
108
123
  - **Positions.**
109
124
  - Positions in range, below and above the price, in one tick array or two, and on the lowest array.
110
- - Liquidity worked out from amount_0 or amount_1, and NFTs with and without metadata.
125
+ - Liquidity worked out from amount_0 or amount_1, and NFTs as Token-2022 mints (with and without metadata) and as
126
+ Metaplex NFTs.
111
127
  - A tick shared by two positions, and a tick array whose address someone pre-funded.
112
- - A restricted-asset pool, whose position NFT account ends frozen.
113
- - Adding and removing liquidity down to an empty position: the counts go back to zero and the bitmap bits clear.
114
- - Fees owed and a reward stream paid out.
115
- - Arrays past the pool's own bitmap, on both sides, and a missing or wrong extension.
116
- - The pool status bits.
117
- - Refusals: slippage, tick order and spacing, wrong arrays, another owner's NFT.
128
+ - A restricted-asset pool, whose position NFT account ends frozen, and its NFT thawed to close it.
129
+ - Adding and removing liquidity with both instruction versions, down to an empty position (counts back to zero,
130
+ bitmap bits cleared); closing a Metaplex and a Token-2022 position.
131
+ - Fees owed and reward streams paid out; arrays past the pool's own bitmap, on both sides.
132
+ - Refusals: slippage, tick order and spacing, wrong arrays, another owner's NFT, closing with liquidity left.
118
133
  - **Swaps.**
119
- - Both directions, by input and by output, across ticks and tick arrays, to a price limit.
120
- - Fees taken in token 0 only or token 1 only, then protocol and fund fees collected.
121
- - A dynamic fee across its filter and decay periods; limit orders filled at a tick while a reward stream accrues, and
122
- orders alone on a tick filled in full (the tick leaves use, its array counts one less).
123
- - Into the bitmap extension and back, above and below the pool's own bitmap, and Token-2022 transfer-fee mints both
124
- ways.
125
- - The USDC/CC pool as cloned from mainnet: its config, vaults, oracle, extension and two tick arrays.
134
+ - `swap`, `swap_v2` and a two-hop `swap_router_base_in`; both directions, by input and by output, across ticks and
135
+ tick arrays, to a price limit.
136
+ - Fee modes, protocol and fund fees collected, a dynamic fee across its filter and decay periods.
137
+ - Limit orders filled at a tick while a reward stream accrues.
138
+ - Into the bitmap extension above and below the pool's own bitmap.
139
+ - Token-2022 transfer-fee mints, and the USDC/CC pool as cloned from mainnet (config, vaults, oracle, extension and
140
+ two tick arrays).
126
141
  - Refusals: slippage both ways, a zero amount, a limit on the wrong side, missing or wrong tick arrays, liquidity
127
142
  running out, swapped vaults, swaps disabled.
143
+ - **Limit orders.** Orders placed on a used tick, on a fresh one and in a tick array that does not exist yet, in both
144
+ directions. Then added to, partly taken back, filled by a swap, settled, closed; one taken back in full, which
145
+ clears its tick and the array's bit. Refusals: the wrong side of the price, off the spacing, a zero amount, orders
146
+ disabled, settling nothing, closing an unfilled order, someone else settling.
147
+ - **Rewards.** A stream set up (period too short, in the past, the same mint twice), brought up to date, changed by
148
+ the admin and by its authority (an extension too short, then a valid one), paid to a position, and what is left
149
+ returned after it ends.
128
150
 
129
151
  ## Cost
130
152
 
@@ -132,45 +154,62 @@ Compute units per transaction, mainnet original against the port, from one run o
132
154
 
133
155
  | Instruction | Raydium (mainnet) | TypeSOL | |
134
156
  | --- | ---: | ---: | ---: |
135
- | `create_pool` | 67,818 | 26,935 | −60% |
136
- | `open_position_with_token22_nft`, in range | 126,375 | 66,015 | −48% |
137
- | `open_position_with_token22_nft`, Token-2022 transfer fee | 117,706 | 67,592 | −43% |
138
- | `increase_liquidity_v2` | 39,759 | 15,018 | −62% |
139
- | `decrease_liquidity_v2` | 40,615 | 17,263 | −57% |
140
- | `decrease_liquidity_v2`, with a reward paid | 67,766 | 20,683 | −69% |
141
- | `swap_v2` | 49,023 | 22,504 | −54% |
142
- | `swap_v2`, across tick arrays | 55,837 | 28,161 | −50% |
143
- | `swap_v2`, dynamic fee | 58,924 | 30,585 | −48% |
144
- | `swap_v2`, through limit orders | 74,417 | 36,995 | −50% |
145
- | `swap_v2`, into the bitmap extension | 78,605 | 44,428 | −43% |
146
- | `swap_v2`, Token-2022 transfer fee | 47,742 | 23,919 | −50% |
147
- | `swap_v2`, the mainnet USDC/CC pool | 52,708 | 26,881 | −49% |
148
- | `collect_protocol_fee` | 13,626 | 2,353 | −83% |
149
-
150
- Opening a position is mostly the token programs' and the System Program's work: the NFT mint, its metadata, the
151
- associated token account and the transfers. That work costs the same in both. Pool and position creation also vary
152
- from run to run with the PDA bump searches of the random keys the test uses, in both programs alike. Refusals cost far
153
- less; a swap of nothing costs 16,665 against 1,644.
154
-
155
- On size, the port's binary is 277,784 bytes and the deployed original 1,700,160 bytes. The original also contains the
156
- 29 instructions not ported here, so the ratio overstates the gain for the same feature set.
157
+ | `create_pool` | 55,818 | 24,441 | −56% |
158
+ | `create_customizable_pool_v2` | 51,673 | 23,730 | −54% |
159
+ | `open_position_with_token22_nft`, in range | 109,875 | 63,145 | −43% |
160
+ | `open_position` (Metaplex NFT) | 121,451 | 80,854 | −33% |
161
+ | `increase_liquidity_v2` | 39,759 | 15,148 | −62% |
162
+ | `decrease_liquidity_v2` | 40,615 | 15,694 | −61% |
163
+ | `decrease_liquidity_v2`, with a reward paid | 58,766 | 20,180 | −66% |
164
+ | `close_position`, Metaplex NFT | 12,532 | 3,689 | −71% |
165
+ | `close_position`, Token-2022 NFT (its mint closed too) | 22,395 | 10,376 | −54% |
166
+ | `swap_v2` | 49,040 | 23,209 | −53% |
167
+ | `swap_v2`, across tick arrays | 55,837 | 29,048 | −48% |
168
+ | `swap_v2`, dynamic fee | 58,924 | 31,228 | −47% |
169
+ | `swap_v2`, through limit orders | 74,417 | 37,989 | −49% |
170
+ | `swap_v2`, the mainnet USDC/CC pool | 52,677 | 27,571 | −48% |
171
+ | `swap` | 51,009 | 21,592 | −58% |
172
+ | `swap_router_base_in`, two hops | 80,365 | 42,150 | −48% |
173
+ | `open_limit_order` | 35,720 | 10,781 | −70% |
174
+ | `settle_limit_order` | 15,682 | 6,496 | −59% |
175
+ | `initialize_reward` | 23,105 | 9,562 | −59% |
176
+ | `collect_protocol_fee` | 13,626 | 2,355 | −83% |
177
+ | `update_amm_config` | 3,028 | 491 | −84% |
178
+
179
+ Opening a position is mostly the token programs', the System Program's and (for a Metaplex NFT) Token Metadata's
180
+ work: the NFT mint, its metadata, the associated token account and the transfers. That work costs the same in both.
181
+ Pool and position creation also vary from run to run with the PDA bump searches of the random keys the test uses, in
182
+ both programs alike. Refusals cost far less; a swap of nothing costs 16,665 against 1,651.
183
+
184
+ On size, the port's binary is 566,280 bytes and the deployed original 1,700,160 bytes, for the same 37 instructions.
157
185
 
158
186
  ## Where they differ
159
187
 
160
188
  - **Panics.** Where the original panics (an index out of range, an overflow under `overflow-checks`), it fails with
161
- `ProgramFailedToComplete`; the port fails with a numbered error. For example, a position past the pool's own bitmap
162
- opened without the extension account: the original reads `remaining_accounts[0]` of none, the port fails with 5104.
163
- The test checks only that both fail there.
164
- - **Check order on double faults.** Anchor creates `personal_position` (its `init`) before it checks the token
165
- accounts after it; the port checks every account first and creates the position at the start of the body. A
166
- transaction breaking one check gets the same code. One that breaks two at once can be reported differently.
189
+ `ProgramFailedToComplete`; the port fails with a numbered error. Examples: a position past the pool's own bitmap
190
+ opened without the extension account (the original reads `remaining_accounts[0]` of none), more than 10 operators
191
+ (`copy_from_slice` of the wrong length). The test checks only that both fail there.
192
+ - **Check order on double faults.** Anchor creates `init` accounts (a position, an order) before it checks the accounts
193
+ after them. The port follows that order where a test showed it mattered (`create_support_mint_associated`);
194
+ elsewhere it checks every account first and creates them at the start of the body. A transaction breaking one check
195
+ gets the same code. One that breaks two at once can be reported differently.
196
+ - **Reward mints' order.** The original keeps the operation account's reward mints in a hash set's order; the port
197
+ keeps them in the order added. With two or more listed, the `OperationState` bytes differ. Only membership is ever
198
+ read, and operators are sorted the same in both.
167
199
  - **Duplicate tick arrays in a swap.** The original loads every tick array it is given before it starts, so one passed
168
200
  twice fails at once. The port loads an array when the swap reaches it. Passed twice but never reached, it does
169
201
  not fail.
202
+ - **The same pool twice in a route.** `swap_router_base_in` through one pool twice works in the original. The port
203
+ loads each hop's pool mutably and refuses a second load of one account (2040).
170
204
  - **Two limit-order fills that empty extension arrays in one swap.** Each needs the extension writable. The port loads
171
- it for each such flip, and a second load in one instruction is refused (2040). Only limit orders can empty an array
172
- during a swap, and their instructions are not ported.
173
- - **Logs.** The original's `msg!` lines in these paths (`exact_swap_internal, …`, the dynamic fee's `state.tick:…`,
174
- `collect reward index: …`) are logged the same. Error messages are TypeSOL's; codes and events are the original's.
205
+ it for each such flip, and a second load in one instruction is refused (2040).
206
+ - **IDL.**
207
+ - For the Metaplex NFTs' associated token account, the original's IDL lists the SPL Token program as a constant
208
+ seed. The port's lists the `token_program` account (fixed to that address) in `open_position`, and nothing in
209
+ `open_position_v2`.
210
+ - `CollectPersonalFeeEvent`, which no instruction emits, is not in the port's IDL.
211
+ - **Logs.** The original's `msg!` lines in these paths are logged the same: `exact_swap_internal, …`, the dynamic fee's
212
+ `state.tick:…`, `collect reward index: …`, `current block timestamp:…`, the close_position reasons. Error messages are
213
+ TypeSOL's; codes and events are the original's.
175
214
  - **Clients and big-endian seeds.** The IDL records tick array seeds as Anchor does, without the byte order, so a client
176
215
  that derives them from the IDL alone gets them wrong (with either program). Pass tick arrays explicitly.
package/docs/errors.md CHANGED
@@ -51,6 +51,9 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
51
51
  | 5115 | an optional account that was left out was used |
52
52
  | 6000+ | your error enums' members, in declaration order (imported files first), then one `RequireFailed<N>` error (code 6000 + N) per distinct `require(cond, "message")` string |
53
53
 
54
+ A member's string is its message (the IDL's `msg`); `X = ""` leaves the message out, as an Anchor variant without
55
+ `#[msg]`.
56
+
54
57
  Any of Anchor's own codes can be raised directly: `require(cond, AnchorError.RequireKeysEqViolated)` fails with 2502,
55
58
  as `require_keys_eq!` does.
56
59
 
package/docs/language.md CHANGED
@@ -71,7 +71,7 @@ The full reference. For a tour, start with the [README](../README.md).
71
71
  | `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL |
72
72
  | 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`) or another group (`p.fees.vault`; the IDL nests it too, the client flattens it to `pFeesVault`); a group may not be optional or a helper parameter. An instruction with a group checks in Anchor's order: its arguments first (102), then each account in order, a group's constraints right after the group's accounts (as a composite's `try_accounts` does), the other constraints last |
73
73
  | `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) |
74
- | `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 (`"@name:be"`: an integer's bytes most significant first, Rust's `to_be_bytes()`; the IDL records the argument, as Anchor's does, so clients that derive the address from the IDL get it wrong: pass such accounts explicitly), `"@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 |
74
+ | `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 (`"@name:be"`: an integer's bytes most significant first, Rust's `to_be_bytes()`; the IDL records the argument, as Anchor's does, so clients that derive the address from the IDL get it wrong: pass such accounts explicitly), `"@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`), or `"@acct.field.inner"` when it is in a struct field of it (Anchor `bump = config.bumps.vault`); `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 |
75
75
  | `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>` |
76
76
  | `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) |
77
77
  | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
@@ -101,7 +101,7 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
101
101
  | --- | --- |
102
102
  | `pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()>` | `export function deposit(owner: Mut<Signer>, vault: Mut<Vault>, …, amount: u64): void` |
103
103
  | `-> Result<u64>` / a struct | `: u64` / a struct: sent as return data, listed in the IDL |
104
- | `#[error_code] enum MyError { #[msg("…")] X }` | `export enum MyError { X = "…" }` (codes from 6000, in order) |
104
+ | `#[error_code] enum MyError { #[msg("…")] X }` | `export enum MyError { X = "…" }` (codes from 6000, in order; `X = ""` for a variant without `#[msg]`) |
105
105
  | `require!(c, MyError::X)`, `err!(MyError::X)` | `require(c, MyError.X)`, `require(false, MyError.X)` |
106
106
  | `require_keys_eq!(a, b)`, `err!(ErrorCode::AccountDidNotDeserialize)` (Anchor's own codes) | `require(a === b, AnchorError.RequireKeysEqViolated)` (or your own error), `require(false, AnchorError.AccountDidNotDeserialize)` |
107
107
  | `init_if_needed` + `extensions::…` on a mint | `mint.createIfNeeded(…, { metadataPointer: {…}, … })`: an existing mint is checked as Anchor checks it (2024–2039) |
package/lib/typesol.d.ts CHANGED
@@ -187,6 +187,8 @@ export declare function loadAccountMut<T>(account: RemainingAccount | AccountInf
187
187
  export interface Hash {
188
188
  readonly __hash: unique symbol;
189
189
  equals(other: Hash): boolean;
190
+ /** The order of the 32 bytes (lexicographic): -1, 0 or 1, as Rust compares `[u8; 32]`. */
191
+ compare(other: Hash): i64;
190
192
  }
191
193
 
192
194
  /** sha256 over the parts concatenated: strings (UTF-8), Pubkeys/Hashes (32 bytes), integers (LE), booleans (1 byte). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.37.0",
3
+ "version": "0.38.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",