@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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,47 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.37.0 — 2026-10-31
10
+
11
+ Raydium CLMM ported and checked against the mainnet binary, with what it needed: `u256`, big-endian seeds,
12
+ accounts loaded in the body and seed lists picked at run time. Programs that use none of these compile to the same
13
+ binaries as in 0.36.0.
14
+
15
+ - Examples: examples/raydium-clmm, a port of Raydium CLMM's pools, positions and swaps: `create_amm_config`,
16
+ `create_pool`, `open_position_with_token22_nft`, `increase_liquidity_v2`, `decrease_liquidity_v2`, `swap_v2`,
17
+ `collect_protocol_fee` and `collect_fund_fee`, with its math in u256 and u128 and its account layouts byte for byte.
18
+ Swaps work on any pool the original runs (dynamic fees, limit orders filled at a tick, fee modes, rewards, the
19
+ tick array bitmap extension, Token-2022 transfer fees). Checked against the mainnet binary
20
+ (test/programs/raydium_clmm.so) on 166 transactions, including a pool cloned from mainnet: the same outcomes,
21
+ account bytes and events, with 43–83% fewer compute units. See docs/case-study-raydium-clmm.md.
22
+ - New: big-endian integer seeds, Rust's `to_be_bytes()`: `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in a seed
23
+ list. The IDL records the argument, as Anchor's does.
24
+ - New: `loadAccount<T>` / `loadAccountMut<T>` take an `AccountInfo` parameter too (Anchor's `AccountLoader::try_from` on
25
+ an `UncheckedAccount`, for accounts an instruction may create first); a second `loadAccountMut` of one parameter is
26
+ refused (2040), two `Dup<…>` parameters that are one account may each be loaded. A loaded struct is also its account
27
+ (`.key`, `.lamports`) and passes to helpers taking `Account<T>` / `Mut<T>`.
28
+ - New: one of two seed lists picked at run time, `const s = cond ? signer([…]) : signer([…])`.
29
+ - New: `mintTo` and `freezeAccount` take a `Mut<AccountInfo>` token account the instruction created (an associated
30
+ token account made with `ata.create`).
31
+ - New: `u256`, a 256-bit unsigned integer for computation (locals, helpers; never stored, sent or returned), with the
32
+ checked operators, comparisons, casts to and from it, and `mulDiv` / `mulDivCeil` through a 512-bit product. The
33
+ runtime works on 32-bit limbs with 64-bit products and divides with Knuth's algorithm D; a fuzzer checks every
34
+ operator against BigInt.
35
+
36
+ ## 0.36.0 — 2026-10-30
37
+
38
+ Verifiable randomness from Switchboard, Anchor's check order for instructions with account groups, and the
39
+ StakeHistory sysvar. Programs without account groups compile to the same binaries as in 0.35.0.
40
+
41
+ - New: `StakeHistorySysvar`, the StakeHistory sysvar read as an account: `count`, `latestEpoch`, `has(epoch)`,
42
+ `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)`.
43
+ - Changed: an instruction with an account group checks in Anchor's order: the arguments first, then the accounts in
44
+ order with each group's constraints right after its accounts, then the other constraints. A transaction failing
45
+ several checks gets Anchor's code. Instructions without groups are unchanged (decoding the arguments first would make
46
+ every binary larger).
47
+ - New: `SwitchboardRandomness`, Switchboard On-Demand's verifiable randomness (commit and reveal): `seedSlot`,
48
+ `revealSlot`, `value()` and `valueU64()`, which fail (5111) unless revealed in this slot, as `get_value` does.
49
+
9
50
  ## 0.35.0 — 2026-10-30
10
51
 
11
52
  Token Metadata's Burn and the EpochSchedule and LastRestartSlot sysvars. Existing programs compile to the same binaries
package/README.md CHANGED
@@ -178,7 +178,10 @@ starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-
178
178
  program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
179
179
  checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units), and
180
180
  [docs/case-study-raydium-cp-swap.md](docs/case-study-raydium-cp-swap.md) does the same for Raydium CP-Swap's swaps and liquidity
