@typesol/cli 0.36.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 +53 -0
- package/README.md +8 -1
- package/dist/compiler/analyze.d.ts +6 -0
- package/dist/compiler/analyze.js +47 -8
- package/dist/compiler/emit/calls.js +40 -6
- package/dist/compiler/emit/cpi-core.js +24 -2
- package/dist/compiler/emit/expressions.d.ts +2 -0
- package/dist/compiler/emit/expressions.js +90 -1
- package/dist/compiler/emit/function.js +31 -7
- package/dist/compiler/emit/program.js +1 -1
- package/dist/compiler/emit/shared.d.ts +6 -0
- package/dist/compiler/emit/shared.js +4 -0
- package/dist/compiler/emit/statements.js +27 -1
- package/dist/compiler/emit/token.js +8 -5
- package/dist/compiler/idl.d.ts +1 -1
- package/dist/compiler/idl.js +7 -3
- package/dist/compiler/model.d.ts +1 -1
- package/dist/compiler/model.js +3 -1
- package/docs/case-study-jito-mev.md +167 -0
- package/docs/case-study-raydium-clmm.md +215 -0
- package/docs/errors.md +3 -0
- package/docs/language.md +10 -6
- package/docs/migrate-from-anchor.md +1 -1
- package/lib/typesol.d.ts +25 -7
- package/package.json +1 -1
- package/runtime/typesol_rt.h +225 -0
|
@@ -910,6 +910,24 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
910
910
|
this.scopes.at(-1).set(name, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
|
|
911
911
|
continue;
|
|
912
912
|
}
|
|
913
|
+
// One of two seed lists, picked at run time: `const pool = indexed ? signer([…, index, bump]) : signer([…, bump])`.
|
|
914
|
+
// Both lists are built (seeds have no side effects to skip), then one is chosen.
|
|
915
|
+
if (init &&
|
|
916
|
+
ts.isConditionalExpression(init) &&
|
|
917
|
+
[init.whenTrue, init.whenFalse].every((b) => ts.isCallExpression(b) && this.exportName(b.expression) === "signer")) {
|
|
918
|
+
if (mutable)
|
|
919
|
+
this.fail(d, "bind seed lists with const");
|
|
920
|
+
const cond = this.expect(this.expr(init.condition, BOOL), BOOL, init.condition);
|
|
921
|
+
const flag = this.tmp("which");
|
|
922
|
+
this.line(`bool ${flag} = ${cond.c};`);
|
|
923
|
+
const a = this.signerSeedsArg(init.whenTrue);
|
|
924
|
+
const b = this.signerSeedsArg(init.whenFalse);
|
|
925
|
+
this.line(`const SolSignerSeed *${c} = ${flag} ? ${a.name} : ${b.name};`);
|
|
926
|
+
this.line(`int ${c}__n = ${flag} ? ${a.count} : ${b.count};`);
|
|
927
|
+
this.line(`(void)${c}; (void)${c}__n;`);
|
|
928
|
+
this.scopes.at(-1).set(name, { c, type: { kind: "signerSeeds" }, mutable: false });
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
913
931
|
// A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
|
|
914
932
|
if (fn === "signer") {
|
|
915
933
|
if (mutable)
|
|
@@ -936,7 +954,15 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
936
954
|
this.fail(d, "bind loaded accounts with const");
|
|
937
955
|
const t = fn === "loadForeign" ? this.loadForeign(init) : this.loadAccount(init, fn === "loadAccountMut");
|
|
938
956
|
this.line(`${valueC(t.type)}${c} = ${t.c};`);
|
|
939
|
-
|
|
957
|
+
// The account it views, kept to pass the struct on to a helper that takes Account<T> / Mut<T>.
|
|
958
|
+
let loaded;
|
|
959
|
+
if (fn !== "loadForeign" && t.type.kind === "structRef") {
|
|
960
|
+
// The view is `((TSS_T *)(h->data + 8))` over a `TsAccount *h` that stays in scope with it.
|
|
961
|
+
const h = /^\(\(TSS_\w+ \*\)\((\w+)->data \+ 8\)\)$/.exec(t.c)?.[1];
|
|
962
|
+
if (h)
|
|
963
|
+
loaded = { handle: h, struct: t.type.struct, mut: fn === "loadAccountMut" };
|
|
964
|
+
}
|
|
965
|
+
this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d, loaded });
|
|
940
966
|
continue;
|
|
941
967
|
}
|
|
942
968
|
// A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
|
|
@@ -7,10 +7,13 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
7
7
|
tokenOp(node, program, method) {
|
|
8
8
|
const a = node.arguments;
|
|
9
9
|
const p = `a_${program.name}`;
|
|
10
|
-
|
|
10
|
+
// `created`: also a Mut<AccountInfo> token account this instruction created (an associated token account).
|
|
11
|
+
const want = (n, kind, mut, what, created = false) => {
|
|
11
12
|
const acct = this.accountParam(n, what);
|
|
13
|
+
if (created && acct.kind.kind === "info" && isWritable(acct.kind))
|
|
14
|
+
return acct;
|
|
12
15
|
if (acct.kind.kind !== kind || (mut && !acct.kind.mut))
|
|
13
|
-
this.fail(n, `${what} must be a ${mut ? "Mut<" : ""}${kind === "token" ? "TokenAccount" : "Mint"}${mut ? ">" : ""}`);
|
|
16
|
+
this.fail(n, `${what} must be a ${mut ? "Mut<" : ""}${kind === "token" ? "TokenAccount" : "Mint"}${mut ? ">" : ""}${created ? ", or a Mut<AccountInfo> token account this instruction created" : ""}`);
|
|
14
17
|
return acct;
|
|
15
18
|
};
|
|
16
19
|
const arity = (fixed) => {
|
|
@@ -46,7 +49,7 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
46
49
|
const mint = this.accountParam(a[0], "the mint");
|
|
47
50
|
if (!isWritable(mint.kind) || (mint.kind.kind !== "mint" && mint.kind.kind !== "signer" && mint.kind.kind !== "info"))
|
|
48
51
|
this.fail(a[0], "the mint must be a Mut<Mint>, or a Mut<Signer> / Mut<AccountInfo> mint this instruction created");
|
|
49
|
-
const to = want(a[1], "token", true, "the destination");
|
|
52
|
+
const to = want(a[1], "token", true, "the destination", true);
|
|
50
53
|
const auth = this.accountParam(a[2], "the mint authority");
|
|
51
54
|
const amt = amount(a[3]);
|
|
52
55
|
const s = this.signerSeeds(a[4], auth, a[2]);
|
|
@@ -494,7 +497,7 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
494
497
|
case "mintToChecked": {
|
|
495
498
|
arity(4);
|
|
496
499
|
const mint = want(a[0], "mint", true, "the mint");
|
|
497
|
-
const to = want(a[1], "token", true, "the destination");
|
|
500
|
+
const to = want(a[1], "token", true, "the destination", true);
|
|
498
501
|
const auth = this.accountParam(a[2], "the mint authority");
|
|
499
502
|
const s = this.signerSeeds(a[4], auth, a[2]);
|
|
500
503
|
simple(14, [value(a[3], U64), decimals(mint)], [
|
|
@@ -542,7 +545,7 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
542
545
|
case "freezeAccount":
|
|
543
546
|
case "thawAccount": {
|
|
544
547
|
arity(3);
|
|
545
|
-
const acct = want(a[0], "token", true, "the token account");
|
|
548
|
+
const acct = want(a[0], "token", true, "the token account", true);
|
|
546
549
|
const mint = this.accountParam(a[1], "the mint");
|
|
547
550
|
const auth = this.accountParam(a[2], "the freeze authority");
|
|
548
551
|
simple(method === "freezeAccount" ? 10 : 11, [], [
|
package/dist/compiler/idl.d.ts
CHANGED
package/dist/compiler/idl.js
CHANGED
|
@@ -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) => ({
|
|
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,
|
package/dist/compiler/model.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type ts from "typescript";
|
|
2
|
-
export type IntName = "u8" | "u16" | "u32" | "u64" | "u128" | "i8" | "i16" | "i32" | "i64" | "i128";
|
|
2
|
+
export type IntName = "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128";
|
|
3
3
|
export declare const INT_NAMES: readonly IntName[];
|
|
4
4
|
export declare const INT_INFO: Record<IntName, {
|
|
5
5
|
bytes: number;
|
package/dist/compiler/model.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
export const INT_NAMES = ["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128"];
|
|
1
|
+
export const INT_NAMES = ["u8", "u16", "u32", "u64", "u128", "u256", "i8", "i16", "i32", "i64", "i128"];
|
|
2
2
|
export const INT_INFO = {
|
|
3
3
|
u8: { bytes: 1, signed: false, c: "uint8_t", min: 0n, max: 0xffn },
|
|
4
4
|
u16: { bytes: 2, signed: false, c: "uint16_t", min: 0n, max: 0xffffn },
|
|
5
5
|
u32: { bytes: 4, signed: false, c: "uint32_t", min: 0n, max: 0xffffffffn },
|
|
6
6
|
u64: { bytes: 8, signed: false, c: "uint64_t", min: 0n, max: 2n ** 64n - 1n },
|
|
7
7
|
u128: { bytes: 16, signed: false, c: "unsigned __int128", min: 0n, max: 2n ** 128n - 1n },
|
|
8
|
+
/** A computation type (locals, helpers): no C integer, runtime limbs (TsU256); never stored, sent or returned. */
|
|
9
|
+
u256: { bytes: 32, signed: false, c: "TsU256", min: 0n, max: 2n ** 256n - 1n },
|
|
8
10
|
i8: { bytes: 1, signed: true, c: "int8_t", min: -(2n ** 7n), max: 2n ** 7n - 1n },
|
|
9
11
|
i16: { bytes: 2, signed: true, c: "int16_t", min: -(2n ** 15n), max: 2n ** 15n - 1n },
|
|
10
12
|
i32: { bytes: 4, signed: true, c: "int32_t", min: -(2n ** 31n), max: 2n ** 31n - 1n },
|
|
@@ -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.
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# Case study: Raydium CLMM
|
|
2
|
+
|
|
3
|
+
This page ports a production concentrated-liquidity AMM in full: [Raydium CLMM](https://github.com/raydium-io/raydium-clmm)
|
|
4
|
+
(`programs/amm` at 6d7a0f8, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
|
|
5
|
+
`CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK`, and its on-chain IDL matches that commit. The port is
|
|
6
|
+
[`examples/raydium-clmm/`](https://github.com/typesol/typesol/blob/main/examples/raydium-clmm). As with
|
|
7
|
+
[Raydium CP-Swap](case-study-raydium-cp-swap.md), it is checked against the binary that runs on mainnet, not a rebuild.
|
|
8
|
+
|
|
9
|
+
## What is ported
|
|
10
|
+
|
|
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`.
|
|
30
|
+
|
|
31
|
+
The files follow the original's modules:
|
|
32
|
+
|
|
33
|
+
| File | From | What |
|
|
34
|
+
| --- | --- | --- |
|
|
35
|
+
| `math.ts` | `libraries/` | tick math, sqrt-price math, liquidity and token deltas, the swap step, in u128 and u256 |
|
|
36
|
+
| `state.ts` | `states/` | every account and event, byte for byte |
|
|
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 |
|
|
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 |
|
|
41
|
+
|
|
42
|
+
The port keeps the original's account layouts:
|
|
43
|
+
|
|
44
|
+
- `PoolState`, `TickArrayState`, `TickArrayBitmapExtension`, `ObservationState` and `OperationState` are zero-copy
|
|
45
|
+
`#[repr(C, packed)]` structs, which is TypeSOL's fixed 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.
|
|
49
|
+
|
|
50
|
+
It also keeps the original's names, argument order and error codes, and emits the same events. The IDL it produces
|
|
51
|
+
matches the on-chain IDL: accounts, flags, addresses, PDA seeds, arguments and discriminators. Two details differ
|
|
52
|
+
(see the end of this page).
|
|
53
|
+
|
|
54
|
+
## What it needed
|
|
55
|
+
|
|
56
|
+
The math needed a 256-bit integer. `u256` is a computation-only type (locals, helpers, never stored or sent). It has
|
|
57
|
+
the checked operators, and `mulDiv` / `mulDivCeil` through a 512-bit product. A fuzzer checks every operator against
|
|
58
|
+
BigInt (`test/verification/fuzz-u256.test.ts`).
|
|
59
|
+
|
|
60
|
+
The positions needed:
|
|
61
|
+
|
|
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.
|
|
65
|
+
- **Accounts loaded in the body.** A tick array may not exist yet, so the original takes it as an `UncheckedAccount`,
|
|
66
|
+
creates it if needed, then loads it. `loadAccount` / `loadAccountMut` now take an `AccountInfo` parameter. The loaded
|
|
67
|
+
struct is also its account (`.key`, `.lamports`), and it can be passed to helpers that take `Mut<T>`.
|
|
68
|
+
- **One account as two parameters.** A position whose ticks are in one array passes that array twice. `Dup<…>` lets
|
|
69
|
+
both be loaded; a write through one is seen through the other, as in the original.
|
|
70
|
+
- **A seed list picked at run time**, `cond ? signer([…]) : signer([…])`. A pool signs with its seed index if it has one.
|
|
71
|
+
- **`mintTo` and `freezeAccount` on a token account the instruction created**, for the position NFT.
|
|
72
|
+
|
|
73
|
+
Tests for these are in `test/language/loaded-accounts.test.ts`.
|
|
74
|
+
|
|
75
|
+
The swap needed nothing new:
|
|
76
|
+
|
|
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.
|
|
84
|
+
|
|
85
|
+
## How it was checked
|
|
86
|
+
|
|
87
|
+
[`test/examples/raydium-clmm.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-clmm.test.ts)
|
|
88
|
+
loads the binary dumped from mainnet on 2026-10-30 (sha256 in
|
|
89
|
+
[`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one LiteSVM
|
|
90
|
+
and the port into another. Both use the same program id and the same clock, and both have Metaplex Token Metadata.
|
|
91
|
+
|
|
92
|
+
**Setup.**
|
|
93
|
+
|
|
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.
|
|
104
|
+
|
|
105
|
+
**Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
|
|
106
|
+
code), the same lamports, owner and data for every account involved, and the same events byte for byte.
|
|
107
|
+
|
|
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.
|
|
123
|
+
- **Positions.**
|
|
124
|
+
- Positions in range, below and above the price, in one tick array or two, and on the lowest array.
|
|
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.
|
|
127
|
+
- A tick shared by two positions, and a tick array whose address someone pre-funded.
|
|
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.
|
|
133
|
+
- **Swaps.**
|
|
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).
|
|
141
|
+
- Refusals: slippage both ways, a zero amount, a limit on the wrong side, missing or wrong tick arrays, liquidity
|
|
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.
|
|
150
|
+
|
|
151
|
+
## Cost
|
|
152
|
+
|
|
153
|
+
Compute units per transaction, mainnet original against the port, from one run of that test:
|
|
154
|
+
|
|
155
|
+
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
156
|
+
| --- | ---: | ---: | ---: |
|
|
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.
|
|
185
|
+
|
|
186
|
+
## Where they differ
|
|
187
|
+
|
|
188
|
+
- **Panics.** Where the original panics (an index out of range, an overflow under `overflow-checks`), it fails with
|
|
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.
|
|
199
|
+
- **Duplicate tick arrays in a swap.** The original loads every tick array it is given before it starts, so one passed
|
|
200
|
+
twice fails at once. The port loads an array when the swap reaches it. Passed twice but never reached, it does
|
|
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).
|
|
204
|
+
- **Two limit-order fills that empty extension arrays in one swap.** Each needs the extension writable. The port loads
|
|
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.
|
|
214
|
+
- **Clients and big-endian seeds.** The IDL records tick array seeds as Anchor does, without the byte order, so a client
|
|
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
|
@@ -8,8 +8,8 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| Instruction | an exported function returning `void`, one integer / boolean / `Pubkey`, a `string` (a Borsh String), or a fixed-size struct (sent as return data, at most 1024 bytes; `returns` in the IDL, and the generated client decodes it) |
|
|
10
10
|
| Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
|
|
11
|
-
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits) |
|
|
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)` |
|
|
11
|
+
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
|
|
12
|
+
| Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-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
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) |
|
|
@@ -29,7 +29,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
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
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 |
|
|
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
|
+
| Remaining accounts | `remainingAccounts()` — `.length`, `.get(i)` → `key`, `owner`, `lamports` (writes check writability), `isSigner`, `isWritable`; `loadAccount<T>` / `loadAccountMut<T>` give checked struct views (also of an `AccountInfo` parameter, Anchor's `AccountLoader::try_from` on an `UncheckedAccount`; the view is also its account: `.key`, `.lamports`, and it passes to a helper taking `Account<T>` / `Mut<T>`); 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) |
|
|
33
33
|
| Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
|
|
34
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 |
|
|
35
35
|
| Other programs' accounts | `const pool = loadForeign<Pool>(account, AMM_PROGRAM)` — owner, `account:Pool` discriminator and size checked (3007 / 3002 / 3003); `readData<u64>(account, offset)` for raw little-endian reads (bounds-checked, 3003) |
|
|
@@ -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, `"@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) |
|
|
@@ -110,7 +110,9 @@ account written through `.lamports` or `loadAccountMut` is another account of th
|
|
|
110
110
|
a close destination or `@layout borsh`): a write through either is seen through the other, so read what you need
|
|
111
111
|
before writing. A remaining account
|
|
112
112
|
can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
|
|
113
|
-
with `i == j`) is refused with 2040 too, since the two views would alias.
|
|
113
|
+
with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
|
|
114
|
+
`AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
|
|
115
|
+
of a position, as Raydium CLMM's tick arrays).
|
|
114
116
|
|
|
115
117
|
## Built-ins
|
|
116
118
|
|
|
@@ -163,7 +165,9 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
|
|
|
163
165
|
- `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
|
|
164
166
|
lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
|
|
165
167
|
- A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
|
|
166
|
-
wherever signerSeeds go.
|
|
168
|
+
wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
|
|
169
|
+
signer([…, bump])`.
|
|
170
|
+
- `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
|
|
167
171
|
- After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
|
|
168
172
|
A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
|
|
169
173
|
unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
|
|
@@ -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) |
|