@typesol/cli 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +2 -1
  3. package/dist/compiler/analyze.js +41 -1
  4. package/dist/compiler/emit/base.d.ts +40 -7
  5. package/dist/compiler/emit/base.js +33 -0
  6. package/dist/compiler/emit/borsh.d.ts +7 -0
  7. package/dist/compiler/emit/borsh.js +86 -1
  8. package/dist/compiler/emit/calls.d.ts +102 -2
  9. package/dist/compiler/emit/calls.js +663 -49
  10. package/dist/compiler/emit/cpi-core.d.ts +9 -3
  11. package/dist/compiler/emit/cpi-core.js +12 -7
  12. package/dist/compiler/emit/cpi.js +8 -14
  13. package/dist/compiler/emit/create.d.ts +3 -3
  14. package/dist/compiler/emit/create.js +33 -25
  15. package/dist/compiler/emit/expressions.js +51 -2
  16. package/dist/compiler/emit/function.js +2 -2
  17. package/dist/compiler/emit/outline.d.ts +24 -0
  18. package/dist/compiler/emit/outline.js +100 -0
  19. package/dist/compiler/emit/program.js +7 -2
  20. package/dist/compiler/emit/shared.d.ts +35 -1
  21. package/dist/compiler/emit/shared.js +9 -1
  22. package/dist/compiler/emit/statements.d.ts +31 -0
  23. package/dist/compiler/emit/statements.js +272 -14
  24. package/dist/compiler/emit/storage.d.ts +27 -1
  25. package/dist/compiler/emit/storage.js +124 -11
  26. package/dist/compiler/emit/token.d.ts +11 -8
  27. package/dist/compiler/emit/token.js +233 -104
  28. package/dist/compiler/hints.js +6 -0
  29. package/dist/compiler/model.d.ts +20 -1
  30. package/dist/compiler/model.js +5 -0
  31. package/dist/testing-stake.d.ts +216 -0
  32. package/dist/testing-stake.js +526 -0
  33. package/dist/testing.d.ts +1 -0
  34. package/dist/testing.js +1 -0
  35. package/docs/architecture.md +1 -1
  36. package/docs/case-study-spl-stake-pool.md +122 -0
  37. package/docs/errors.md +1 -1
  38. package/docs/language.md +107 -14
  39. package/docs/security-model.md +4 -0
  40. package/docs/stability.md +13 -0
  41. package/docs/test-your-program.md +47 -0
  42. package/docs/testing.md +19 -0
  43. package/lib/typesol.d.ts +241 -40
  44. package/llms-full.txt +172 -15
  45. package/llms.txt +1 -1
  46. package/package.json +1 -1
  47. package/runtime/typesol_rt.h +69 -0
