@typesol/cli 0.35.0 → 0.37.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.
@@ -32,7 +32,11 @@ export class FunctionEmitter extends StatementEmitter {
32
32
  if (n > limit)
33
33
  this.reporter.fail(ix.node, `instructions may take at most ${limit} accounts (const MAX_ACCOUNTS = …n raises it, up to 255)`);
34
34
  head.push(` if (params->ka_num < ${n}) TS_FAIL(TS_ERR_NOT_ENOUGH_ACCOUNTS, "TypeSOL: not enough accounts");`);
35
+ // Where each account's checks start in `head` (account groups move their constraints in between, below).
36
+ const loopStart = head.length;
37
+ const startOf = new Map();
35
38
  for (const a of ix.accounts) {
39
+ startOf.set(a.name, head.length);
36
40
  const v = `a_${a.name}`;
37
41
  head.push(` TsAccount *${v} = params->ka[${a.index}];`);
38
42
  const start = head.length;
@@ -74,12 +78,16 @@ export class FunctionEmitter extends StatementEmitter {
74
78
  head.push(` uint64_t pm_${a.name}; bool pf_${a.name};`, ` TS_TRY(ts_pyth_message(${v}, &pm_${a.name}, &pf_${a.name}));`);
75
79
  if (k.kind === "switchboard")
76
80
  head.push(` TS_TRY(ts_check_switchboard(${v}, ${k.devnet}));`);
81
+ if (k.kind === "sbRandomness")
82
+ head.push(` TS_TRY(ts_check_sb_randomness(${v}, ${k.devnet}));`);
77
83
  if (k.kind === "ataProgram")
78
84
  head.push(` TS_TRY(ts_check_address(${v}, &TS_ATA_PROGRAM_ID));`);
79
85
  if (k.kind === "memoProgram")
80
86
  head.push(` TS_TRY(ts_check_address(${v}, &TS_MEMO_PROGRAM_ID));`);
81
87
  if (k.kind === "stakeProgram")
82
88
  head.push(` TS_TRY(ts_check_address(${v}, &TS_STAKE_PROGRAM_ID));`);
89
+ if (k.kind === "stakeHistory")
90
+ head.push(` TS_TRY(ts_check_address(${v}, &TS_STAKE_HISTORY_ID));`, ` if (${v}->data_len < 8) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: not the StakeHistory sysvar's data");`);
83
91
  // SlotHashes: the address, and room for its length and one entry (u64 count, then (u64 slot, hash) newest first).
84
92
  if (k.kind === "slotHashes")
85
93
  head.push(` TS_TRY(ts_check_address(${v}, &TS_SLOT_HASHES_ID));`, ` if (${v}->data_len < 48 || ts_read_le(${v}->data, 8) == 0) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: SlotHashes has no entries");`);
@@ -161,6 +169,7 @@ export class FunctionEmitter extends StatementEmitter {
161
169
  head.push(` if (${v} != NULL) {`, ...inside, ` }`);
162
170
  }
163
171
  }
172
+ const loopEnd = head.length;
164
173
  // Writable accounts must be distinct: aliasing two mutable views of one account is the classic drain.
165
174
  // The loader passes each account once and marks repeats as duplicates, which share its record (ts_deserialize),
166
175
  // so two parameters name the same account exactly when their pointers are equal.
@@ -199,6 +208,7 @@ export class FunctionEmitter extends StatementEmitter {
199
208
  // Arguments: Borsh, read sequentially (strings make later offsets dynamic). Anchor decodes them before the accounts;
200
209
  // here they come after the account types (decoding first keeps them live across the checks: larger binaries), so
201
210
  // only a transaction wrong in both ways sees a different error.
211
+ const argsStart = head.length;
202
212
  if (ix.args.length)
203
213
  head.push(` uint64_t off = ${ix.discriminator.length};`);
204
214
  const need = (bytes) => head.push(` if (params->data_len < off + ${bytes}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: instruction data too short");`);
@@ -354,9 +364,34 @@ export class FunctionEmitter extends StatementEmitter {
354
364
  }
355
365
  if (ix.args.length)
356
366
  head.push(` (void)off;`);
367
+ const argsEnd = head.length;
357
368
  this.scopes = [new Map()];
358
369
  const raw = this.rawConstraints(ix);
359
- head.push(...this.constraintChecks(ix, raw.lines));
370
+ const grouped = ix.accounts.filter((a) => a.group);
371
+ if (!grouped.length)
372
+ head.push(...this.constraintChecks(ix, raw.lines));
373
+ else {
374
+ // With account groups, Anchor's order: the arguments first, then each account in order, a group's constraints
375
+ // right after its accounts (a composite's try_accounts runs its own constraints), the others last.
376
+ const groups = [...new Set(grouped.map((a) => a.group.path[0]))];
377
+ const after = new Map();
378
+ for (const g of groups) {
379
+ const members = ix.accounts.filter((a) => a.group?.path[0] === g);
380
+ const last = members[members.length - 1];
381
+ const next = ix.accounts[ix.accounts.indexOf(last) + 1];
382
+ const at = next ? startOf.get(next.name) : loopEnd;
383
+ after.set(at, [...(after.get(at) ?? []), ...this.constraintChecks(ix, raw.lines, (a) => a.group?.path[0] === g)]);
384
+ }
385
+ const accountsPart = [];
386
+ for (let i = loopStart; i <= loopEnd; i++) {
387
+ accountsPart.push(...(after.get(i) ?? []));
388
+ if (i < loopEnd)
389
+ accountsPart.push(head[i]);
390
+ }
391
+ const rest = this.constraintChecks(ix, raw.lines, (a) => !a.group);
392
+ head.splice(loopStart, argsEnd - loopStart, ...head.slice(argsStart, argsEnd), ...accountsPart, ...head.slice(loopEnd, argsStart));
393
+ head.push(...rest);
394
+ }
360
395
  this.scopes = [new Map()];
361
396
  // Two back-to-back markers measure what one marker costs, so the profiler can subtract it.
362
397
  if (this.profile)
@@ -455,11 +490,11 @@ export class FunctionEmitter extends StatementEmitter {
455
490
  }
456
491
  return { lines, count };
457
492
  }
458
- constraintChecks(ix, raw = new Map()) {
493
+ constraintChecks(ix, raw = new Map(), only = () => true) {
459
494
  const out = [];
460
495
  // Bumps found by Seeds<…> checks, declared ahead of the (possibly optional-guarded) checks for `acct.pdaBump`.
461
496
  const bumpDecls = [];
462
- for (const a of ix.accounts) {
497
+ for (const a of ix.accounts.filter(only)) {
463
498
  const start = out.length;
464
499
  const c = a.constraints;
465
500
  const k = a.kind.kind;
@@ -572,10 +607,21 @@ export class FunctionEmitter extends StatementEmitter {
572
607
  const c = a.constraints;
573
608
  const parts = [];
574
609
  const idl = [];
575
- for (const raw of c.seeds.names) {
610
+ for (const named of c.seeds.names) {
576
611
  // "@name" refers to an account parameter (its key) or an argument (its bytes); anything else is a literal.
612
+ // "@name:be" takes an integer's bytes most significant first (Rust's `to_be_bytes()`).
613
+ const be = named.startsWith("@") && named.endsWith(":be");
614
+ const raw = be ? named.slice(0, -3) : named;
577
615
  const ref = raw.startsWith("@") ? raw.slice(1) : undefined;
578
616
  const n = ref ?? raw;
617
+ const intSeed = (place, size) => {
618
+ if (!be)
619
+ return `{(const uint8_t *)&${place}, ${size}}`;
620
+ const t = `sbe_${a.name}_${parts.length}`;
621
+ out.push(` uint8_t ${t}[${size}]; for (int i = 0; i < ${size}; i++) ${t}[i] = ((const uint8_t *)&${place})[${size - 1} - i];`);
622
+ return `{${t}, ${size}}`;
623
+ };
624
+ const notInt = () => be && this.reporter.fail(a.node, `Seeds: "${named}": only integers have a byte order`);
579
625
  // "@acct.field": a field of a struct account parameter (its data was checked in the head), Anchor's
580
626
  // `seeds = [pool.amm.as_ref()]`. The account may be this one (`seeds = [offer.id.to_le_bytes()]`).
581
627
  if (ref?.includes(".")) {
@@ -588,9 +634,13 @@ export class FunctionEmitter extends StatementEmitter {
588
634
  if (!f)
589
635
  this.reporter.fail(a.node, `Seeds: ${st.name} has no field "${field}"`);
590
636
  const t = f.type;
591
- if (t.kind === "pubkey")
637
+ if (t.kind === "int")
638
+ parts.push(intSeed(`d_${owner}->${field}`, scalarSize(t)));
639
+ else if (notInt())
640
+ return out;
641
+ else if (t.kind === "pubkey")
592
642
  parts.push(`{(const uint8_t *)&d_${owner}->${field}, 32}`);
593
- else if (t.kind === "int" || t.kind === "enum")
643
+ else if (t.kind === "enum")
594
644
  parts.push(`{(const uint8_t *)&d_${owner}->${field}, ${scalarSize(t)}}`);
595
645
  else
596
646
  this.reporter.fail(a.node, `Seeds: field "${ref}" of type ${typeName(t)} cannot be a seed (use a Pubkey, an integer or a unit enum)`);
@@ -602,22 +652,28 @@ export class FunctionEmitter extends StatementEmitter {
602
652
  if (ref && !acct && !arg)
603
653
  this.reporter.fail(a.node, `Seeds: "@${ref}" is neither an account parameter nor an argument`);
604
654
  if (acct) {
655
+ notInt();
605
656
  parts.push(`{(const uint8_t *)&a_${n}->key, 32}`);
606
657
  idl.push({ kind: "account", path: snakeCase(n) });
607
658
  }
608
659
  else if (arg) {
609
660
  const t = arg.type;
610
- if (t.kind === "string")
661
+ if (t.kind === "int")
662
+ parts.push(intSeed(`arg_${n}`, scalarSize(t)));
663
+ else if (notInt())
664
+ return out;
665
+ else if (t.kind === "string")
611
666
  parts.push(`{arg_${n}.ptr, arg_${n}.len}`);
612
667
  else if (t.kind === "pubkey")
613
668
  parts.push(`{(const uint8_t *)&arg_${n}, 32}`);
614
- else if (t.kind === "int" || t.kind === "enum")
669
+ else if (t.kind === "enum")
615
670
  parts.push(`{(const uint8_t *)&arg_${n}, ${scalarSize(t)}}`);
616
671
  else
617
672
  this.reporter.fail(a.node, `Seeds: argument "${n}" of type ${typeName(t)} cannot be a seed`);
618
673
  idl.push({ kind: "arg", path: snakeCase(n) });
619
674
  }
620
675
  else {
676
+ notInt();
621
677
  if (Buffer.byteLength(n, "utf8") > 32)
622
678
  this.reporter.fail(a.node, "a seed can be at most 32 bytes");
623
679
  parts.push(`{(const uint8_t *)${cString(n)}, ${Buffer.byteLength(n, "utf8")}}`);
@@ -158,7 +158,7 @@ export function emitProgram(analysis, opts = {}) {
158
158
  // Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
159
159
  if (limit > 32)
160
160
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
161
- if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_claim_mut(")))
161
+ if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?\(/.test(b)))
162
162
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
163
163
  const fallback = model.instructions.find((ix) => ix.fallback);
164
164
  const dispatched = model.instructions.filter((ix) => !ix.fallback);
@@ -83,6 +83,12 @@ export interface Local {
83
83
  decl?: ts.VariableDeclaration | ts.ParameterDeclaration;
84
84
  /** A local closure (`const f = (…) => …` reading the enclosing function's variables), expanded where it is called. */
85
85
  closure?: Closure;
86
+ /** `const t = loadAccount<T>(acct)` / `loadAccountMut`: the account it views (a `TsAccount *`), to pass to helpers. */
87
+ loaded?: {
88
+ handle: string;
89
+ struct: string;
90
+ mut: boolean;
91
+ };
86
92
  }
87
93
  /** A closure and the scopes it was declared in (its free names resolve there, wherever it is called). */
88
94
  export interface Closure {
@@ -29,6 +29,10 @@ export const isStable = (c) => /^\w+$/.test(c) || /^\(&\w+\)$/.test(c) || /^&\w+
29
29
  /** A C string literal of the UTF-8 bytes. Octal escapes (at most three digits) cannot swallow following characters. */
30
30
  export const cString = (s) => `"${[...Buffer.from(s, "utf8")].map((b) => (b >= 0x20 && b < 0x7f && b !== 0x22 && b !== 0x5c && b !== 0x3f ? String.fromCharCode(b) : `\\${b.toString(8).padStart(3, "0")}`)).join("")}"`;
31
31
  export function intLiteral(value, name) {
32
+ if (name === "u256") {
33
+ const w = [0n, 1n, 2n, 3n].map((i) => (value >> (64n * i)) & (2n ** 64n - 1n));
34
+ return `ts_u256_lit(${w.map((x) => `${x}ULL`).join(", ")})`;
35
+ }
32
36
  if (name === "i64") {
33
37
  if (value === INT_INFO.i64.min)
34
38
  return "(-9223372036854775807LL - 1)";
@@ -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
- this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d });
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
- const want = (n, kind, mut, what) => {
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, [], [
@@ -132,6 +132,8 @@ function accountEntry(ix, name, k, programAddress) {
132
132
  entry.address = "Stake11111111111111111111111111111111111111";
133
133
  if (k.kind === "slotHashes")
134
134
  entry.address = "SysvarS1otHashes111111111111111111111111111";
135
+ if (k.kind === "stakeHistory")
136
+ entry.address = "SysvarStakeHistory1111111111111111111111111";
135
137
  if (k.kind === "metadataProgram")
136
138
  entry.address = "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s";
137
139
  if (k.kind === "coreProgram")
@@ -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;
@@ -254,11 +254,20 @@ export type ParamKind = {
254
254
  /** The SlotHashes sysvar account (too large for the sysvar syscalls, so read as an account). */
255
255
  | {
256
256
  kind: "slotHashes";
257
+ }
258
+ /** The StakeHistory sysvar account. */
259
+ | {
260
+ kind: "stakeHistory";
257
261
  } | {
258
262
  kind: "metadataProgram";
259
263
  } | {
260
264
  kind: "switchboard";
261
265
  devnet: boolean;
266
+ }
267
+ /** A Switchboard On-Demand randomness account (RandomnessAccountData). */
268
+ | {
269
+ kind: "sbRandomness";
270
+ devnet: boolean;
262
271
  } | {
263
272
  kind: "tokenProgram";
264
273
  flavor: TokenProgramKind;
@@ -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,176 @@
1
+ # Case study: Raydium CLMM
2
+
3
+ This page ports the core of a production concentrated-liquidity AMM: [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
+ 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`.
17
+
18
+ The files follow the original's modules:
19
+
20
+ | File | From | What |
21
+ | --- | --- | --- |
22
+ | `math.ts` | `libraries/` | tick math, sqrt-price math, liquidity and token deltas, the swap step, in u128 and u256 |
23
+ | `state.ts` | `states/` | every account and event, byte for byte |
24
+ | `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 |
27
+
28
+ The port keeps the original's account layouts:
29
+
30
+ - `PoolState`, `TickArrayState`, `TickArrayBitmapExtension` and `ObservationState` are zero-copy
31
+ `#[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.
34
+
35
+ 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`.
56
+
57
+ ## What it needed
58
+
59
+ The math needed a 256-bit integer. `u256` is a computation-only type (locals, helpers, never stored or sent). It has
60
+ the checked operators, and `mulDiv` / `mulDivCeil` through a 512-bit product. A fuzzer checks every operator against
61
+ BigInt (`test/verification/fuzz-u256.test.ts`).
62
+
63
+ The positions needed:
64
+
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.
68
+ - **Accounts loaded in the body.** A tick array may not exist yet, so the original takes it as an `UncheckedAccount`,
69
+ creates it if needed, then loads it. `loadAccount` / `loadAccountMut` now take an `AccountInfo` parameter. The loaded
70
+ struct is also its account (`.key`, `.lamports`), and it can be passed to helpers that take `Mut<T>`.
71
+ - **One account as two parameters.** A position whose ticks are in one array passes that array twice. `Dup<…>` lets
72
+ both be loaded; a write through one is seen through the other, as in the original.
73
+ - **A seed list picked at run time**, `cond ? signer([…]) : signer([…])`. A pool signs with its seed index if it has one.
74
+ - **`mintTo` and `freezeAccount` on a token account the instruction created**, for the position NFT.
75
+
76
+ Tests for these are in `test/language/loaded-accounts.test.ts`.
77
+
78
+ The swap loop needed nothing new. It is one instruction body:
79
+
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.
83
+
84
+ ## How it was checked
85
+
86
+ [`test/examples/raydium-clmm.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-clmm.test.ts)
87
+ loads the binary dumped from mainnet on 2026-10-30 (sha256 in
88
+ [`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
+
91
+ **Setup.**
92
+
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.
99
+
100
+ **Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
101
+ code), the same lamports, owner and data for every account involved, and the same events byte for byte.
102
+
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
+ - **Positions.**
109
+ - 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.
111
+ - 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.
118
+ - **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.
126
+ - Refusals: slippage both ways, a zero amount, a limit on the wrong side, missing or wrong tick arrays, liquidity
127
+ running out, swapped vaults, swaps disabled.
128
+
129
+ ## Cost
130
+
131
+ Compute units per transaction, mainnet original against the port, from one run of that test:
132
+
133
+ | Instruction | Raydium (mainnet) | TypeSOL | |
134
+ | --- | ---: | ---: | ---: |
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
+
158
+ ## Where they differ
159
+
160
+ - **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.
167
+ - **Duplicate tick arrays in a swap.** The original loads every tick array it is given before it starts, so one passed
168
+ twice fails at once. The port loads an array when the swap reaches it. Passed twice but never reached, it does
169
+ not fail.
170
+ - **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.
175
+ - **Clients and big-endian seeds.** The IDL records tick array seeds as Anchor does, without the byte order, so a client
176
+ that derives them from the IDL alone gets them wrong (with either program). Pass tick arrays explicitly.
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) |
@@ -41,6 +41,7 @@ The full reference. For a tour, start with the [README](../README.md).
41
41
  | `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
42
42
  | Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash`; `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump; `programId()` → this program's address; `a.compare(b)` orders Pubkeys as Rust does (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
43
43
  | Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted) (mainnet program unless `SwitchboardFeed<"devnet">`) |
44
+ | Randomness | A chain has no secret randomness of its own: slot hashes and timestamps are known to, or chosen by, the block producer. `SwitchboardRandomness` (Switchboard On-Demand's RandomnessAccountData; owner, discriminator and size checked) gives verifiable randomness by commit and reveal: commit while `r.seedSlot === currentSlot() - 1n` and store `r.key` and `r.seedSlot`; settle in a later transaction after checking both, with `r.value()` (32 bytes) or `r.valueU64()`, which fail (5111) unless the value was revealed in this slot. See test/fixtures/coinflip.ts |
44
45
  | Multiple files | `import { Side, min } from "./math"` — structs, enums, constants and helpers can live in other files; only the entry file's exported functions are instructions; names are program-wide, so imports from TypeSOL files cannot be renamed; error codes number imported files first |
45
46
  | Loops | `for (let i = 0n; i < n; i++)`, `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
46
47
  | Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds` and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); no recursion. A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
@@ -50,7 +51,7 @@ The full reference. For a tour, start with the [README](../README.md).
50
51
  | Generic helpers | `function max<T extends bigint>(a: T, b: T): T` — compiled once per set of types it is called with (`max(a, b)` with u64 arguments, or `max<u128>(x, 1n)` when only literals tell); a type parameter stands for an integer, boolean, Pubkey, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: `return (a + b) as T` (`as` names a type the value already has; it never converts) |
51
52
  | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) |
52
53
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
53
- | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()` |
54
+ | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()`; `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
54
55
  | Account size | `realloc(account, newSize, payer)` on a `Mut<Struct>` — growing charges the payer the extra rent (at most 10 KiB per instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a growable `Vec` (its push / pop / clear size the account) |
55
56
  | Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferFeeInverse(mint, amountReceived)` (the fee when the recipient is to get that much: spl-token-2022's `calculate_inverse_epoch_fee`), `transferFeeBasisPoints(mint)` / `transferFeeMaximum(mint)` (this epoch's; 0 without the extension), `extensionsWithin(account, [1n, 18n, …])` (every extension is one of those types), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
56
57
  | Events through CPI | `emitCpi<Paid>({ … }, eventAuthority, self)` with `eventAuthority: EventAuthority, self: SelfProgram` parameters — Anchor `emit_cpi!`: the event rides in a self-CPI (inner instruction), not in logs; the program accepts Anchor's event instruction (2002 / 2006 otherwise) |
@@ -68,9 +69,9 @@ The full reference. For a tour, start with the [README](../README.md).
68
69
  | `Init<T>` | writable; `create(payer, seeds)` derives the PDA, verifies it, funds rent, writes the discriminator (up to 10 KiB); `create(payer, null)` creates a new keypair account that signs the transaction instead (3010 if it did not; a signer in the IDL); a third argument is Anchor's `space = …` (discriminator included, at least 8 + the struct's size) |
69
70
  | `InitIfNeeded<T>` | `const created = acct.createIfNeeded(payer, seeds)` — creates once; afterwards re-derives the PDA and checks owner, discriminator and size (Anchor `init_if_needed`); `acct.pdaBump` after create. An existing account is used as it is: check the fields you rely on |
70
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 |
71
- | 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. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
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 |
72
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) |
73
- | `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`); `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
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>` |
75
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) |
76
77
  | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
@@ -109,7 +110,9 @@ account written through `.lamports` or `loadAccountMut` is another account of th
109
110
  a close destination or `@layout borsh`): a write through either is seen through the other, so read what you need
110
111
  before writing. A remaining account
111
112
  can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
112
- 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).
113
116
 
114
117
  ## Built-ins
115
118
 
@@ -162,7 +165,9 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
162
165
  - `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
163
166
  lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
164
167
  - A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
165
- 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)]`).
166
171
  - After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
167
172
  A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
168
173
  unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is