@typesol/cli 0.38.0 → 0.39.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 (52) hide show
  1. package/CHANGELOG.md +327 -2
  2. package/README.md +29 -15
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +6 -11
  5. package/dist/compiler/analyze.js +323 -31
  6. package/dist/compiler/emit/alias.js +3 -2
  7. package/dist/compiler/emit/base.d.ts +5 -0
  8. package/dist/compiler/emit/base.js +2 -0
  9. package/dist/compiler/emit/borsh.js +63 -2
  10. package/dist/compiler/emit/calls.d.ts +9 -1
  11. package/dist/compiler/emit/calls.js +147 -18
  12. package/dist/compiler/emit/cpi-core.js +17 -5
  13. package/dist/compiler/emit/cpi.js +81 -27
  14. package/dist/compiler/emit/create.d.ts +7 -0
  15. package/dist/compiler/emit/create.js +27 -0
  16. package/dist/compiler/emit/expressions.js +7 -4
  17. package/dist/compiler/emit/function.d.ts +7 -0
  18. package/dist/compiler/emit/function.js +164 -29
  19. package/dist/compiler/emit/program.js +15 -2
  20. package/dist/compiler/emit/shared.d.ts +5 -5
  21. package/dist/compiler/emit/shared.js +5 -0
  22. package/dist/compiler/emit/statements.d.ts +8 -0
  23. package/dist/compiler/emit/statements.js +93 -6
  24. package/dist/compiler/emit/storage.d.ts +10 -1
  25. package/dist/compiler/emit/storage.js +50 -11
  26. package/dist/compiler/idl.d.ts +1 -1
  27. package/dist/compiler/idl.js +42 -11
  28. package/dist/compiler/model.d.ts +47 -10
  29. package/dist/compiler/model.js +14 -4
  30. package/dist/testing.js +8 -0
  31. package/dist/tools/clientgen.js +10 -1
  32. package/dist/tools/portgen.d.ts +6 -0
  33. package/dist/tools/portgen.js +68 -17
  34. package/docs/architecture.md +5 -4
  35. package/docs/audit.md +31 -19
  36. package/docs/case-study-escrow.md +5 -5
  37. package/docs/case-study-jito-mev.md +9 -5
  38. package/docs/case-study-marginfi.md +797 -0
  39. package/docs/case-study-multisig.md +3 -3
  40. package/docs/case-study-raydium-clmm.md +44 -33
  41. package/docs/case-study-raydium-cp-swap.md +3 -3
  42. package/docs/cli.md +5 -5
  43. package/docs/client.md +1 -1
  44. package/docs/errors.md +13 -5
  45. package/docs/language.md +38 -25
  46. package/docs/migrate-from-anchor.md +4 -1
  47. package/docs/runtime.md +1 -1
  48. package/docs/security-model.md +2 -1
  49. package/docs/testing.md +33 -1
  50. package/lib/typesol.d.ts +46 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