package/CHANGELOG.md CHANGED
@@ -6,6 +6,98 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.42.0 — 2026-11-09
10
+
11
+ SPL Stake Pool ported in full, the native program behind most liquid staking tokens, from the tag a reproducible build
12
+ proves is the mainnet binary, and checked against that binary on 2,107 transactions and a fuzz over epochs. The
13
+ compiler gained what it needed: Borsh accounts without a discriminator, `BigVec<T>`, typed CPIs on remaining accounts
14
+ (`programAt`, `sysvarAt`, `named`), the Stake program's split, merge and minimum delegation, native account writes,
15
+ the EpochRewards sysvar, local lists and the instruction data as a list; `typesol/testing` gained epochs and staking.
16
+ Every program that uses none of the new features compiles to the same binary as in 0.41.0.
17
+
18
+ - Examples: showcase/mainnet/spl-stake-pool, a port of SPL Stake Pool (the native program at SPoo1Ku8…, all 27
19
+ instructions), from the tag a reproducible build proves is the mainnet binary (program@v2.1.0), checked against that
20
+ binary on 2,107 transactions (the original's own 221 integration tests mapped and run as differential cases, pools of
21
+ up to 20,000 validators) and a random walk over epochs with the same outcomes, log lines and account bytes; 19–80% of
22
+ the original's compute units (the stake CPIs are the same in both), 202,240 bytes against 338,912.
23
+ docs/case-study-spl-stake-pool.md.
24
+ - BigVec loops cost less an entry. A loop over a BigVec (`for … of`, the list methods, a slice) becomes a C function
25
+ of its own, given the variables it uses: inside a large function it shared SBF's registers with everything held
26
+ across it, and clang spilled its pointer and totals every step. `retain` over structs walks the elements with one
27
+ pointer. SPL Stake Pool's UpdateStakePoolBalance sum costs 16 CU an entry (was 31; the original 27) and its cleanup's
28
+ retain 5 (was 11; the original 9), so both fit the default 200,000 units wherever the original does. The heap
29
+ buffers such a loop takes on first use (an event's, an element copied for a helper) stay declared in the function
30
+ it came from, so they are taken once however many times the loop runs; a loop that formats a Pubkey moves too.
31
+ Programs without a BigVec compile to the same C.
32
+ - `panic(null, "src/lib.rs:105:19")` panics at a location without logging a message, for a native port whose panic
33
+ handler writes none; `abort()` is Rust's abort on SBF (the allocator's out-of-memory error), the runtime's `abort`
34
+ syscall: "SBF program panicked", no location.
35
+ - A ternary between accounts, `const source = ephemeral ? rest.get(5n) : reserve`: remaining accounts, locals and
36
+ `RemainingAccount` helper parameters bound to one, and `AccountInfo` parameters; only the chosen side runs, and the
37
+ result goes wherever a remaining account does (typed CPIs, `readData`, `loadRaw`, `loadBorsh`, helpers).
38
+ - Local lists on the stack: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey, isSigner, isWritable }])`,
39
+ `fixedVec([])`, `FixedArray<T, N>` locals, structs and `FixedString<N>` elements (also in `fixedArray<T, N>(fill)`),
40
+ at most 2 KiB each (a compile error naming the size); `fixedArray(…)` written inline feeds a chain, a list method or
41
+ `for … of`.
42
+ - New: `FixedVec.pushAll(items)`, a bulk append (a memcpy: about 0.01 CU a byte for 1000 bytes, against 11 for a loop
43
+ of `push`), 5104 when it does not fit. Declared on `Vec` as well so a Vec still passes for a FixedVec; calling it on
44
+ a Vec is a compile error.
45
+ - The instruction data is a list: `for … of`, the list methods, `data.slice(start, end?)` (a view; 5104 out of range,
46
+ where JS would clamp) and `InstructionBytes` helper parameters.
47
+ - `invokeInstruction` in helpers (with their `RemainingAccounts` parameter), with metas and data from local lists, a
48
+ `FixedArray`, the instruction data or a slice of it: a native port's instruction builder, metas naming accounts by
49
+ key.
50
+ - `NATIVE_ACCOUNT_WRITES` (no change in behaviour, now tested and documented): a second `loadRawMut` of one account at
51
+ the same position is allowed with the flag (2040 without), and `loadRaw` reads what `loadRawMut`, `storeBorsh` or a
52
+ BigVec push wrote, with or without it.
53
+ - New: `named(account, address)`, a Stake CPI's sysvar or stake config argument as solana_program's stake builders
54
+ and `invoke_signed` give it: the instruction names the address, the slot's account is the account info. The runtime
55
+ looks the address up among the CPI's accounts only, so a slot holding another account fails with MissingAccount, as
56
+ the original does, even when the sysvar is elsewhere in the transaction.
57
+ - New: `loadBorsh<T>(acct)` / `storeBorsh(acct, value)`, a native program's Borsh account (no discriminator; SPL Stake
58
+ Pool's `StakePool`) read into a local struct and written back from byte 0, as Rust's `try_from_slice_unchecked` and
59
+ `serialize` do: trailing bytes ignored, the bytes after a shrunk value left as they were, invalid bytes or a value
60
+ that does not fit failing with `ProgramError.BorshIoError`. Without `NATIVE_ACCOUNT_WRITES` the account written must
61
+ be writable (3006) and passed once (2040: not also another declared or remaining account), as the other writes
62
+ check. A straight-line decoder and encoder per struct, no heap
63
+ (a 611-byte `StakePool`: about 280 CU to read, 610 CU to read and write back). Programs that do not use them
64
+ compile to the same C as before.
65
+ - New: `BigVec<T>`, SPL's `big_vec` for native ports (the stake pool's validator list): the last field of a `loadRaw`
66
+ struct, sized by the account; `push`, `retain`, `slice` (`deserialize_mut_slice`), `get` / `set`, `for … of`, the list
67
+ methods and `.capacity`, with big_vec's bytes and errors (AccountDataTooSmall). Every access is bounded by the
68
+ account's room as well as the length (the capacity computed once at the load), so a length written again after the
69
+ load (writeData, another view, storeBorsh) never reaches past the account. Other programs compile to the same C.
70
+ - `typesol/testing`: epochs and staking. `warpToEpoch` / `nextEpoch` move the Clock consistently (epoch, slot, leader
71
+ schedule epoch, timestamps); `StakeCluster` keeps a cluster-like StakeHistory over one or more LiteSVMs, so warmup
72
+ and cooldown are rate-limited as on a cluster (it refuses a history with a gap or an entry for an epoch that has not
73
+ ended, when made and at each warp); `stakeActivation` ports the Stake program's activation math;
74
+ `createVoteAccount`, `createStakeAccount`, `delegateStake`, `readStakeAccount`. Checked to the lamport against the
75
+ Stake program in LiteSVM (docs/test-your-program.md#epochs-and-staking).
76
+ - New: `programAt<P>(account)`: a remaining account (or an `AccountInfo` parameter) checked to be that program (one key
77
+ compare; ProgramError.IncorrectProgramId otherwise) with P's typed methods, for `StakeProgram`, `SystemProgram`,
78
+ `TokenProgram`, `Token2022Program`, `TokenInterface`, `AssociatedTokenProgram` and `MemoProgram`; bind it, call it
79
+ inline or pass it to a helper taking that program. `sysvarAt<StakeHistorySysvar>(account)` likewise.
80
+ - Typed CPIs (System, Token / Token-2022, ATA, Memo, Stake) take remaining accounts and `AccountInfo` parameters for
81
+ any account, as native ports need; declared parameters keep their compile-time checks, remaining accounts are left to
82
+ the runtime and the called program. `returnData` takes a remaining account as the program.
83
+ - Stake program: `split`, `merge`, `getMinimumDelegation()` (fails as solana_program's `get_minimum_delegation`),
84
+ `initialize(…, lockup?)`, and the lockup custodian for `authorize` / `withdraw`. Existing calls compile to the same C.
85
+ - New (language surface: `epochRewards()` and the `EpochRewards` type in lib/typesol.d.ts): the EpochRewards sysvar
86
+ through `sol_get_epoch_rewards_sysvar`, Rust's `EpochRewards::get()`, with no account: every field
87
+ (`active`, `totalRewards`, `distributedRewards`, `totalPoints`, `numPartitions`, `parentBlockhash`,
88
+ `distributionStartingBlockHeight`). Other programs compile to the same C.
89
+ - New: a struct, data-enum or `fixedArray<T, N>(fill)` literal as a helper argument (`applyFee({ denominator: 100n,
90
+ numerator: 3n }, amount)`, nested literals, a ternary with a literal branch, helpers in other files), built as
91
+ `const fee: Fee = { … }` would be; it failed with "expected a Fee". Other programs compile to the same C.
92
+ - Fixed: an `Option<Pubkey>` (or `Option<Hash>`) in a template string or `+` was refused ("only strings, integers,
93
+ booleans and Pubkeys can be joined into text") even after `x !== null`; it joins as the base58, or `null` when
94
+ empty, as JS prints it (as Options of integers and booleans already did). Other programs compile to the same C.
95
+ - New: `export const NATIVE_ACCOUNT_WRITES = true` (opt-in, for native ports): `loadRawMut`, `storeBorsh` and BigVec
96
+ writes skip the up-front writability check (3006) and the one-claim-per-account refusal (2040) and take a plain
97
+ `AccountInfo`; the runtime reports a changed read-only account (`ReadonlyDataModified`), and an account passed twice
98
+ is two views of one buffer, as in a native program. Lamports, `loadAccountMut`, CPIs and `Mut<…>` checks unchanged;
99
+ see docs/language.md#porting-a-native-program for the trade-off. Programs without it compile to the same C.
100
+
9
101
  ## 0.41.0 — 2026-11-07
10
102
 
11
103
  TypeSOL for AI coding agents, and Raydium CP-Swap ported in full. `typesol init` writes the rules an agent needs
package/README.md CHANGED
@@ -344,7 +344,7 @@ Details are in [docs/testing.md](docs/testing.md).
344
344
  [`showcase/`](showcase) holds programs ported from Anchor and checked against the binaries deployed on mainnet (same
345
345
  outcomes, account bytes and events; [`showcase/test`](showcase/test)), and the ports of all 46
346
346
  [solana-developers/program-examples](showcase/program-examples/README.md).
347
- Case studies: [Marginfi v2](docs/case-study-marginfi.md), [Raydium AMM v4](docs/case-study-raydium-amm.md), [Raydium CLMM](docs/case-study-raydium-clmm.md),
347
+ Case studies: [Marginfi v2](docs/case-study-marginfi.md), [SPL Stake Pool](docs/case-study-spl-stake-pool.md), [Raydium AMM v4](docs/case-study-raydium-amm.md), [Raydium CLMM](docs/case-study-raydium-clmm.md),
348
348
  [Raydium CP-Swap](docs/case-study-raydium-cp-swap.md), [Jito MEV](docs/case-study-jito-mev.md),
349
349
  [coral-xyz/multisig](docs/case-study-multisig.md), [an Anchor escrow](docs/case-study-escrow.md).
350
350
 
@@ -354,6 +354,7 @@ Case studies: [Marginfi v2](docs/case-study-marginfi.md), [Raydium AMM v4](docs/
354
354
  | [`raydium-clmm/`](showcase/mainnet/raydium-clmm) | Raydium CLMM in full: concentrated-liquidity positions as NFTs, swaps and multi-hop routes across tick arrays, limit orders, rewards, dynamic fees, u256 math |
355
355
  | [`jito-mev/`](showcase/mainnet/jito-mev) | Jito's tip payment, tip distribution and priority fee distribution: tips paid out per leader, Merkle-proof claims, epochs and expiry |
356
356
  | [`marginfi/`](showcase/mainnet/marginfi) | Marginfi v2 in full, all 124 instructions: I80F48 fixed-point arithmetic, zero-copy accounts, oracles (Pyth, Switchboard, staked SOL, Scope, venue exchange rates), the risk engine, liquidation and bankruptcy, flash loans, orders, rebalances, and the Solend, Kamino, Drift and JupLend banks |
357
+ | [`spl-stake-pool/`](showcase/mainnet/spl-stake-pool) | SPL Stake Pool in full, all 27 instructions, a native program and the one behind most liquid staking tokens: pools of stake across up to 20,000 validators, SOL and stake deposits and withdrawals, rebalancing over epochs, fees and authorities, token metadata |
357
358
  | [`raydium-amm/`](showcase/mainnet/raydium-amm) | Raydium AMM v4, the original constant-product AMM and a native (non-Anchor) program, in full: pool creation, deposits and withdrawals, the v1 and v2 swaps, P&L and administration, down to its log records and panics |
358
359
  | [`multisig.ts`](showcase/mainnet/multisig/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
359
360
 
@@ -80,6 +80,9 @@ const TYPE_EXPORTS = new Set([
80
80
  "FixedArray",
81
81
  "FixedString",
82
82
  "FixedVec",
83
+ "BigVec",
84
+ "BigVecSlice",
85
+ "InstructionBytes",
83
86
  "Program",
84
87
  "UncheckedProgram",
85
88
  "CpiAccount",
@@ -122,6 +125,7 @@ const TYPE_EXPORTS = new Set([
122
125
  "ProgramData",
123
126
  "SignerSeeds",
124
127
  "SystemAccount",
128
+ "EpochRewards",
125
129
  ]);
126
130
  /** Largest fixed array a struct may declare, and largest FixedString. */
127
131
  const MAX_ARRAY_LEN = 1_000_000;
@@ -921,6 +925,7 @@ export function analyze(entry, files) {
921
925
  fstrings,
922
926
  fixedVecs,
923
927
  localVecs: new Map(),
928
+ borshNative: new Set(),
924
929
  },
925
930
  sourceFile,
926
931
  files: programFiles(program, entryPath).map((f) => f.fileName),
@@ -1182,6 +1187,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1182
1187
  }
1183
1188
  const ext = typesolName(node, imports);
1184
1189
  const targs = node.typeArguments ?? [];
1190
+ if (ext === "BigVec")
1191
+ reporter.fail(node, "BigVec<T> is only the last field of a struct (its elements run to the end of the account), not inside another type");
1185
1192
  if (ext === "FixedArray") {
1186
1193
  if (!targs[0])
1187
1194
  reporter.fail(node, "FixedArray<T, N> needs an element type");
@@ -1219,6 +1226,20 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1219
1226
  return { kind: "struct", name: node.typeName.text };
1220
1227
  reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct");
1221
1228
  };
1229
+ // `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
1230
+ // elements are the account's remaining bytes; T is a scalar or a fixed-size struct.
1231
+ const bigVecField = (m, decl) => {
1232
+ const node = m.type;
1233
+ const elemNode = node.typeArguments?.[0];
1234
+ if (!elemNode || node.typeArguments.length !== 1)
1235
+ reporter.fail(node, "BigVec<T> takes one element type: BigVec<ValidatorStakeInfo>");
1236
+ if (decl.members.at(-1) !== m)
1237
+ reporter.fail(m, `BigVec<T> must be the last field of ${decl.name.text}: its elements run to the end of the account (move it after the others)`);
1238
+ const elem = fieldType(elemNode);
1239
+ if (!isScalarField(elem) && elem.kind !== "struct")
1240
+ reporter.fail(elemNode, "BigVec elements are integers, booleans, Pubkeys, unit enums or fixed-size structs");
1241
+ return { kind: "vec", elem, big: true };
1242
+ };
1222
1243
  for (const { decl, imports: fileImports } of items) {
1223
1244
  scope = scopeFor(fileImports);
1224
1245
  imports = fileImports;
@@ -1237,7 +1258,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1237
1258
  const problem = cNameProblem(name);
1238
1259
  if (problem)
1239
1260
  reporter.fail(m.name, problem);
1240
- const type = fieldType(m.type);
1261
+ const type = typesolName(m.type, imports) === "BigVec" ? bigVecField(m, decl) : fieldType(m.type);
1241
1262
  // `/** @bytes */`: an integer the IDL describes as its bytes (Marginfi's WrappedI80F48 { value: [u8; 16] }), or a
1242
1263
  // FixedArray of them, each its bytes (Marginfi's HealthCache.prices: [[u8; 8]; 16], f64 bits).
1243
1264
  const bytesTag = ts.getJSDocTags(m).find((t) => t.tagName.text === "bytes");
@@ -1259,6 +1280,11 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1259
1280
  if (layoutTag && layoutText !== "borsh" && layoutText !== "fixed")
1260
1281
  reporter.fail(layoutTag, "@layout is borsh (Anchor's account bytes) or fixed (the default)");
1261
1282
  const growable = (f) => f.type.kind === "vec" && f.type.cap === undefined;
1283
+ const big = fields.find((f) => f.type.kind === "vec" && f.type.big);
1284
+ if (big && layoutText === "borsh")
1285
+ reporter.fail(big.node, "a @layout borsh struct cannot hold a BigVec: BigVec is read in place (loadRaw / loadRawMut) from a fixed layout");
1286
+ if (big && fields.some((f) => f !== big && growable(f)))
1287
+ reporter.fail(big.node, `${decl.name.text} has a Vec and a BigVec: only one list may run to the end of the account`);
1262
1288
  // In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
1263
1289
  // only by the account when it is written back.
1264
1290
  if (layoutText === "borsh")
@@ -1407,6 +1433,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1407
1433
  visit(s);
1408
1434
  if (s.size === undefined)
1409
1435
  reporter.fail(at, `${t.name} has a string field and cannot be nested; use FixedString<N>`);
1436
+ if (s.bigVec)
1437
+ reporter.fail(at, `${t.name} ends in a BigVec and cannot be nested: read it with loadRaw / loadRawMut`);
1410
1438
  if (s.vec)
1411
1439
  reporter.fail(at, `${t.name} has a growable Vec and can only be account data, not nested`);
1412
1440
  return s.size;
@@ -1478,6 +1506,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1478
1506
  (s.vecs ??= []).push({ name: f.name, elem: f.type.elem, elemSize });
1479
1507
  }