181
- (pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
181
+ (pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units), and
182
+ [docs/case-study-raydium-clmm.md](docs/case-study-raydium-clmm.md) for Raydium CLMM's pools, positions and swaps
183
+ (dynamic fees, limit orders and the tick array bitmap extension included: the same on 166 transactions; 43–83% fewer
184
+ compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
182
185
  mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
183
186
 
184
187
  ## How it works
@@ -210,7 +213,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
210
213
  | **Control flow** | `if`, `for`, `for … of`, `while`, `switch` (with narrowing on data enums), ternaries, `??`, destructuring, helper functions (returning structs too, arrow functions, closures, function arguments, generics), list callbacks (`some`, `find`, `reduce`, …) across multiple files |
211
214
  | **CPIs** | System, SPL Token, Token-2022 (including extension reads, metadata and token groups), ATA, Memo, Stake, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing (one or several PDAs per call), return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
212
215
  | **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
213
- | **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard |
216
+ | **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard feeds and verifiable randomness |
214
217
  | **Interfaces** | custom discriminators (`@discriminator`), so a TypeSOL program can be a Token-2022 transfer hook, with extra accounts (ExtraAccountMetaList) |
215
218
 
216
219
  The full reference, with every type, check and built-in, is in [docs/language.md](docs/language.md).
@@ -329,6 +332,7 @@ Details are in [docs/testing.md](docs/testing.md).
329
332
  | [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
330
333
  | [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
331
334
  | [`raydium-cp-swap/`](examples/raydium-cp-swap) | Raydium CP-Swap's trading core: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle |
335
+ | [`raydium-clmm/`](examples/raydium-clmm) | Raydium CLMM: concentrated-liquidity positions as Token-2022 NFTs, swaps across tick arrays, u256 math, rewards, dynamic fees |
332
336
  | [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
333
337
 
334
338
  ## Status
@@ -97,7 +97,9 @@ const TYPE_EXPORTS = new Set([
97
97
  "MemoProgram",
98
98
  "StakeProgram",
99
99
  "SlotHashesSysvar",
100
+ "StakeHistorySysvar",
100
101
  "SwitchboardFeed",
102
+ "SwitchboardRandomness",
101
103
  "HasOne",
102
104
  "TokenOf",
103
105
  "MintOf",
@@ -468,6 +470,11 @@ export function analyze(entry, files) {
468
470
  });
469
471
  }
470
472
  const structs = analyzeStructs(interfaces, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs);
473
+ // u256 is a computation type: nothing stores, sends or returns it (the IDL has no 256-bit integer).
474
+ for (const s of structs.values())
475
+ for (const f of s.fields)
476
+ if (hasU256(f.type))
477
+ reporter.error(s.node ?? interfaces[0].decl, `${s.name}.${f.name}: u256 is for computation; store a u128 (or two u128s)`);
471
478
  const checker = program.getTypeChecker();
472
479
  // Local `const f = (…) => …` in any function body (and in those local functions): lifted to helpers.
473
480
  const locals = [];
@@ -668,6 +675,11 @@ export function analyze(entry, files) {
668
675
  reporter.error(fn.node.name ?? fn.node, "a program has at most one @fallback");
669
676
  ix.fallback = true;
670
677
  }
678
+ for (const a of ix.args)
679
+ if (hasU256(a.type))
680
+ reporter.error(a.node, `${a.name}: u256 is for computation; take a u128 (or two) and convert with u256(…)`);
681
+ if (ix.returns && hasU256(ix.returns))
682
+ reporter.error(fn.node.type ?? fn.node, "u256 is for computation; return a u128 (or a struct of them)");
671
683
  instructions.push(ix);
672
684
  for (const a of ix.args)
673
685
  collectStructs(a.type, structs, dataEnums, argStructs);
@@ -1485,6 +1497,15 @@ function checkRecursion(sources, decls, checker, reporter) {
1485
1497
  for (const name of byName.keys())
1486
1498
  walk(name, []);
1487
1499
  }
1500
+ /** Whether a stored, sent or returned type contains a u256. */
1501
+ function hasU256(t) {
1502
+ if (!t || typeof t !== "object")
1503
+ return false;
1504
+ const x = t;
1505
+ if (x.kind === "int")
1506
+ return x.name === "u256";
1507
+ return ["elem", "inner", "array"].some((k) => hasU256(x[k]));
1508
+ }
1488
1509
  /** TypeSOL types an account parameter can have (with the constraint wrappers around them). */
1489
1510
  const ACCOUNT_TYPES = new Set([
1490
1511
  "Signer",
@@ -1510,7 +1531,9 @@ const ACCOUNT_TYPES = new Set([
1510
1531
  "MemoProgram",
1511
1532
  "StakeProgram",
1512
1533
  "SlotHashesSysvar",
1534
+ "StakeHistorySysvar",
1513
1535
  "SwitchboardFeed",
1536
+ "SwitchboardRandomness",
1514
1537
  "HasOne",
1515
1538
  "TokenOf",
1516
1539
  "MintOf",
@@ -1779,7 +1802,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
1779
1802
  const c = a.constraints;
1780
1803
  const refs = [
1781
1804
  ...c.hasOne.map((e) => (e.includes("=") ? e.split("=").at(-1) : (c.hasOneParams?.get(e) ?? e))),
1782
- ...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).split(".")[0]),
1805
+ ...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).replace(/:be$/, "").split(".")[0]),
1783
1806
  ...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
1784
1807
  ...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
1785
1808
  ...(c.closeTo ? [c.closeTo] : []),
@@ -2005,8 +2028,17 @@ function resolveAccountKind(node, reporter, imports, structs) {
2005
2028
  return { kind: "stakeProgram" };
2006
2029
  case "SlotHashesSysvar":
2007
2030
  return { kind: "slotHashes" };
2031
+ case "StakeHistorySysvar":
2032
+ return { kind: "stakeHistory" };
2008
2033
  case "TokenMetadataProgram":
2009
2034
  return { kind: "metadataProgram" };
2035
+ case "SwitchboardRandomness": {
2036
+ const arg = ref.typeArguments?.[0];
2037
+ const cluster = arg && ts.isLiteralTypeNode(arg) && ts.isStringLiteral(arg.literal) ? arg.literal.text : "mainnet";
2038
+ if (cluster !== "mainnet" && cluster !== "devnet")
2039
+ reporter.fail(node, 'SwitchboardRandomness<"mainnet" | "devnet">');
2040
+ return { kind: "sbRandomness", devnet: cluster === "devnet" };
2041
+ }
2010
2042
  case "SwitchboardFeed": {
2011
2043
  const arg = ref.typeArguments?.[0];
2012
2044
  const cluster = arg && ts.isLiteralTypeNode(arg) && ts.isStringLiteral(arg.literal) ? arg.literal.text : "mainnet";
@@ -165,7 +165,7 @@ export class CallEmitter extends ExpressionEmitter {
165
165
  // a * b / c with a double-width intermediate (128-bit for u64, 256-bit for u128), rounding down or up;
166
166
  // aborts if the result does not fit. All three are u64, or all u128 (literals take the others' type).
167
167
  if (args.length !== 3)
168
- this.fail(node, `${builtin}(a, b, c) takes three u64 or three u128 values`);
168
+ this.fail(node, `${builtin}(a, b, c) takes three u64, u128 or u256 values`);
169
169
  const vals = [];
170
170
  for (const a of args) {
171
171
  const mark = this.lines.length;
@@ -175,6 +175,16 @@ export class CallEmitter extends ExpressionEmitter {
175
175
  vals.push(v);
176
176
  }
177
177
  const typed = vals.find((v) => v.literal === undefined);
178
+ if (typed?.type.kind === "int" && typed.type.name === "u256") {
179
+ // u256: a 512-bit product in the runtime.
180
+ const ty = typed.type;
181
+ const [x, y, z] = vals.map((v, i) => this.expect(v.literal !== undefined ? this.literal(v.literal, ty, args[i]) : v, ty, args[i]));
182
+ const t = this.tmp("md");
183
+ this.line(`TsU256 ${t};`);
184
+ this.line(`if (ts_u256_is_zero(${z.c})) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
185
+ this.line(`if (!ts_u256_muldiv(${x.c}, ${y.c}, ${z.c}, ${builtin === "mulDivCeil"}, &${t})) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow");`);
186
+ return { c: t, type: ty };
187
+ }
178
188
  const wide = typed?.type.kind === "int" && typed.type.name === "u128";
179
189
  const ty = wide ? { kind: "int", name: "u128" } : U64;
180
190
  const [x, y, z] = vals.map((v, i) => this.expect(v.literal !== undefined ? this.literal(v.literal, ty, args[i]) : v, ty, args[i]));
@@ -529,6 +539,8 @@ export class CallEmitter extends ExpressionEmitter {
529
539
  return { c: "", type: { kind: "remaining" } };
530
540
  case "readData":
531
541
  return this.readData(node);
542
+ case "bigEndian":
543
+ this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
532
544
  case "loadAccount":
533
545
  case "loadAccountMut":
534
546
  case "loadForeign":
@@ -706,6 +718,29 @@ export class CallEmitter extends ExpressionEmitter {
706
718
  return this.ataOp(node, target, method);
707
719
  if (target?.kind.kind === "memoProgram")
708
720
  return this.memoOp(node, target, method);
721
+ if (target?.kind.kind === "stakeHistory") {
722
+ const fields = { has: 0, effective: 1, activating: 2, deactivating: 3 };
723
+ if (!(method in fields))
724
+ this.fail(callee.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
725
+ if (args.length !== 1)
726
+ this.fail(node, `${method}(epoch) takes the epoch`);
727
+ const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
728
+ const f = this.tmp("shf");
729
+ const v = this.tmp("shv");
730
+ this.line(`bool ${f};`);
731
+ this.line(`uint64_t ${v} = ts_stake_history(a_${target.name}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
732
+ return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
733
+ }
734
+ if (target?.kind.kind === "sbRandomness") {
735
+ if (method !== "value" && method !== "valueU64")
736
+ this.fail(callee.name, "SwitchboardRandomness has value() and valueU64()");
737
+ if (args.length)
738
+ this.fail(node, `${method}() takes no arguments`);
739
+ const t = this.tmp("rand");
740
+ this.line(`const uint8_t *${t};`);
741
+ this.line(`TS_TRY(ts_sb_randomness_value(a_${target.name}, &${t}));`);
742
+ return method === "value" ? { c: `((const SolPubkey *)${t})`, type: HASH } : { c: `ts_read_le(${t}, 8)`, type: U64 };
743
+ }
709
744
  if (target?.kind.kind === "stakeProgram")
710
745
  return this.stakeOp(node, target, method);
711
746
  if (target?.kind.kind === "metadataProgram")
@@ -1216,10 +1251,22 @@ export class CallEmitter extends ExpressionEmitter {
1216
1251
  if (s.layout === "borsh")
1217
1252
  this.fail(node, `${s.name} is @layout borsh: declare it as an instruction parameter (remaining accounts are read in place)`);
1218
1253
  if (node.arguments.length !== 1)
1219
- this.fail(node, "loadAccount<T>(account) takes one remaining account");
1220
- const h = this.handle(node.arguments[0]);
1221
- if (!h)
1222
- this.fail(node.arguments[0], "pass a remaining account, e.g. remainingAccounts().get(i)");
1254
+ this.fail(node, "loadAccount<T>(account) takes one remaining account or AccountInfo parameter");
1255
+ let h = this.handle(node.arguments[0]);
1256
+ // An AccountInfo parameter (Anchor: AccountLoader::try_from on an UncheckedAccount). The entry checks already
1257
+ // refuse it aliasing another writable parameter (unless Dup<…>), so only a second load of it is refused here.
1258
+ let param;
1259
+ if (!h) {
1260
+ const acct = this.accountParam(node.arguments[0], "the account");
1261
+ if (acct.kind.kind !== "info")
1262
+ this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
1263
+ if (mut && !isWritable(acct.kind))
1264
+ this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadAccountMut`);
1265
+ if (!this.ix)
1266
+ this.fail(node, `load ${acct.name} in the instruction and pass the struct to this helper as ${mut ? "Mut" : "Account"}<${s.name}>`);
1267
+ h = `a_${acct.name}`;
1268
+ param = this.ix.accounts.indexOf(acct);
1269
+ }
1223
1270
  if (this.model.events.has(s.name) && s.fields.some((f) => f.type.kind === "option" || f.type.kind === "dataEnum"))
1224
1271
  this.fail(node, `${s.name} is emitted as an event and has Option or enum fields; declare a separate event struct`);
1225
1272
  this.model.accountStructs.add(s.name);
@@ -1229,7 +1276,7 @@ export class CallEmitter extends ExpressionEmitter {
1229
1276
  this.line(l);
1230
1277
  if (mut) {
1231
1278
  this.line(`TS_TRY(ts_check_writable(${h}));`);
1232
- this.line(`TS_TRY(ts_claim_mut(params, ${h}));`);
1279
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1233
1280
  }
1234
1281
  return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: mut } };
1235
1282
  }
@@ -1454,6 +1501,16 @@ export class CallEmitter extends ExpressionEmitter {
1454
1501
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
1455
1502
  helperArg(h, p, n) {
1456
1503
  if (p.account) {
1504
+ // A struct of this program loaded with loadAccount / loadAccountMut: its account, as Account<T> / Mut<T>.
1505
+ const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
1506
+ if (l?.loaded) {
1507
+ const want = p.account;
1508
+ if (want.kind !== "account" || want.struct.name !== l.loaded.struct || want.struct.layout === "borsh" || want.struct.vec)
1509
+ this.fail(n, `${h.name}() takes ${p.name} as another kind of account; ${n.text} is a loaded ${l.loaded.struct}`);
1510
+ if (want.mut && !l.loaded.mut)
1511
+ this.fail(n, `${h.name}() takes ${p.name} as Mut<${l.loaded.struct}>: load it with loadAccountMut`);
1512
+ return l.loaded.handle;
1513
+ }
1457
1514
  const acct = this.accountParam(n, `${h.name}()'s ${p.name}`);
1458
1515
  const why = accountMismatch(acct.kind, p.account);
1459
1516
  if (why)
@@ -38,6 +38,20 @@ export class CpiCoreEmitter extends CallEmitter {
38
38
  parts.push(`{(const uint8_t *)${cString(el.text)}, ${len}}`);
39
39
  continue;
40
40
  }
41
+ // bigEndian(x): the integer's bytes most significant first (Rust's `x.to_be_bytes()`).
42
+ if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian") {
43
+ if (el.arguments.length !== 1)
44
+ this.fail(el, "bigEndian(value) takes one integer");
45
+ const v = this.expr(el.arguments[0]);
46
+ if (v.type.kind !== "int" || v.literal !== undefined)
47
+ this.fail(el, "bigEndian(value) takes a typed integer (an argument, a field or a local), not a literal");
48
+ const info = INT_INFO[v.type.name];
49
+ const t = this.tmp("seed");
50
+ this.line(`uint8_t ${t}[${info.bytes}];`);
51
+ this.line(`{ ${info.c} ${t}_v = ${v.c}; for (int ${t}_i = 0; ${t}_i < ${info.bytes}; ${t}_i++) ${t}[${t}_i] = ((const uint8_t *)&${t}_v)[${info.bytes - 1} - ${t}_i]; }`);
52
+ parts.push(`{${t}, ${info.bytes}}`);
53
+ continue;
54
+ }
41
55
  // Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
42
56
  const v = this.expr(el);
43
57
  if (v.type.kind === "pubkey" && (isStable(v.c) || (inPlace && /^\(&d_\w+(->\w+)+\)$/.test(v.c))))
@@ -86,6 +100,9 @@ export class CpiCoreEmitter extends CallEmitter {
86
100
  return { name, count: parts.length, idl };
87
101
  }
88
102
  describeSeed(el) {
103
+ // Anchor's IDL records `x.to_be_bytes()` as the argument (or field) itself, without the byte order.
104
+ if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian" && el.arguments.length === 1)
105
+ return this.describeSeed(el.arguments[0]);
89
106
  if (ts.isStringLiteral(el))
90
107
  return { kind: "const", value: [...Buffer.from(el.text, "utf8")] };
91
108
  if (ts.isBigIntLiteral(el)) {
@@ -262,6 +279,8 @@ export class CpiCoreEmitter extends CallEmitter {
262
279
  if (v.isNull)
263
280
  this.fail(node, "a bare null has no type here; pass an Option value (e.g. a local declared `const x: u64 | null = null`)");
264
281
  const typed = v.literal !== undefined ? this.literal(v.literal, U64, node) : v;
282
+ if (typed.type.kind === "int" && typed.type.name === "u256")
283
+ this.fail(node, "u256 is for computation: convert to u128 (or smaller) to send it");
265
284
  if (typed.type.kind === "pubkey") {
266
285
  put(`(${typed.c})`, "32", 32);
267
286
  }
@@ -69,6 +69,8 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
69
69
  protected binary(node: ts.BinaryExpression, hint?: ValueType): Value;
70
70
  /** Checked integer arithmetic into a fresh temporary. */
71
71
  protected arith(op: ts.BinaryOperator, left: Value, right: Value, node: ts.Node): Value;
72
+ /** u256 arithmetic through the runtime's limb routines (checked like the other integers). */
73
+ private arith256;
72
74
  protected cast(arg: ts.Expression, to: ScalarType & {
73
75
  kind: "int";
74
76
  }): Value;
@@ -234,6 +234,8 @@ export class ExpressionEmitter extends StorageEmitter {
234
234
  const typed = v.literal !== undefined ? this.literal(v.literal, hint?.kind === "int" ? hint : U64, node) : v;
235
235
  if (typed.type.kind !== "int")
236
236
  this.fail(node, "~ needs an integer");
237
+ if (typed.type.name === "u256")
238
+ return { c: `ts_u256_bit(${typed.c}, ts_u256_lit(~0ULL, ~0ULL, ~0ULL, ~0ULL), 2)`, type: typed.type };
237
239
  return { c: `((${INT_INFO[typed.type.name].c})~${typed.c})`, type: typed.type };
238
240
  }
239
241
  this.fail(node, "this operator is not supported");
@@ -322,6 +324,23 @@ export class ExpressionEmitter extends StorageEmitter {
322
324
  }
323
325
  this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner and isWritable, not ${field}`);
324
326
  }
327
+ // A struct loaded with loadAccount / loadAccountMut is also its account: key, lamports, dataLen, isSigner, isWritable.
328
+ if (ts.isIdentifier(node.expression)) {
329
+ const l = this.lookup(node.expression.text);
330
+ // A field of the struct by that name comes first (as before loaded structs were accounts too).
331
+ const own = l?.loaded && this.model.structs.get(l.loaded.struct)?.fields.some((f) => f.name === field);
332
+ const acct = own ? undefined : l?.loaded?.handle;
333
+ if (acct && field === "key")
334
+ return { c: `&${acct}->key`, type: PUBKEY };
335
+ if (acct && field === "lamports")
336
+ return { c: `${acct}->lamports`, type: U64 };
337
+ if (acct && field === "dataLen")
338
+ return { c: `${acct}->data_len`, type: U64 };
339
+ if (acct && field === "isSigner")
340
+ return { c: `${acct}->is_signer`, type: BOOL };
341
+ if (acct && field === "isWritable")
342
+ return { c: `${acct}->is_writable`, type: BOOL };
343
+ }
325
344
  if (this.accountAt(node))
326
345
  this.fail(node, `"${node.getText()}" is an account; use ${node.getText()}.key for its address`);
327
346
  if (this.isGroupValue(node))
@@ -373,6 +392,20 @@ export class ExpressionEmitter extends StorageEmitter {
373
392
  if (field === "tokenProgram")
374
393
  return { c: `&${v}->owner`, type: PUBKEY };
375
394
  }
395
+ if (k.kind === "sbRandomness") {
396
+ if (field === "seedSlot")
397
+ return { c: `ts_read_le(${v}->data + TS_SB_RAND_SEED_SLOT, 8)`, type: U64 };
398
+ if (field === "revealSlot")
399
+ return { c: `ts_read_le(${v}->data + TS_SB_RAND_REVEAL_SLOT, 8)`, type: U64 };
400
+ this.fail(node.name, "SwitchboardRandomness has seedSlot, revealSlot, value() and valueU64()");
401
+ }
402
+ if (k.kind === "stakeHistory") {
403
+ if (field === "count")
404
+ return { c: `ts_read_le(${v}->data, 8)`, type: U64 };
405
+ if (field === "latestEpoch")
406
+ return { c: `(${v}->data_len >= 16 && ts_read_le(${v}->data, 8) ? ts_read_le(${v}->data + 8, 8) : 0)`, type: U64 };
407
+ this.fail(node.name, "StakeHistorySysvar has count, latestEpoch, has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
408
+ }
376
409
  if (k.kind === "slotHashes") {
377
410
  // u64 count, then (u64 slot, 32-byte hash) entries, newest first; the entry check ran at entry.
378
411
  if (field === "count")
@@ -581,6 +614,9 @@ export class ExpressionEmitter extends StorageEmitter {
581
614
  /** C statement writing the decimal text of an integer into the TS_Str `out`. */
582
615
  textOfInt(name, c, out) {
583
616
  const info = INT_INFO[name];
617
+ // u256 prints as text when it fits in 128 bits (logs of larger values are refused at run time: 5100).
618
+ if (name === "u256")
619
+ return `if (!ts_u256_fits(${c}, 128)) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: u256 too large to print"); TS_TRY(ts_str_u128(ts_u256_lo128(${c}), false, &${out}));`;
584
620
  if (info.bytes === 16)
585
621
  return info.signed ? `TS_TRY(ts_str_i128(${c}, &${out}));` : `TS_TRY(ts_str_u128(${c}, false, &${out}));`;
586
622
  return info.signed ? `TS_TRY(ts_str_i64((int64_t)(${c}), &${out}));` : `TS_TRY(ts_str_u64((uint64_t)(${c}), false, &${out}));`;
@@ -863,11 +899,15 @@ export class ExpressionEmitter extends StorageEmitter {
863
899
  ? `ts_key_eq(${left.c}, ${right.c})`
864
900
  : left.type.kind === "string"
865
901
  ? `ts_str_eq(${left.c}, ${right.c})`
866
- : `(${left.c} == ${right.c})`;
902
+ : left.type.kind === "int" && left.type.name === "u256"
903
+ ? `(ts_u256_cmp(${left.c}, ${right.c}) == 0)`
904
+ : `(${left.c} == ${right.c})`;
867
905
  return { c: neg ? `(!${c})` : c, type: BOOL };
868
906
  }
869
907
  if (left.type.kind !== "int")
870
908
  this.fail(node, `${node.operatorToken.getText()} needs integer operands`);
909
+ if (isCmp && left.type.name === "u256")
910
+ return { c: `(ts_u256_cmp(${left.c}, ${right.c}) ${node.operatorToken.getText()} 0)`, type: BOOL };
871
911
  if (isCmp)
872
912
  return { c: `(${left.c} ${node.operatorToken.getText()} ${right.c})`, type: BOOL };
873
913
  return this.arith(op, left, right, node);
@@ -882,6 +922,8 @@ export class ExpressionEmitter extends StorageEmitter {
882
922
  const K = ts.SyntaxKind;
883
923
  this.line(`${ct} ${t};`);
884
924
  const overflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
925
+ if (type.name === "u256")
926
+ return this.arith256(op, left, right, node, t, overflow);
885
927
  switch (op) {
886
928
  case K.PlusToken:
887
929
  // u64 through the runtime helpers: one compare instead of a materialized carry flag on SBF.
@@ -935,6 +977,48 @@ export class ExpressionEmitter extends StorageEmitter {
935
977
  }
936
978
  return { c: t, type };
937
979
  }
980
+ /** u256 arithmetic through the runtime's limb routines (checked like the other integers). */
981
+ arith256(op, left, right, node, t, overflow) {
982
+ const K = ts.SyntaxKind;
983
+ const type = left.type;
984
+ switch (op) {
985
+ case K.PlusToken:
986
+ case K.MinusToken:
987
+ case K.AsteriskToken:
988
+ this.line(`if (ts_u256_${op === K.PlusToken ? "add" : op === K.MinusToken ? "sub" : "mul"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
989
+ break;
990
+ case K.SlashToken:
991
+ case K.PercentToken:
992
+ this.line(`if (ts_u256_is_zero(${right.c})) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
993
+ this.line(`${t} = ts_u256_divmod(${left.c}, ${right.c}, ${op === K.SlashToken});`);
994
+ break;
995
+ case K.AmpersandToken:
996
+ case K.BarToken:
997
+ case K.CaretToken:
998
+ this.line(`${t} = ts_u256_bit(${left.c}, ${right.c}, ${op === K.AmpersandToken ? 0 : op === K.BarToken ? 1 : 2});`);
999
+ break;
1000
+ case K.LessThanLessThanToken:
1001
+ case K.GreaterThanGreaterThanToken: {
1002
+ if (right.type.kind !== "int")
1003
+ this.fail(node, "shift amounts must be integers");
1004
+ if (right.type.name === "u256")
1005
+ this.fail(node, "shift by a u64 (or smaller) amount");
1006
+ const sh = this.tmp("sh");
1007
+ this.line(`if (${INT_INFO[right.type.name].signed ? `${right.c} < 0 || ` : ""}${right.c} >= 256) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range");`);
1008
+ this.line(`uint64_t ${sh} = (uint64_t)(${right.c});`);
1009
+ if (op === K.GreaterThanGreaterThanToken)
1010
+ this.line(`${t} = ts_u256_shr(${left.c}, ${sh});`);
1011
+ else {
1012
+ this.line(`${t} = ts_u256_shl(${left.c}, ${sh});`);
1013
+ this.line(`if (ts_u256_cmp(ts_u256_shr(${t}, ${sh}), ${left.c}) != 0) ${overflow};`);
1014
+ }
1015
+ break;
1016
+ }
1017
+ default:
1018
+ this.fail(node, "unsupported arithmetic operator");
1019
+ }
1020
+ return { c: t, type };
1021
+ }
938
1022
  cast(arg, to) {
939
1023
  const v = this.expr(arg);
940
1024
  if (v.literal !== undefined)
@@ -945,6 +1029,25 @@ export class ExpressionEmitter extends StorageEmitter {
945
1029
  return v;
946
1030
  const from = INT_INFO[v.type.name];
947
1031
  const target = INT_INFO[to.name];
1032
+ if (to.name === "u256") {
1033
+ // Widen: any unsigned value, or a signed one that is not negative.
1034
+ if (from.signed)
1035
+ this.line(`if (${v.c} < 0) TS_FAIL(TS_ERR_CAST, "TypeSOL: value does not fit in u256");`);
1036
+ const t = this.tmp();
1037
+ this.line(`TsU256 ${t} = ts_u256_from_u128((unsigned __int128)${v.c});`);
1038
+ return { c: t, type: to };
1039
+ }
1040
+ if (v.type.name === "u256") {
1041
+ // Narrow: the value must fit the target (checked on the limbs, then on the low 128 bits).
1042
+ const t = this.tmp();
1043
+ const lo = this.tmp("lo");
1044
+ this.line(`if (!ts_u256_fits(${v.c}, 128)) TS_FAIL(TS_ERR_CAST, "TypeSOL: value does not fit in ${to.name}");`);
1045
+ this.line(`unsigned __int128 ${lo} = ts_u256_lo128(${v.c});`);
1046
+ if (target.max < 2n ** 128n - 1n)
1047
+ this.line(`if (${lo} > ${intLiteral(target.max, "u128")}) TS_FAIL(TS_ERR_CAST, "TypeSOL: value does not fit in ${to.name}");`);
1048
+ this.line(`${target.c} ${t} = (${target.c})${lo};`);
1049
+ return { c: t, type: to };
1050
+ }
948
1051
  const conds = [];
949
1052
  if (from.min < target.min)
950
1053
  conds.push(`${v.c} < ${intLiteral(target.min, v.type.name)}`);
@@ -25,7 +25,7 @@ export declare class FunctionEmitter extends StatementEmitter {
25
25
  lines: Map<string, string[]>;
26
26
  count: number;
27
27
  };
28
- protected constraintChecks(ix: Instruction, raw?: Map<string, string[]>): string[];
28
+ protected constraintChecks(ix: Instruction, raw?: Map<string, string[]>, only?: (a: AccountParam) => boolean): string[];
29
29
  /** Ata<…>: the account's owner (2015) and address (2009) as Anchor checks them, then its mint. */
30
30
  private ataCheck;
31
31
  /** Seeds<…>: the account is the PDA of its seeds (with the stored bump, or the canonical one found here). */