package/docs/testing.md CHANGED
@@ -6,10 +6,42 @@ run prints its seed; reproduce with `FUZZ_SEED=<n>`, widen with `FUZZ_RUNS` / `F
6
6
  | Check | Oracle | What must hold |
7
7
  | --- | --- | --- |
8
8
  | `test/verification/fuzz-arith.test.ts` | BigInt | `+ - * / % **`, `& \| ^ << >> ~`, unary minus, comparisons and casts at every width u8…u128 / i8…i128, plus `mulDiv`, `mulDivCeil`, `isqrt`, `min`, `max`, return the same value or abort with the same code (5100/5101/4102), for edge and random inputs |
9
+ | `test/verification/fuzz-u256.test.ts` | BigInt | every `u256` operator, `mulDiv` / `mulDivCeil` with their 512-bit product, comparisons and the checked narrowing casts, on random values: the same value or the same error (5100, 5101, 4102) |
10
+ | `showcase/test/fuzz-i80f48.test.ts` | vectors the `fixed` crate (1.28.0) wrote, from `showcase/test/fixtures/marginfi/i80f48-oracle` | Marginfi's I80F48 (`showcase/mainnet/marginfi/i80f48.ts`): a BigInt model must give every vector, then the port must give the model's answer on them and on random values (products toward −∞, quotients toward zero, f64 to nearest-even) |
9
11
  | `test/verification/fuzz-state.test.ts` | TypeScript state model | random honest + hostile actions on vault and escrow: every outcome as predicted, balances equal the model, SOL conserved up to fees, token supply exactly conserved; random filings/decisions/resets on ledgerbook: Vec contents, account size and rent exemption equal the model |
10
12
  | `test/verification/fuzz-layout.test.ts` | TypeScript model | random pushes, pops, sets, in-place additions, moves and clears on an account with two growable Vecs (honest, out of range and by a stranger): the decoded account equals the model after every step; random `loadAccountMut` index pairs over remaining-account lists that repeat accounts: every alias refused (2040), balances conserved |
13
+ | `showcase/test/fuzz-jito.test.ts` | Jito's tip payment, tip distribution and priority fee distribution as deployed on mainnet | random sequences of tips, receiver and builder changes, accounts opened over epochs, roots uploaded, Merkle claims (wrong amounts, proofs and signers among them), closes and config changes, with at most one injected fault per transaction: the same outcome, account bytes, events and log lines as the original after every step; keys, amounts and choices all come from the seed |
14
+ | `showcase/test/fuzz-marginfi.test.ts` | Marginfi v2 as deployed on mainnet | random sequences of bank creation (random weights, curves and fees, most valid, some broken one way), configuration (operational states, curves, liquidation fees, the circuit breaker's switch and settings, frozen banks), accruals over balances written into both at every scale and clock jumps up to a year, limits, pauses, wrong signers: the same outcome, account bytes and events as the original after every step; inputs the original panics on (a negative fee rate) must fail in the port too |
15
+ | the `fuzz:` case of `showcase/test/raydium-clmm.test.ts` | Raydium CLMM as deployed on mainnet | random swaps (both ways, exact in and out, price limits, thresholds), positions opened at random ranges, and liquidity added and taken out (over the position's own, under slippage limits): the same outcome, account bytes and events as the original after every step; choices and amounts come from the seed (`CLMM_FUZZ_STEPS` lengthens it), keys are fresh each run; each transaction may use 1.4M compute units, so a swap the original needs more than 200,000 for still runs to its end |
11
16
  | `test/verification/differential.test.ts` | Anchor twins in `test/anchor-twins` | identical transactions to TypeSOL and Anchor programs: same outcomes, same account contents, same wallet and token balances after every step |
12
- | `test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `test/ports/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([test/ports/README.md](https://github.com/typesol/typesol/blob/main/test/ports/README.md)) |
17
+ | `showcase/test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `showcase/program-examples/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([showcase/program-examples/README.md](https://github.com/typesol-lang/typesol/blob/main/showcase/program-examples/README.md)) |
13
18
 
14
19
  Compute-unit and binary-size comparisons with Anchor, native Rust and Pinocchio are in the README
15
20
  ([Numbers](../README.md#numbers)).
21
+
22
+ ## Reproducing a release
23
+
24
+ From the release after 0.38.0 on, each release's GitHub Release carries `manifest.json` (written by
25
+ `scripts/release-manifest.ts` from the published package and the tag's sources; the scripts need Node 22.18 or later):
26
+
27
+ - the compiler and toolchain versions (clang, platform-tools, Node, TypeScript, the runtime header's sha256);
28
+ - the sha256 of the SBF binary, IDL and C that every program under `examples/` and `showcase/program-examples/` builds to;
29
+ - the sha256 of the reference binaries the differential tests run against (`test/programs/`);
30
+ - a hash of the test corpus.
31
+
32
+ It also carries the previous release's sources built by the previous package and by this one, and their diff
33
+ (`binary-diff.txt`). That is the check behind a changelog line such as "programs that use none of these compile to the
34
+ same binaries". To redo it, or to compare other versions:
35
+
36
+ ```sh
37
+ git worktree add ../typesol-prev v0.37.0 # the sources to build
38
+ npm install --prefix /tmp/a @typesol/cli@0.37.0
39
+ npm install --prefix /tmp/b @typesol/cli@0.38.0
40
+ node scripts/release-manifest.ts --compiler /tmp/a/node_modules/@typesol/cli --sources ../typesol-prev --out a.json
41
+ node scripts/release-manifest.ts --compiler /tmp/b/node_modules/@typesol/cli --sources ../typesol-prev --out b.json
42
+ node scripts/release-manifest.ts --diff a.json b.json
43
+ ```
44
+
45
+ For 0.37.0 → 0.38.0 (run by hand before the manifest job existed): all 67 programs of the 0.37.0 sources build to
46
+ the same binary and IDL with both packages.
47
+
package/lib/typesol.d.ts CHANGED
@@ -177,8 +177,10 @@ export declare function remainingAccounts(): RemainingAccounts;
177
177
  * Read a struct of this program from a remaining account or an `AccountInfo` parameter (Anchor's
178
178
  * `AccountLoader::try_from` on an `UncheckedAccount`): owner, discriminator and size are checked.
179
179
  * `loadAccountMut` also requires it to be writable, not aliased by another writable account, and not already loaded
180
- * with `loadAccountMut` in this instruction (2040). The result is also the account (`.key`, `.lamports`), and passes
181
- * to a helper that takes `Account<T>` / `Mut<T>`.
180
+ * with `loadAccountMut` in this instruction (2040). A `const` view declared in a loop body ends with its iteration,
181
+ * so a later iteration may load the account again; `loadAccountMut<Dup<T>>` there also lets a remaining account be
182
+ * passed more than once (a route back through one pool), one view at a time. The result is also the account (`.key`,
183
+ * `.lamports`), and passes to a helper that takes `Account<T>` / `Mut<T>`.
182
184
  */
183
185
  export declare function loadAccount<T>(account: RemainingAccount | AccountInfo): Account<T>;
184
186
  export declare function loadAccountMut<T>(account: RemainingAccount | AccountInfo): Mut<T>;
@@ -655,6 +657,12 @@ export declare const AuthorityType: {
655
657
  * the struct size. Accounts ending in a Vec size themselves through push/pop/clear.
656
658
  */
657
659
  export declare function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void;
660
+ /**
661
+ * Resize a `Mut<AccountInfo>` of this program to `newSize` bytes (Rust's `AccountInfo::resize`): the data length only,
662
+ * the new bytes zeroed. No rent moves: fund the account first (`rentExempt(newSize)`), the runtime refuses an account
663
+ * left short. At most 10 KiB past its size when the instruction started (3016).
664
+ */
665
+ export declare function resizeAccount(account: Mut<AccountInfo>, newSize: u64): void;
658
666
 
659
667
  /**
660
668
  * Token-2022 extensions of a mint (any account works; legacy SPL Token mints have none).
@@ -725,8 +733,8 @@ export type Account<T> = Readonly<T> & AccountMeta;
725
733
  */
726
734
  export type Mut<T, E = never> = T & AccountMeta;
727
735
 
728
- /** A PDA seed: a string, a Pubkey, an integer (at its width) or a unit enum value (one byte). */
729
- export type Seed = string | Pubkey | bigint | number;
736
+ /** A PDA seed: a string, a Pubkey, a Hash (its 32 bytes), an integer (at its width) or a unit enum value (one byte). */
737
+ export type Seed = string | Pubkey | Hash | bigint | number;
730
738
 
731
739
  /**
732
740
  * The seeds (with the bump) of one PDA signature, for helpers that sign CPIs: declare a `seeds: SignerSeeds`
@@ -831,7 +839,7 @@ export type MintOf<A, AuthorityParam extends string, FreezeAuthorityParam extend
831
839
  /**
832
840
  * Anchor's `dup`: this writable account may be the same account as another writable parameter (TypeSOL refuses that
833
841
  * otherwise, 2040). Both are read and written in place, so a write through one is seen through the other: read
834
- * what you need before writing. Not for accounts that are created, closed, a close destination or `@layout borsh`.
842
+ * what you need before writing. Not for accounts that are created, closed or `@layout borsh` (a close destination may be one: it receives the rent through either).
835
843
  */
836
844
  export type Dup<A> = A & { readonly __dup?: true };
837
845
  /**
@@ -1516,6 +1524,8 @@ export interface CompressedLeaf {
1516
1524
  /** The current slot and epoch (Clock sysvar). */
1517
1525
  export declare function currentSlot(): u64;
1518
1526
  export declare function currentEpoch(): u64;
1527
+ /** The Unix time the current epoch started at (Clock.epoch_start_timestamp). */
1528
+ export declare function epochStartTimestamp(): i64;
1519
1529
  /** The EpochSchedule sysvar: slots per epoch (after warmup), whether epochs warm up, and where normal epochs start. */
1520
1530
  export declare function slotsPerEpoch(): u64;
1521
1531
  export declare function epochWarmup(): boolean;
@@ -1632,6 +1642,13 @@ export interface SystemProgram extends AccountMeta {
1632
1642
  * `Mut<Signer>` keypair, or a PDA of this program when you pass its `signerSeeds` (with the bump).
1633
1643
  */
1634
1644
  createAccount(payer: Mut<Signer>, account: AccountMeta, lamports: u64, space: u64, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
1645
+ /**
1646
+ * Anchor's `init` with `seeds`, `space` and `owner = …` on an `UncheckedAccount`: `account` must be the PDA of this
1647
+ * program for `seeds` (no bump; 2006 otherwise); it is created with `space` bytes owned by `owner`, or, when someone
1648
+ * already funded the address, topped up to rent, allocated and assigned. Returns the bump. Among the creates a body
1649
+ * starts with, it runs before the other accounts' constraints, as Anchor's `init` does.
1650
+ */
1651
+ createPda(payer: Mut<Signer>, account: Mut<AccountInfo>, space: u64, owner: Pubkey, seeds: Seed[]): u8;
1635
1652
  /** System Allocate: give `account` `space` bytes of data. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
1636
1653
  allocate(account: AccountMeta, space: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1637
1654
  /** System Assign: make `owner` the account's owner. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
@@ -1820,9 +1837,13 @@ export interface UncheckedProgram extends AccountMeta {
1820
1837
  export interface CpiAccount {
1821
1838
  readonly __cpi_account: void;
1822
1839
  }
1823
- export declare function readonly(account: AccountMeta | RemainingAccount): CpiAccount;
1840
+ /**
1841
+ * An optional account (`A | null`) passed as it is, without `!`: left out of the CPI's list when it was not passed
1842
+ * (Rust's `if let Some(a) = &self.a { accounts.push(a) }`, as for `with_remaining_accounts`).
1843
+ */
1844
+ export declare function readonly(account: AccountMeta | RemainingAccount | null): CpiAccount;
1824
1845
  export declare function readonly(accounts: RemainingAccounts | RemainingSlice): Iterable<CpiAccount>;
1825
- export declare function writable(account: AccountMeta | RemainingAccount): CpiAccount;
1846
+ export declare function writable(account: AccountMeta | RemainingAccount | null): CpiAccount;
1826
1847
  export declare function writable(accounts: RemainingAccounts | RemainingSlice): Iterable<CpiAccount>;
1827
1848
  export declare function readonlySigner(account: AccountMeta | RemainingAccount): CpiAccount;
1828
1849
  export declare function writableSigner(account: AccountMeta | RemainingAccount): CpiAccount;
@@ -1968,9 +1989,11 @@ export declare enum AnchorError {
1968
1989
  /**
1969
1990
  * Abort with the given error unless `condition` holds. The error is a member of an exported string enum, any
1970
1991
  * `AnchorError` member, or a string literal: each distinct literal becomes an error named `RequireFailed<N>` with code
1971
- * 6000 + N, numbered after the program's error enums and listed in the IDL.
1992
+ * 6000 + N, numbered after the program's error enums and listed in the IDL. A `u32` value instead fails with that code
1993
+ * as computed at run time (`require(r.err === 0n, r.err)`, a helper returning its error as a value, as Rust's `?` passes
1994
+ * one on); a zero code fails with 5100.
1972
1995
  */
1973
- export declare function require(condition: boolean, error: string | AnchorError): asserts condition;
1996
+ export declare function require(condition: boolean, error: string | AnchorError | u32): asserts condition;
1974
1997
  /**
1975
1998
  * Anchor's `constraint = condition @ error` on `account`. Written at the start of an instruction's body (before any
1976
1999
  * other statement), it runs with that account's checks, after its has_one and before its owner check, so a transaction
@@ -2038,6 +2061,15 @@ export declare function mulDiv(a: u64, b: u64, c: u64): u64;
2038
2061
  export declare function mulDivCeil(a: u64, b: u64, c: u64): u64;
2039
2062
  /** floor(sqrt(x)) for unsigned integers up to u128. */
2040
2063
  export declare function isqrt<T extends bigint>(x: T): T;
2064
+
2065
+ /**
2066
+ * A 64-bit float, held as its IEEE 754 bits (Borsh writes an f64 as those 8 bytes, little-endian); the IDL calls it
2067
+ * f64. There is no float arithmetic: make one from bits the program computed in integers (`f64FromBits`), as
2068
+ * Marginfi's events report I80F48 amounts, and read the bits back with `f64Bits`.
2069
+ */
2070
+ export type f64 = bigint & { readonly __f64: unique symbol };
2071
+ export declare function f64FromBits(bits: u64): f64;
2072
+ export declare function f64Bits(value: f64): u64;
2041
2073
  export declare function min<T extends bigint>(a: T, b: T): T;
2042
2074
  export declare function max<T extends bigint>(a: T, b: T): T;
2043
2075
 
@@ -2046,6 +2078,11 @@ export declare function max<T extends bigint>(a: T, b: T): T;
2046
2078
  * `readData<u64>(pool, 72n)`, `readData<Pubkey>(pool, 8n)`. Check the account's owner yourself first.
2047
2079
  */
2048
2080
  export declare function readData<T extends bigint | boolean | Pubkey | Hash>(account: AccountMeta | RemainingAccount, offset: u64): T;
2081
+ /**
2082
+ * Write a little-endian value at `offset` in a `Mut<AccountInfo>`'s data (bounds-checked, error 3003):
2083
+ * `writeData<u64>(archive, 72n, count)`. Only this program's accounts can change: check the owner first.
2084
+ */
2085
+ export declare function writeData<T extends bigint | boolean | Pubkey | Hash>(account: Mut<AccountInfo>, offset: u64, value: T): void;
2049
2086
 
2050
2087
  /**
2051
2088
  * View another program's Anchor account as a struct declared here (same field layout): the owner must be
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -63,13 +63,15 @@
63
63
  "test": "vitest run",
64
64
  "typesol": "node dist/cli.js",
65
65
  "smoke": "node scripts/smoke.ts",
66
- "fuzz": "FUZZ_RUNS=2000 FUZZ_STEPS=600 FUZZ_VERBOSE=1 vitest run test/verification/fuzz-arith.test.ts test/verification/fuzz-state.test.ts test/verification/fuzz-layout.test.ts test/verification/differential.test.ts --silent=false",
66
+ "fuzz": "FUZZ_RUNS=2000 FUZZ_STEPS=600 FUZZ_VERBOSE=1 vitest run test/verification/fuzz-arith.test.ts test/verification/fuzz-state.test.ts test/verification/fuzz-layout.test.ts test/verification/differential.test.ts showcase/test/fuzz-jito.test.ts showcase/test/fuzz-marginfi.test.ts --silent=false",
67
67
  "build:twins": "cd test/anchor-twins && cargo-build-sbf",
68
68
  "prepack": "npm run build",
69
69
  "fetch:programs": "bash scripts/fetch-programs.sh",
70
- "format": "prettier --write \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\"",
71
- "lint": "prettier --check \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\" && pnpm typecheck",
72
- "prepublishOnly": "pnpm lint && pnpm test"
70
+ "format": "prettier --write \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"showcase/test/*.ts\" \"showcase/test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\"",
71
+ "lint": "prettier --check \"src/**/*.ts\" \"test/*.ts\" \"test/*/*.test.ts\" \"showcase/test/*.ts\" \"showcase/test/*/*.test.ts\" \"scripts/**/*.ts\" \"lib/**/*.ts\" && pnpm typecheck",
72
+ "prepublishOnly": "pnpm lint && pnpm test",
73
+ "test:core": "vitest run --exclude 'showcase/**'",
74
+ "test:showcase": "vitest run showcase"
73
75
  },
74
76
  "engines": {
75
77
  "node": ">=22.12"
@@ -115,10 +117,10 @@
115
117
  "packageManager": "pnpm@11.9.0",
116
118
  "repository": {
117
119
  "type": "git",
118
- "url": "git+https://github.com/typesol/typesol.git"
120
+ "url": "git+https://github.com/typesol-lang/typesol.git"
119
121
  },
120
122
  "bugs": {
121
- "url": "https://github.com/typesol/typesol/issues"
123
+ "url": "https://github.com/typesol-lang/typesol/issues"
122
124
  },
123
125
  "homepage": "https://typesol.com",
124
126
  "publishConfig": {
@@ -38,6 +38,7 @@
38
38
  #define TS_ERR_DUPLICATE_MUT 2040 /* ConstraintDuplicateMutableAccount */
39
39
  #define TS_ERR_ALREADY_INITIALIZED 3000 /* AccountDiscriminatorAlreadySet */
40
40
  #define TS_ERR_INIT_PAYER 4101 /* TryingToInitPayerAsProgramAccount */
41
+ #define TS_ERR_DISC_NOT_FOUND 3001 /* AccountDiscriminatorNotFound */
41
42
  #define TS_ERR_DISCRIMINATOR 3002 /* AccountDiscriminatorMismatch */
42
43
  #define TS_ERR_ACCOUNT_TOO_SMALL 3003 /* AccountDidNotDeserialize */
43
44
  #define TS_ERR_DID_NOT_SERIALIZE 3004 /* AccountDidNotSerialize */
@@ -73,6 +74,10 @@ static __attribute__((noinline)) uint64_t ts_fail(uint64_t code, const char *msg
73
74
  return code;
74
75
  }
75
76
  #define TS_FAIL(code, msg) return ts_fail((code), (msg), sol_strlen(msg))
77
+ /* require(condition, code) with a code computed at run time: 0 would read as success, so it fails as an overflow. */
78
+ static __attribute__((noinline, unused)) uint64_t ts_fail_code(uint32_t code, const char *msg) {
79
+ return ts_fail(code ? code : TS_ERR_OVERFLOW, msg, sol_strlen(msg));
80
+ }
76
81
 
77
82
  #define TS_TRY(expr) \
78
83
  do { \
@@ -355,17 +360,25 @@ static __attribute__((noinline)) void ts_divmod32(const uint32_t *u, int mmax, T
355
360
  }
356
361
  if (rem) *rem = ts_u256_from32(r);
357
362
  }
363
+ /* Two 64-bit values: one 128-bit product. Otherwise schoolbook over the limbs that are not zero (two 88-bit values
364
+ take 9 products, not 64). */
358
365
  static inline bool ts_u256_mul(TsU256 a, TsU256 b, TsU256 *out) {
359
- if (ts_u256_fits(a, 128) && ts_u256_fits(b, 128) && ((a.w[1] | b.w[1]) == 0)) {
366
+ if (((a.w[1] | a.w[2] | a.w[3]) | (b.w[1] | b.w[2] | b.w[3])) == 0) {
360
367
  *out = ts_u256_from_u128((unsigned __int128)a.w[0] * b.w[0]);
361
368
  return false;
362
369
  }
363
370
  uint32_t x[8], y[8], r[16];
364
371
  ts_u256_to32(a, x);
365
372
  ts_u256_to32(b, y);
366
- ts_mul32(x, 8, y, 8, r);
373
+ int n = ts_len32(x, 8), m = ts_len32(y, 8);
374
+ if (n == 0 || m == 0) {
375
+ *out = ts_u256_lit(0, 0, 0, 0);
376
+ return false;
377
+ }
378
+ ts_mul32(x, n, y, m, r);
379
+ for (int i = n + m; i < 16; i++) r[i] = 0;
367
380
  *out = ts_u256_from32(r);
368
- for (int i = 8; i < 16; i++)
381
+ for (int i = 8; i < n + m; i++)
369
382
  if (r[i]) return true;
370
383
  return false;
371
384
  }
@@ -711,6 +724,18 @@ static inline uint64_t ts_check_program_account(const TsAccount *a, const SolPub
711
724
  return SUCCESS;
712
725
  }
713
726
 
727
+ /* A zero-copy (`@serialization bytemuck`) account, as Anchor's AccountLoader checks one: owner, then a discriminator to
728
+ read and match, with no "not initialized" case. Anchor's load() then panics on data shorter than the struct; this
729
+ refuses it (3003). */
730
+ static inline uint64_t ts_check_loader_account(const TsAccount *a, const SolPubkey *program_id, const uint8_t disc[8],
731
+ uint64_t size) {
732
+ if (!ts_key_eq(&a->owner, program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");
733
+ if (a->data_len < 8) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: account has no discriminator");
734
+ if (!ts_mem_eq(a->data, disc, 8)) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: account discriminator mismatch");
735
+ if (a->data_len < 8 + size) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");
736
+ return SUCCESS;
737
+ }
738
+
714
739
  /* An account ending in Vec<T>: data must be exactly fixed part + len * element size. */
715
740
  static inline uint64_t ts_check_vec_len(const TsAccount *a, uint64_t fixed, uint32_t len, uint64_t elem) {
716
741
  if (a->data_len != 8 + fixed + (uint64_t)len * elem)
@@ -756,6 +781,44 @@ static inline uint64_t ts_claim_mut_at(TsParams *params, uint64_t at) {
756
781
  return SUCCESS;
757
782
  }
758
783
 
784
+ /* A loadAccountMut inside a loop whose view cannot outlive the iteration: the claim's index is kept in `*slot`, so the
785
+ iteration's end can drop it (ts_release_mut) and the next iteration may load the same account again.
786
+ A remaining account may be passed more than once here (a route through one pool twice): its slots share one record,
787
+ and the claim bit is the last slot's, so two live views of it are still refused. It may not also be one of the
788
+ instruction's own accounts (`declared`: their count), whose views last the whole instruction. */
789
+ static inline uint64_t ts_claim_mut_rec(TsParams *params, const TsAccount *a, uint64_t *slot, uint64_t declared) {
790
+ uint64_t seen = 0, at = 0, first = (uint64_t)-1;
791
+ for (uint64_t i = 0; i < params->ka_num; i++)
792
+ if (params->ka[i] == a) {
793
+ seen++, at = i;
794
+ if (first == (uint64_t)-1) first = i;
795
+ }
796
+ if (seen > 1 && first < declared) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account passed more than once");
797
+ #if TS_MAX_ACCOUNTS > 64
798
+ if (params->loaded_mut[at >> 6] >> (at & 63) & 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account already loaded with loadAccountMut");
799
+ params->loaded_mut[at >> 6] |= (uint64_t)1 << (at & 63);
800
+ #else
801
+ if (params->loaded_mut >> at & 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account already loaded with loadAccountMut");
802
+ params->loaded_mut |= (uint64_t)1 << at;
803
+ #endif
804
+ *slot = at;
805
+ return SUCCESS;
806
+ }
807
+ static inline uint64_t ts_claim_mut_at_rec(TsParams *params, uint64_t at, uint64_t *slot) {
808
+ TS_TRY(ts_claim_mut_at(params, at));
809
+ *slot = at;
810
+ return SUCCESS;
811
+ }
812
+ static inline void ts_release_mut(TsParams *params, uint64_t *slot) {
813
+ if (*slot == (uint64_t)-1) return;
814
+ #if TS_MAX_ACCOUNTS > 64
815
+ params->loaded_mut[*slot >> 6] &= ~((uint64_t)1 << (*slot & 63));
816
+ #else
817
+ params->loaded_mut &= ~((uint64_t)1 << *slot);
818
+ #endif
819
+ *slot = (uint64_t)-1;
820
+ }
821
+
759
822
  static inline uint64_t ts_check_address(const TsAccount *a, const SolPubkey *expected) {
760
823
  if (!ts_key_eq(&a->key, expected)) TS_FAIL(TS_ERR_WRONG_PROGRAM, "TypeSOL: unexpected program address");
761
824
  return SUCCESS;
@@ -778,13 +841,19 @@ static inline bool ts_is_token_program(const SolPubkey *k) {
778
841
  }
779
842
  /* A Token-2022 Multisig is 355 bytes and its signer bytes are attacker-chosen: never accept that length. */
780
843
  #define TS_MULTISIG_LEN 355
844
+ /* A token account or mint not owned by a token program. As Anchor's (Interface)Account: an empty system account (never
845
+ created) is "not initialized", anything else a wrong owner. Out of line: the checks that pass stay as small as before. */
846
+ static __attribute__((noinline)) uint64_t ts_token_owner_fail(const TsAccount *a) {
847
+ if (a->lamports == 0 && ts_key_eq(&a->owner, &TS_SYSTEM_PROGRAM_ID)) TS_FAIL(TS_ERR_NOT_INITIALIZED, "TypeSOL: account is not initialized");
848
+ TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: not owned by a token program");
849
+ }
781
850
  static inline uint64_t ts_check_token_account(const TsAccount *a) {
782
851
  bool ok = false;
783
852
  if (ts_key_eq(&a->owner, &TS_TOKEN_PROGRAM_ID)) ok = a->data_len == TS_TOKEN_ACCOUNT_LEN;
784
853
  else if (ts_key_eq(&a->owner, &TS_TOKEN_2022_PROGRAM_ID))
785
854
  ok = a->data_len == TS_TOKEN_ACCOUNT_LEN ||
786
855
  (a->data_len > TS_TOKEN_ACCOUNT_LEN && a->data_len != TS_MULTISIG_LEN && a->data[TS_TOKEN_ACCOUNT_LEN] == 2);
787
- else TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: token account not owned by a token program");
856
+ else return ts_token_owner_fail(a);
788
857
  if (!ok || a->data[108] == 0) TS_FAIL(TS_ERR_TOKEN_ACCOUNT, "TypeSOL: not an initialized token account");
789
858
  return SUCCESS;
790
859
  }
@@ -795,7 +864,7 @@ static inline uint64_t ts_check_mint(const TsAccount *a) {
795
864
  else if (ts_key_eq(&a->owner, &TS_TOKEN_2022_PROGRAM_ID))
796
865
  ok = a->data_len == TS_MINT_LEN ||
797
866
  (a->data_len > TS_TOKEN_ACCOUNT_LEN && a->data_len != TS_MULTISIG_LEN && a->data[TS_TOKEN_ACCOUNT_LEN] == 1);
798
- else TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: mint not owned by a token program");
867
+ else return ts_token_owner_fail(a);
799
868
  if (!ok || a->data[45] != 1) TS_FAIL(TS_ERR_MINT, "TypeSOL: not an initialized mint");
800
869
  return SUCCESS;
801
870
  }
@@ -998,10 +1067,13 @@ static inline uint64_t ts_init_account(TsAccount *a, const SolPubkey *program_id
998
1067
  return SUCCESS;
999
1068
  }
1000
1069
 
1001
- /* Pubkey order: Rust's Ord on [u8; 32], lexicographic. */
1070
+ /* Pubkey order: Rust's Ord on [u8; 32], lexicographic. Eight bytes at a time: a word read big-endian orders as its
1071
+ bytes do, so the first word that differs decides. */
1002
1072
  static inline int64_t ts_key_cmp(const SolPubkey *a, const SolPubkey *b) {
1003
- for (int i = 0; i < 32; i++)
1004
- if (a->x[i] != b->x[i]) return a->x[i] < b->x[i] ? -1 : 1;
1073
+ for (int i = 0; i < 32; i += 8) {
1074
+ uint64_t x = ts_ld64(a->x + i), y = ts_ld64(b->x + i);
1075
+ if (x != y) return __builtin_bswap64(x) < __builtin_bswap64(y) ? -1 : 1;
1076
+ }
1005
1077
  return 0;
1006
1078
  }
1007
1079
 
@@ -1034,12 +1106,12 @@ static inline uint64_t ts_system_transfer(TsParams *params, TsAccount *from, TsA
1034
1106
  }
1035
1107
 
1036
1108
  /*
1037
- * Create `acct` as a PDA of this program. `seeds` must have room for one extra
1038
- * entry: the bump is appended there. Writes the discriminator on success.
1109
+ * Create `acct` as a PDA of this program, owned by `owner` (Anchor's `init` with `owner = …`). `seeds` must have room
1110
+ * for one extra entry: the bump is appended there.
1039
1111
  */
1040
- static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccount *acct,
1041
- SolSignerSeed *seeds, int n, const uint8_t disc[8], uint64_t space,
1042
- uint8_t *bump_out) {
1112
+ static inline uint64_t ts_create_pda_owned(TsParams *params, TsAccount *payer, TsAccount *acct,
1113
+ SolSignerSeed *seeds, int n, const SolPubkey *owner, uint64_t space,
1114
+ uint8_t *bump_out) {
1043
1115
  SolPubkey derived;
1044
1116
  uint8_t bump;
1045
1117
  if (ts_find_pda(seeds, n, params->program_id, &derived, &bump) != SUCCESS ||
@@ -1059,7 +1131,7 @@ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccou
1059
1131
  ts_memcpy(data, &tag, 4);
1060
1132
  ts_memcpy(data + 4, &lamports, 8);
1061
1133
  ts_memcpy(data + 12, &space, 8);
1062
- ts_memcpy(data + 20, params->program_id, 32);
1134
+ ts_memcpy(data + 20, owner, 32);
1063
1135
  SolAccountMeta metas[2] = {{&payer->key, true, true}, {&acct->key, true, true}};
1064
1136
  SolInstruction ix = {(SolPubkey *)&TS_SYSTEM_PROGRAM_ID, metas, 2, data, sizeof(data)};
1065
1137
  TS_TRY(ts_invoke(params, &ix, &signer, 1));
@@ -1077,17 +1149,25 @@ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccou
1077
1149
  uint8_t assign[36];
1078
1150
  uint32_t assign_tag = 1; /* Assign */
1079
1151
  ts_memcpy(assign, &assign_tag, 4);
1080
- ts_memcpy(assign + 4, params->program_id, 32);
1152
+ ts_memcpy(assign + 4, owner, 32);
1081
1153
  SolInstruction assign_ix = {(SolPubkey *)&TS_SYSTEM_PROGRAM_ID, one, 1, assign, sizeof(assign)};
1082
1154
  TS_TRY(ts_invoke(params, &assign_ix, &signer, 1));
1083
1155
  }
1084
1156
 
1085
1157
  acct->data_len = space;
1086
- ts_memcpy(acct->data, disc, 8);
1087
1158
  *bump_out = bump;
1088
1159
  return SUCCESS;
1089
1160
  }
1090
1161
 
1162
+ /* Create `acct` as a PDA of this program, owned by it; writes the discriminator on success. */
1163
+ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccount *acct,
1164
+ SolSignerSeed *seeds, int n, const uint8_t disc[8], uint64_t space,
1165
+ uint8_t *bump_out) {
1166
+ TS_TRY(ts_create_pda_owned(params, payer, acct, seeds, n, params->program_id, space, bump_out));
1167
+ ts_memcpy(acct->data, disc, 8);
1168
+ return SUCCESS;
1169
+ }
1170
+
1091
1171
  /*
1092
1172
  * Create `acct` with `space` bytes owned by `owner` (a token program), funded by `payer`: a PDA of this program when
1093
1173
  * `n` > 0 (seeds without the bump; a pre-funded address is topped up, allocated and assigned), otherwise a new keypair
@@ -1239,6 +1319,15 @@ static inline uint64_t ts_resize(TsParams *params, TsAccount *payer, TsAccount *
1239
1319
  return SUCCESS;
1240
1320
  }
1241
1321
 
1322
+ /* resizeAccount(): the data length only (AccountInfo::resize), new bytes zeroed; no rent moves. */
1323
+ static inline uint64_t ts_resize_raw(TsAccount *acct, uint64_t new_len, uint64_t entry_len) {
1324
+ if (new_len > entry_len + MAX_PERMITTED_DATA_INCREASE)
1325
+ TS_FAIL(TS_ERR_REALLOC, "TypeSOL: account would grow more than 10 KiB in one instruction");
1326
+ if (new_len > acct->data_len) ts_memzero(acct->data + acct->data_len, new_len - acct->data_len);
1327
+ acct->data_len = new_len;
1328
+ return SUCCESS;
1329
+ }
1330
+
1242
1331
  /*
1243
1332
  * InitIfNeeded: create the PDA like ts_create_pda, or accept it when it already exists as this program's
1244
1333
  * account of the right type (owner, discriminator, size). The PDA is re-derived either way.
@@ -1511,7 +1600,12 @@ static const SolPubkey TS_INSTRUCTIONS_SYSVAR_ID = {{6,167,213,23,24,123,209,102
1511
1600
  * difference as uint8_t, so any difference is positive.)
1512
1601
  */
1513
1602
  static inline int ts_bytes_cmp(const uint8_t *a, const uint8_t *b, uint64_t n) {
1514
- for (uint64_t i = 0; i < n; i++)
1603
+ uint64_t i = 0;
1604
+ for (; i + 8 <= n; i += 8) {
1605
+ uint64_t x = ts_ld64(a + i), y = ts_ld64(b + i);
1606
+ if (x != y) return __builtin_bswap64(x) < __builtin_bswap64(y) ? -1 : 1;
1607
+ }
1608
+ for (; i < n; i++)
1515
1609
  if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1;
1516
1610
  return 0;
1517
1611
  }