1480
1508
  s.vec = s.vecs?.[0];
1509
+ if (s.vec && s.fields.some((f) => f.name === s.vec.name && f.type.kind === "vec" && f.type.big))
1510
+ s.bigVec = s.vec;
1481
1511
  // The C struct holds the first Vec's length; each further one adds its own when the account is created.
1482
1512
  if (s.vecs && s.size !== undefined)
1483
1513
  s.size -= 4 * (s.vecs.length - 1);
@@ -1710,6 +1740,9 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1710
1740
  reporter.fail(p.type, "helpers take the list itself: check the Option argument is not null and pass it");
1711
1741
  if (type)
1712
1742
  return { name: p.name.text, type, node: p };
1743
+ // The instruction data (or a slice of it), read-only: a view like a Vec<u8> argument.
1744
+ if (typesolName(p.type, scope.imports) === "InstructionBytes")
1745
+ return { name: p.name.text, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, node: p };
1713
1746
  if (typesolName(p.type, scope.imports) === "SignerSeeds")
1714
1747
  return { name: p.name.text, type: { kind: "signerSeeds" }, node: p };
1715
1748
  // One of the remaining accounts (remainingAccounts().get(i)), as the instruction holds it: read with readData or
@@ -2305,6 +2338,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
2305
2338
  const s = ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) ? structs.get(t.typeName.text) : undefined;
2306
2339
  if (s && s.size === undefined)
2307
2340
  reporter.fail(t, `${s.name} has a variable-length string field and cannot be account data; use FixedString<N>`);
2341
+ if (s?.bigVec)
2342
+ reporter.fail(t, `${s.name} ends in a BigVec, which is a native program's zero-copy list: take the account as AccountInfo (or a remaining account) and read it with loadRaw<${s.name}> / loadRawMut<${s.name}>`);
2308
2343
  if (s)
2309
2344
  checkAccountMembers(s, t, reporter);
2310
2345
  return s;
@@ -2457,6 +2492,11 @@ function resolveAccountKind(node, reporter, imports, structs) {
2457
2492
  reporter.fail(t, "Mut<T> takes a struct, Signer, AccountInfo, TokenAccount or Mint");
2458
2493
  }
2459
2494
  }
2495
+ const bare = ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) ? structs.get(node.typeName.text) : undefined;
2496
+ if (bare?.bigVec)
2497
+ reporter.fail(node, `${bare.name} ends in a BigVec, so it is account data, not an argument: read it with loadRaw<${bare.name}> / loadRawMut<${bare.name}> from an AccountInfo or a remaining account`);
2498
+ if (typesolName(node, imports) === "BigVec")
2499
+ reporter.fail(node, "BigVec<T> is the last field of a native account's struct (read with loadRaw), not an argument; a list argument is a Vec<T>");
2460
2500
  reporter.fail(node, "parameter type must be an integer, boolean, Pubkey, string, or an account type (Signer, Account<T>, Mut<T>, Init<T>, AccountInfo, TokenAccount, Mint, SystemProgram, TokenProgram, Token2022Program, TokenInterface, Program<...>)");
2461
2501
  }
2462
2502
  export { isScalar };
@@ -2,7 +2,7 @@ import ts from "typescript";
2
2
  import { type Analysis, type TypeArg, type TypeScope } from "../analyze.js";
3
3
  import type { Reporter } from "../diagnostics.js";
4
4
  import { type AccountParam, type GenericHelper, type Helper, type IdlSeed, type Instruction, type ProgramModel, type ValueType } from "../model.js";
5
- import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions } from "./shared.js";
5
+ import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions, type CpiProgram } from "./shared.js";
6
6
  /**
7
7
  * State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
8
8
  * scopes, evaluation-order snapshots and account lookups.
@@ -17,6 +17,17 @@ export declare abstract class EmitterBase {
17
17
  protected lines: string[];
18
18
  /** Declarations placed at the top of the function (buffers reused by every pass through a loop). */
19
19
  protected hoisted: string[];
20
+ /**
21
+ * The hoisted declarations of heap buffers taken on first use (`T *name = NULL;`), by line: a loop moved into a
22
+ * function of its own leaves them in its caller and is given a pointer to each (see outlinedLoop), so the buffer is
23
+ * still taken once per function, not once per call of the loop's.
24
+ */
25
+ protected readonly lazyHoists: Map<string, {
26
+ name: string;
27
+ decl: (name: string) => string;
28
+ }>;
29
+ /** Loops moved into C functions of their own (see outlinedLoop), placed before this function. */
30
+ protected outlinedLoops: string[];
20
31
  protected indent: number;
21
32
  protected temp: number;
22
33
  /** Init accounts whose create() has run (top-level, in order). */
@@ -81,6 +92,8 @@ export declare abstract class EmitterBase {
81
92
  /** `file.ts:line` of a node, for messages. */
82
93
  protected location(node: ts.Node): string;
83
94
  protected tmp(prefix?: string): string;
95
+ /** Declare a heap buffer pointer at the top of the function, NULL until first use (`decl(name)` declares it). */
96
+ protected hoistLazy(name: string, decl: (name: string) => string): void;
84
97
  /**
85
98
  * JS evaluates operands left to right, but a lowered Value is a C expression read where it is used.
86
99
  * When lowering a later operand emitted statements (from line `mark` on, e.g. a pop() or a helper call),
@@ -100,6 +113,15 @@ export declare abstract class EmitterBase {
100
113
  protected probe<T>(fn: () => T): T | undefined;
101
114
  protected fail(node: ts.Node, message: string): never;
102
115
  protected exportName(node: ts.Expression): string | undefined;
116
+ /**
117
+ * `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut, storeBorsh and BigVec writes follow a native program, which
118
+ * writes data in place and leaves writability to the runtime (ReadonlyDataModified when a read-only account's data
119
+ * changed) and lets one account be viewed twice. Without it they check writability (3006) and claim the account
120
+ * once (2040) up front.
121
+ */
122
+ protected nativeAccountWrites(): boolean;
123
+ /** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
124
+ protected isEpochRewards(node: ts.Expression): boolean;
103
125
  /**
104
126
  * `acct!.field` on an optional account: the same access without `!` (using the account checks that it was passed,
105
127
  * failing with 5115 otherwise). Returns undefined for anything else.
@@ -123,6 +145,15 @@ export declare abstract class EmitterBase {
123
145
  protected abstract isRemaining(node: ts.Expression): boolean;
124
146
  protected abstract remainingBase(node: ts.Expression): string;
125
147
  protected abstract handle(node: ts.Expression): string | undefined;
148
+ protected abstract looksLikeAccountHandle(node: ts.Expression): boolean;
149
+ protected abstract isVecArgView(node: ts.Expression): boolean;
150
+ protected abstract vecArgView(node: ts.Expression): {
151
+ c: string;
152
+ type: ValueType & {
153
+ kind: "vecArg";
154
+ };
155
+ } | undefined;
156
+ protected abstract accountChoice(node: ts.ConditionalExpression): Value;
126
157
  protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
127
158
  protected abstract isTxIx(node: ts.Expression): boolean;
128
159
  protected abstract seeds(node: ts.Expression, extra: number): {
@@ -135,13 +166,13 @@ export declare abstract class EmitterBase {
135
166
  protected abstract createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
136
167
  protected abstract createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
137
168
  protected abstract systemTransfer(node: ts.CallExpression): undefined;
138
- protected abstract createAccount(node: ts.CallExpression, system: AccountParam): undefined;
169
+ protected abstract createAccount(node: ts.CallExpression, system: CpiProgram): undefined;
139
170
  protected abstract createPda(node: ts.CallExpression): Value;
140
- protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
141
- protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
142
- protected abstract ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
143
- protected abstract memoOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
144
- protected abstract stakeOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
171
+ protected abstract allocateOrAssign(node: ts.CallExpression, system: CpiProgram, method: "allocate" | "assign"): undefined;
172
+ protected abstract tokenOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
173
+ protected abstract ataOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
174
+ protected abstract memoOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
175
+ protected abstract stakeOp(node: ts.CallExpression, program: CpiProgram, method: string): Value | undefined;
145
176
  protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
146
177
  protected abstract coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
147
178
  protected abstract bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
@@ -155,6 +186,7 @@ export declare abstract class EmitterBase {
155
186
  protected abstract expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
156
187
  protected abstract callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
157
188
  protected abstract listMethod(node: ts.CallExpression, method: string): Value | undefined;
189
+ protected abstract programErrorFail(name: string, node: ts.Node): string;
158
190
  protected abstract isPipeline(e: ts.Expression): e is ts.CallExpression;
159
191
  protected abstract closureOf(arg: ts.Expression): Closure;
160
192
  /** The arguments and accounts code written here can name (what a closure written here keeps). */
@@ -168,5 +200,6 @@ export declare abstract class EmitterBase {
168
200
  next?: string;
169
201
  alwaysNext?: boolean;
170
202
  atNext?: () => void;
203
+ body?: ts.Node;
171
204
  }, body: (element: ts.Expression, index: ts.Expression) => void): void;
172
205
  }
@@ -16,6 +16,14 @@ export class EmitterBase {
16
16
  lines = [];
17
17
  /** Declarations placed at the top of the function (buffers reused by every pass through a loop). */
18
18
  hoisted = [];
19
+ /**
20
+ * The hoisted declarations of heap buffers taken on first use (`T *name = NULL;`), by line: a loop moved into a
21
+ * function of its own leaves them in its caller and is given a pointer to each (see outlinedLoop), so the buffer is
22
+ * still taken once per function, not once per call of the loop's.
23
+ */
24
+ lazyHoists = new Map();
25
+ /** Loops moved into C functions of their own (see outlinedLoop), placed before this function. */
26
+ outlinedLoops = [];
19
27
  indent = 1;
20
28
  temp = 0;
21
29
  /** Init accounts whose create() has run (top-level, in order). */
@@ -218,6 +226,12 @@ export class EmitterBase {
218
226
  tmp(prefix = "t") {
219
227
  return `${prefix}${this.temp++}`;
220
228
  }
229
+ /** Declare a heap buffer pointer at the top of the function, NULL until first use (`decl(name)` declares it). */
230
+ hoistLazy(name, decl) {
231
+ const line = ` ${decl(name)} = NULL;`;
232
+ this.lazyHoists.set(line, { name, decl });
233
+ this.hoisted.push(line);
234
+ }
221
235
  /**
222
236
  * JS evaluates operands left to right, but a lowered Value is a C expression read where it is used.
223
237
  * When lowering a later operand emitted statements (from line `mark` on, e.g. a pop() or a helper call),
@@ -301,6 +315,7 @@ export class EmitterBase {
301
315
  const saved = {
302
316
  lines: this.lines.length,
303
317
  hoisted: this.hoisted.length, // a probed helper call may hoist declarations
318
+ outlined: this.outlinedLoops.length,
304
319
  temp: this.temp,
305
320
  diagnostics: this.reporter.diagnostics.length,
306
321
  scopes: this.scopes.length,
@@ -318,6 +333,7 @@ export class EmitterBase {
318
333
  finally {
319
334
  this.lines.length = saved.lines;
320
335
  this.hoisted.length = saved.hoisted;
336
+ this.outlinedLoops.length = saved.outlined;
321
337
  this.temp = saved.temp;
322
338
  this.reporter.diagnostics.length = saved.diagnostics;
323
339
  this.scopes.length = saved.scopes;
@@ -343,6 +359,23 @@ export class EmitterBase {
343
359
  exportName(node) {
344
360
  return ts.isIdentifier(node) ? this.imports.get(node.text) : undefined;
345
361
  }
362
+ /**
363
+ * `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut, storeBorsh and BigVec writes follow a native program, which
364
+ * writes data in place and leaves writability to the runtime (ReadonlyDataModified when a read-only account's data
365
+ * changed) and lets one account be viewed twice. Without it they check writability (3006) and claim the account
366
+ * once (2040) up front.
367
+ */
368
+ nativeAccountWrites() {
369
+ return this.model.constants.get("NATIVE_ACCOUNT_WRITES")?.value === true;
370
+ }
371
+ /** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
372
+ isEpochRewards(node) {
373
+ if (ts.isParenthesizedExpression(node))
374
+ return this.isEpochRewards(node.expression);
375
+ if (ts.isIdentifier(node))
376
+ return this.lookup(node.text)?.type.kind === "epochRewards";
377
+ return ts.isCallExpression(node) && this.exportName(node.expression) === "epochRewards";
378
+ }
346
379
  /**
347
380
  * `acct!.field` on an optional account: the same access without `!` (using the account checks that it was passed,
348
381
  * failing with 5115 otherwise). Returns undefined for anything else.
@@ -11,3 +11,10 @@ export declare function borshIdentical(t: FieldType, model: Pick<ProgramModel, "
11
11
  export declare function borshMinSize(s: StructDef, model: Pick<ProgramModel, "structs">): number;
12
12
  /** C for `ts_unpack_<S>` and `ts_pack_<S>` of every `@layout borsh` struct. */
13
13
  export declare function emitBorshCodecs(model: ProgramModel): string[];
14
+ /**
15
+ * C for `ts_bdec_<S>` / `ts_benc_<S>` of the structs `loadBorsh` / `storeBorsh` use (model.borshNative): the same
16
+ * straight-line codec, failing with a bare nonzero return (no log) so that the call site fails with BorshIoError.
17
+ */
18
+ export declare function emitNativeBorshCodecs(model: ProgramModel): string[];
19
+ /** Why `loadBorsh<S>` / `storeBorsh` cannot take struct `s`, or undefined when they can. */
20
+ export declare function borshNativeStructUnsupported(s: StructDef, model: Pick<ProgramModel, "structs" | "dataEnums">): string | undefined;
@@ -71,6 +71,89 @@ export function emitBorshCodecs(model) {
71
71
  for (const s of model.structs.values()) {
72
72
  if ((s.layout !== "borsh" && s.wire !== "borsh") || s.size === undefined)
73
73
  continue;
74
+ out.push(...codec(s, model, { unpack: `ts_unpack_${s.name}`, pack: `ts_pack_${s.name}`, deser: DESER, ser: SER, title: "Borsh (Anchor's account layout)" }));
75
+ }
76
+ return out;
77
+ }
78
+ /**
79
+ * C for `ts_bdec_<S>` / `ts_benc_<S>` of the structs `loadBorsh` / `storeBorsh` use (model.borshNative): the same
80
+ * straight-line codec, failing with a bare nonzero return (no log) so that the call site fails with BorshIoError.
81
+ */
82
+ export function emitNativeBorshCodecs(model) {
83
+ const out = [];
84
+ for (const name of model.borshNative) {
85
+ const s = model.structs.get(name);
86
+ out.push(...codec(s, model, {
87
+ unpack: `ts_bdec_${name}`,
88
+ pack: `ts_benc_${name}`,
89
+ deser: "return 1",
90
+ ser: "return 1",
91
+ title: "Borsh (loadBorsh / storeBorsh)",
92
+ utf8: true,
93
+ }));
94
+ }
95
+ return out;
96
+ }
97
+ /**
98
+ * Why `loadBorsh<T>` / `storeBorsh` cannot take a field of this type (their codec has no heap and no views), or
99
+ * undefined when it can.
100
+ */
101
+ function borshNativeUnsupported(t, model) {
102
+ if (borshIdentical(t, model))
103
+ return undefined;
104
+ switch (t.kind) {
105
+ case "fstring":
106
+ return undefined;
107
+ case "vec":
108
+ if (t.heap || t.cap === undefined)
109
+ return "a Vec<T> (it would live on the heap): use FixedVec<T, N>";
110
+ return borshIdentical(t.elem, model) || t.elem.kind === "fstring" ? undefined : "a FixedVec of Options, data enums or lists";
111
+ case "option": {
112
+ const inner = t.inner;
113
+ if (borshIdentical(inner, model))
114
+ return undefined;
115
+ const v = variableStruct(inner, model);
116
+ return v ? borshNativeStructUnsupported(v, model) : "an Option of a list, a string or a data enum";
117
+ }
118
+ case "struct": {
119
+ const v = variableStruct(t, model);
120
+ return v ? borshNativeStructUnsupported(v, model) : `${t.name} is itself @layout borsh: nest a plain struct (it is Borsh inside this one)`;
121
+ }
122
+ case "dataEnum": {
123
+ const e = model.dataEnums.get(t.name);
124
+ for (const v of e.variants)
125
+ for (const f of v.fields)
126
+ if (!borshIdentical(f.type, model))
127
+ return `${e.name} variant ${v.name}'s ${f.name} is not fixed-size (data enum payloads: integers, booleans, Pubkeys, unit enums, FixedArrays and structs of them)`;
128
+ return undefined;
129
+ }
130
+ case "array":
131
+ return "a FixedArray of Options, data enums, strings or lists";
132
+ case "string":
133
+ return "a string (a view of the bytes it was read from): use FixedString<N>";
134
+ default:
135
+ return `a ${t.kind} field`;
136
+ }
137
+ }
138
+ /** Why `loadBorsh<S>` / `storeBorsh` cannot take struct `s`, or undefined when they can. */
139
+ export function borshNativeStructUnsupported(s, model) {
140
+ if (s.size === undefined || s.viewsOnly)
141
+ return `${s.name} has string fields (views of the bytes it was read from): use FixedString<N>`;
142
+ if (s.vec)
143
+ return `${s.name} has a Vec<T> field (it would live on the heap): use FixedVec<T, N>`;
144
+ for (const f of s.fields) {
145
+ const why = borshNativeUnsupported(f.type, model);
146
+ if (why)
147
+ return `${s.name}.${f.name} is ${why}`;
148
+ }
149
+ return undefined;
150
+ }
151
+ /** The decode / encode pair of one struct. */
152
+ function codec(s, model, o) {
153
+ const out = [];
154
+ const DESER = o.deser;
155
+ const SER = o.ser;
156
+ {
74
157
  let k = 0;
75
158
  const tmp = (p) => `${p}${k++}`;
76
159
  // Bools and enum tags inside a Borsh-identical value: invalid ones fail, as Borsh deserialization does.
@@ -114,6 +197,8 @@ export function emitBorshCodecs(model) {
114
197
  `${pad}at += 4;`,
115
198
  `${pad}if (${l} > ${t.cap}) ${DESER};`,
116
199
  need(l, rest, pad),
200
+ // Bytes another program wrote (loadBorsh): checked as UTF-8 as Borsh String deserialization does.
201
+ ...(o.utf8 ? [`${pad}if (!ts_utf8_valid(src + at, ${l})) ${DESER};`] : []),
117
202
  `${pad}${lv}.len = ${l};`,
118
203
  `${pad}ts_memcpy(${lv}.bytes, src + at, ${l});`,
119
204
  `${pad}at += ${l};`,
@@ -356,7 +441,7 @@ export function emitBorshCodecs(model) {
356
441
  i++;
357
442
  }
358
443
  const min = borshMinSize(s, model);
359
- out.push(`/* ${s.name} as Borsh (Anchor's account layout) <-> its fixed-layout struct. */`, `__attribute__((noinline)) static uint64_t ts_unpack_${s.name}(const uint8_t *src, uint64_t len, TSS_${s.name} *out, uint64_t *used) {`, ` if (len < ${min}) ${DESER};`, ` uint64_t at = 0;`, ...unpackLines, ` if (used) *used = at;`, ` return SUCCESS;`, `}`, `__attribute__((noinline)) static uint64_t ts_pack_${s.name}(const TSS_${s.name} *in, uint8_t *dst, uint64_t cap, uint64_t *written) {`, ` if (cap < ${min}) ${SER};`, ` uint64_t at = 0;`, ...packLines, ` if (written) *written = at;`, ` return SUCCESS;`, `}`, "");
444
+ out.push(`/* ${s.name} as ${o.title} <-> its fixed-layout struct. */`, `__attribute__((noinline)) static uint64_t ${o.unpack}(const uint8_t *src, uint64_t len, TSS_${s.name} *out, uint64_t *used) {`, ` if (len < ${min}) ${DESER};`, ` uint64_t at = 0;`, ...unpackLines, ` if (used) *used = at;`, ` return SUCCESS;`, `}`, `__attribute__((noinline)) static uint64_t ${o.pack}(const TSS_${s.name} *in, uint8_t *dst, uint64_t cap, uint64_t *written) {`, ` if (cap < ${min}) ${SER};`, ` uint64_t at = 0;`, ...packLines, ` if (written) *written = at;`, ` return SUCCESS;`, `}`, "");
360
445
  }
361
446
  return out;
362
447
  }