@typesol/cli 0.27.0 → 0.29.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 (42) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +3 -1
  3. package/dist/compiler/analyze.d.ts +5 -1
  4. package/dist/compiler/analyze.js +53 -15
  5. package/dist/compiler/emit/alias.d.ts +48 -0
  6. package/dist/compiler/emit/alias.js +166 -0
  7. package/dist/compiler/emit/base.d.ts +1 -0
  8. package/dist/compiler/emit/borsh.js +6 -3
  9. package/dist/compiler/emit/calls.js +23 -4
  10. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  11. package/dist/compiler/emit/cpi-core.js +356 -0
  12. package/dist/compiler/emit/cpi.d.ts +10 -175
  13. package/dist/compiler/emit/cpi.js +71 -2716
  14. package/dist/compiler/emit/create.d.ts +39 -0
  15. package/dist/compiler/emit/create.js +548 -0
  16. package/dist/compiler/emit/function.d.ts +11 -2
  17. package/dist/compiler/emit/function.js +55 -12
  18. package/dist/compiler/emit/metaplex.d.ts +78 -0
  19. package/dist/compiler/emit/metaplex.js +1345 -0
  20. package/dist/compiler/emit/program.js +24 -4
  21. package/dist/compiler/emit/shared.d.ts +5 -1
  22. package/dist/compiler/emit/shared.js +11 -2
  23. package/dist/compiler/emit/statements.d.ts +0 -9
  24. package/dist/compiler/emit/statements.js +2 -53
  25. package/dist/compiler/emit/storage.d.ts +5 -20
  26. package/dist/compiler/emit/storage.js +55 -100
  27. package/dist/compiler/emit/token.d.ts +8 -0
  28. package/dist/compiler/emit/token.js +493 -0
  29. package/dist/compiler/idl.js +1 -1
  30. package/dist/compiler/model.d.ts +12 -2
  31. package/dist/compiler/model.js +7 -1
  32. package/dist/tools/portgen.js +3 -0
  33. package/docs/architecture.md +31 -2
  34. package/docs/audit.md +4 -2
  35. package/docs/case-study-multisig.md +169 -0
  36. package/docs/errors.md +6 -4
  37. package/docs/language.md +22 -6
  38. package/docs/migrate-from-anchor.md +7 -2
  39. package/docs/security-model.md +5 -1
  40. package/lib/typesol.d.ts +51 -7
  41. package/package.json +1 -1
  42. package/runtime/typesol_rt.h +93 -3
package/CHANGELOG.md CHANGED
@@ -6,6 +6,49 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.29.0 — 2026-10-30
10
+
11
+ The remaining Anchor gaps: declarative constraints in Anchor's order, Anchor's unbounded `Vec` in Borsh accounts, and
12
+ more than 32 accounts per instruction. Programs that use none of them compile to the same binaries as in 0.28.0.
13
+
14
+ - New: `export const MAX_ACCOUNTS = 128n` (33–255) lets a program's instructions take more than 32 accounts, as Anchor
15
+ programs can. Above 32 the CPI scratch lists live on the heap, grown as needed.
16
+
17
+ - New: `constraint(account, condition, error?)`, Anchor's `constraint = condition @ error`: statements at the start of
18
+ an instruction that run with that account's checks (after its `has_one`), so a transaction breaking several checks
19
+ gets Anchor's code. The default error is ConstraintRaw (2003).
20
+ - New: `Vec<T>` in a `@layout borsh` struct is Anchor's Vec: any field position, held on the heap while the instruction
21
+ runs (growing as Rust's does), bounded only by the account when it is written back (3004). Such a struct can be an
22
+ account or a whole argument (not return data or an event); `Init` of one takes its space. `typesol port` now writes
23
+ `Vec<T>` for Anchor's Vec fields instead of a `FixedVec` to size by hand.
24
+ - Changed: `push(value, payer)`'s payer is optional in the types (the compiler still requires it for a Vec that grows
25
+ the account), so a `Vec` assigns to a `FixedVec` without the earlier type workaround.
26
+ - Changed: examples/multisig.ts uses both; it now matches the mainnet program on 52 transactions, including one that
27
+ breaks two checks at once and an account holding 40 owners.
28
+ - Internal: `cpi.ts` split into `cpi-core`, `create`, `token`, `metaplex` and `cpi`; aliasing rules in `alias.ts`;
29
+ `scripts/codegen-snapshot.ts`; the IR decision in docs/architecture.md.
30
+
31
+ ## 0.28.0 — 2026-10-29
32
+
33
+ A port of coral-xyz/multisig, checked against the program deployed on mainnet, and the features it needed. The
34
+ benchmark programs compile to the same numbers as in 0.27.0.
35
+
36
+ - New: `invokeInstruction(programId, metas, data, infos, signerSeeds?)`, a CPI decided at run time (Rust's
37
+ `invoke_signed` of an `Instruction` built from data): metas are structs with `pubkey`, `isSigner`, `isWritable`, the
38
+ data a list of u8, and every account in `infos` (the remaining accounts or a slice) goes to the runtime.
39
+ - New: `Signed<A>`, Anchor's `signer` constraint on an account that is not a `Signer` (2002); the IDL marks it a signer.
40
+ - New: `Zeroed<T>` of a `@layout borsh` struct (Anchor's `#[account(zero)]` on a Borsh account): it starts empty and is
41
+ written as Borsh when the instruction returns.
42
+ - New: a Seeds bump stored in another struct account, `Seeds<A, ["@multisig"], "@multisig.nonce">` (Anchor's
43
+ `bump = multisig.nonce`).
44
+ - New: `list = vecArgument` copies a `Vec` argument (or another list of the same elements) into a `FixedVec` (5104 when
45
+ it does not fit).
46
+ - Changed: a `Zeroed<T>` account whose discriminator is already set fails with 2013 (ConstraintZero), checked before its
47
+ owner, as under Anchor; it was 3000 after the owner check.
48
+ - Changed: `key`, `lamports`, `dataLen`, `isSigner`, `isWritable` and `pdaBump` are refused as field names only in
49
+ structs held in an account (where they would shadow `acct.key` and the others), no longer in every struct.
50
+ - Docs: `docs/case-study-multisig.md`; the mainnet binary is in `test/programs/coral_multisig.so`.
51
+
9
52
  ## 0.27.0 — 2026-10-29
10
53
 
11
54
  Anchor 1.0 parity: instruction introspection, `Dup<…>` and account migration. Existing programs compile to the same
package/README.md CHANGED
@@ -175,7 +175,8 @@ program's address.
175
175
 
176
176
  Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, `typesol port`
177
177
  starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one complete Anchor
178
- program through the port. Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
178
+ program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
179
+ checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% 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
179
180
  mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
180
181
 
181
182
  ## How it works
@@ -323,6 +324,7 @@ Details are in [docs/testing.md](docs/testing.md).
323
324
  | [`relay.ts`](examples/relay.ts), [`caller.ts`](examples/caller.ts) | generic `invoke`, PDA-signed transfers, return data |
324
325
  | [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
325
326
  | [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
327
+ | [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
326
328
 
327
329
  ## Status
328
330
 
@@ -1,7 +1,9 @@
1
1
  import ts from "typescript";
2
2
  import { Reporter } from "./diagnostics.js";
3
- import { type DataEnumDef, type EnumDef, type GenericHelper, type Helper, type ProgramModel, type ScalarType, type StructDef, type ValueType, isScalar } from "./model.js";
3
+ import { type DataEnumDef, type EnumDef, type GenericHelper, type Helper, type ProgramModel, type ScalarType, type StructDef, type StructField, type ValueType, isScalar } from "./model.js";
4
4
  export declare const LIB_PATH: string;
5
+ /** A struct used as account data: none of its fields may shadow an account member. */
6
+ export declare function checkAccountMembers(s: StructDef, at: ts.Node, reporter: Reporter): void;
5
7
  /** Why a name cannot be used as a C member, or undefined when it can. */
6
8
  export declare function cNameProblem(name: string): string | undefined;
7
9
  /** Solana's account size limit, and what a program can allocate itself through a CPI (Init<T>). */
@@ -62,6 +64,8 @@ export declare function resolveOptionType(node: ts.TypeNode, scope: TypeScope):
62
64
  }) | undefined;
63
65
  /** Values a local, argument or helper parameter can hold. */
64
66
  export declare function resolveValueType(node: ts.TypeNode, scope: TypeScope, allowVec?: boolean): ValueType | undefined;
67
+ /** The first heap Vec<T> field of a struct (a Vec in a `@layout borsh` struct), if it has one. */
68
+ export declare function heapVecOf(s: StructDef): StructField | undefined;
65
69
  /** The helper (or generic) a call's callee names: a local function by its declaration, others by name. */
66
70
  export declare function calleeName(callee: ts.Identifier, decls: Map<ts.Node, string>, checker: ts.TypeChecker): string | undefined;
67
71
  export { isScalar };
@@ -8,7 +8,15 @@ import { borshIdentical } from "./emit/borsh.js";
8
8
  import { optionKey, INT_INFO, INT_NAMES, scalarKey, fixedVecName, isScalar, scalarSize, typeName, } from "./model.js";
9
9
  export const LIB_PATH = fileURLToPath(new URL("../../lib/typesol.d.ts", import.meta.url));
10
10
  /** Names a struct field may not use because account parameters already expose them. */
11
- const RESERVED_FIELDS = new Set(["key", "lamports", "dataLen", "create", "equals", "get", "set", "length", "isSigner", "isWritable", "pdaBump"]);
11
+ const RESERVED_FIELDS = new Set(["create", "equals", "get", "set", "length"]);
12
+ /** Members every account parameter has (`acct.key`, `acct.isSigner`, …): a struct held in an account cannot use them. */
13
+ const ACCOUNT_MEMBERS = new Set(["key", "lamports", "dataLen", "isSigner", "isWritable", "pdaBump"]);
14
+ /** A struct used as account data: none of its fields may shadow an account member. */
15
+ export function checkAccountMembers(s, at, reporter) {
16
+ const clash = s.fields.find((f) => ACCOUNT_MEMBERS.has(f.name));
17
+ if (clash)
18
+ reporter.fail(at, `${s.name}.${clash.name}: "${clash.name}" is an account member (acct.${clash.name}); rename the field to hold ${s.name} in an account`);
19
+ }
12
20
  /**
13
21
  * Struct fields and enum variants become C member names as written. C keywords and the object-like
14
22
  * macros of the Solana C SDK / TypeSOL runtime would break or silently change the generated C.
@@ -86,6 +94,7 @@ const TYPE_EXPORTS = new Set([
86
94
  "Owner",
87
95
  "Executable",
88
96
  "Dup",
97
+ "Signed",
89
98
  "Migrate",
90
99
  "Optional",
91
100
  "EventAuthority",
@@ -612,10 +621,13 @@ export function analyze(entry) {
612
621
  collectStructs(a.type, structs, dataEnums, seen);
613
622
  // A @layout borsh struct is decoded as a whole argument; inside lists or enums it would need a fixed size.
614
623
  const whole = a.type.kind === "structRef" ? a.type.struct : undefined;
615
- for (const s of seen)
624
+ for (const s of seen) {
616
625
  if (structs.get(s).layout === "borsh" && s !== whole)
617
626
  reporter.error(fn.node.name ?? fn.node, `argument ${a.name}: ${s} is @layout borsh; pass it as a whole argument, not inside a list or enum`);
627
+ }
618
628
  }
629
+ if (ix.returns?.kind === "struct" && heapVecOf(structs.get(ix.returns.name)))
630
+ reporter.error(fn.node.name ?? fn.node, `${ix.returns.name} holds a Vec<T>; return data takes a struct with FixedVec<T, N> instead`);
619
631
  // A returned struct goes out in its fixed layout, like an argument comes in: it cannot also be a Borsh event.
620
632
  if (ix.returns?.kind === "struct")
621
633
  collectStructs(ix.returns, structs, dataEnums, argStructs);
@@ -975,11 +987,12 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
975
987
  if (layoutTag && layoutText !== "borsh" && layoutText !== "fixed")
976
988
  reporter.fail(layoutTag, "@layout is borsh (Anchor's account bytes) or fixed (the default)");
977
989
  const growable = (f) => f.type.kind === "vec" && f.type.cap === undefined;
978
- // Anchor's bytes keep the declared order, so there a growable Vec has to be last (the fields after it would move).
990
+ // In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
991
+ // only by the account when it is written back.
979
992
  if (layoutText === "borsh")
980
- for (const f of fields.slice(0, -1))
993
+ for (const f of fields)
981
994
  if (growable(f))
982
- reporter.fail(f.node ?? decl, "in a @layout borsh struct a Vec<T> field must be the last field (Anchor's bytes keep the declared order); use FixedVec<T, N> for a list of at most N elsewhere");
995
+ f.type = { ...f.type, heap: true };
983
996
  // The fixed layout stores the growable Vecs after the fixed-size fields, in the order declared, so every other
984
997
  // field keeps a fixed offset; the IDL lists the fields in this stored order.
985
998
  const stored = layoutText === "borsh" ? fields : [...fields.filter((f) => !growable(f)), ...fields.filter(growable)];
@@ -1089,6 +1102,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1089
1102
  return 1 + e.payload;
1090
1103
  }
1091
1104
  case "vec": {
1105
+ if (t.heap)
1106
+ return 16; // TSH_*: u32 length, u32 capacity, a pointer to the elements on the heap
1092
1107
  if (t.cap === undefined)
1093
1108
  return 4; // the u32 length; elements live past the fixed part
1094
1109
  const e = sizeOf(t.elem, at);
@@ -1140,7 +1155,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1140
1155
  // Growable Vecs (stored last, see above): the first one's length and elements end the C struct; the others follow
1141
1156
  // it in the account, each a u32 length and its elements.
1142
1157
  for (const f of s.fields)
1143
- if (f.type.kind === "vec" && f.type.cap === undefined) {
1158
+ if (f.type.kind === "vec" && f.type.cap === undefined && !f.type.heap) {
1144
1159
  const elemSize = sizeOf(f.type.elem, s.node);
1145
1160
  if (elemSize === undefined)
1146
1161
  reporter.fail(s.node, "Vec elements must have a fixed size");
@@ -1260,6 +1275,10 @@ function references(l, decls, checker) {
1260
1275
  visit(l.node.body);
1261
1276
  return found;
1262
1277
  }
1278
+ /** The first heap Vec<T> field of a struct (a Vec in a `@layout borsh` struct), if it has one. */
1279
+ export function heapVecOf(s) {
1280
+ return s.fields.find((f) => f.type.kind === "vec" && f.type.heap);
1281
+ }
1263
1282
  /**
1264
1283
  * A `@layout borsh` struct: its own fields may be FixedString (Borsh String), FixedVec (Borsh Vec) and Option; anything
1265
1284
  * nested must already be Borsh-identical (fixed-size scalars, Pubkeys, enums, arrays and structs of them).
@@ -1280,8 +1299,12 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
1280
1299
  reporter.fail(at, `${t.name}.${v.name}.${vf.name} in a @layout borsh struct: enum variants hold fixed-size values and strings`);
1281
1300
  continue;
1282
1301
  }
1283
- if (t.kind === "vec" && t.cap === undefined)
1284
- reporter.fail(at, "a @layout borsh struct cannot end in a growable Vec<T>; use FixedVec<T, N> (Anchor's #[max_len(N)] Vec)");
1302
+ if (t.kind === "vec" && t.heap) {
1303
+ const e = t.elem;
1304
+ if (!fixed(e) || e.kind === "array")
1305
+ reporter.fail(at, `${typeName(t)} in a @layout borsh struct: its elements are integers, booleans, Pubkeys, unit enums or fixed-size structs`);
1306
+ continue;
1307
+ }
1285
1308
  if (t.kind === "vec" && (fixed(t.elem) || t.elem.kind === "fstring"))
1286
1309
  continue;
1287
1310
  if (t.kind === "option" && fixed(t.inner))
@@ -1341,7 +1364,8 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1341
1364
  wrapped === "Seeds" ||
1342
1365
  wrapped === "CloseTo" ||
1343
1366
  wrapped === "Address" ||
1344
- wrapped === "Ata")
1367
+ wrapped === "Ata" ||
1368
+ wrapped === "Signed")
1345
1369
  reporter.fail(p.type, "constraints belong on instruction parameters; helpers take the plain account type");
1346
1370
  const account = resolveAccountKind(p.type, reporter, scope.imports, structs);
1347
1371
  if (account.kind === "init" || account.kind === "initIfNeeded" || account.kind === "zeroed" || account.kind === "migrate")
@@ -1529,9 +1553,20 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1529
1553
  if (!accounts.some((o) => o.name === f))
1530
1554
  reporter.fail(a.node, `HasOne<…, "${f}">: add an account parameter named "${f}"`);
1531
1555
  }
1532
- if (c.seeds?.bump) {
1556
+ if (c.seeds?.bump?.startsWith("@")) {
1557
+ // "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`).
1558
+ const [owner, field, ...rest] = c.seeds.bump.slice(1).split(".");
1559
+ const o = accounts.find((x) => x.name === owner);
1560
+ const os = o?.kind.kind === "account" ? o.kind.struct : undefined;
1561
+ if (!os || !field || rest.length)
1562
+ reporter.fail(a.node, `Seeds bump: "${c.seeds.bump}" must name a u8 field of a struct account parameter ("@config.bump")`);
1563
+ const bf = os.fields.find((x) => x.name === field);
1564
+ if (!bf || bf.type.kind !== "int" || bf.type.name !== "u8")
1565
+ reporter.fail(a.node, `Seeds bump: ${os.name} needs a u8 field "${field}"`);
1566
+ }
1567
+ else if (c.seeds?.bump) {
1533
1568
  if (!struct)
1534
- reporter.fail(a.node, "Seeds with a bump field needs a struct account");
1569
+ reporter.fail(a.node, `Seeds with a bump field needs a struct account; for a bump stored elsewhere name it "@acct.field"`);
1535
1570
  const bf = struct.fields.find((x) => x.name === c.seeds.bump);
1536
1571
  if (!bf || bf.type.kind !== "int" || bf.type.name !== "u8")
1537
1572
  reporter.fail(a.node, `Seeds bump: ${struct.name} needs a u8 field "${c.seeds.bump}"`);
@@ -1562,6 +1597,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1562
1597
  ...c.hasOne.map((e) => e.split("=").at(-1)),
1563
1598
  ...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).split(".")[0]),
1564
1599
  ...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
1600
+ ...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
1565
1601
  ...(c.closeTo ? [c.closeTo] : []),
1566
1602
  ...(c.ata
1567
1603
  ? [c.ata.owner, c.ata.mint, ...(a.kind.kind === "token" ? [] : accounts.filter((o) => o.kind.kind === "tokenProgram").map((o) => o.name))]
@@ -1631,7 +1667,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1631
1667
  /** Peel HasOne / Seeds / CloseTo wrappers off a parameter type, recording what they ask for. */
1632
1668
  function unwrapConstraints(node, reporter, imports, out) {
1633
1669
  const name = typesolName(node, imports);
1634
- if (!["HasOne", "TokenOf", "MintOf", "Seeds", "CloseTo", "Address", "Ata", "Owner", "Executable", "Dup"].includes(name ?? ""))
1670
+ if (!["HasOne", "TokenOf", "MintOf", "Seeds", "CloseTo", "Address", "Ata", "Owner", "Executable", "Dup", "Signed"].includes(name ?? ""))
1635
1671
  return node;
1636
1672
  const args = node.typeArguments ?? [];
1637
1673
  const lit = (t) => {
@@ -1675,6 +1711,8 @@ function unwrapConstraints(node, reporter, imports, out) {
1675
1711
  out.executable = true;
1676
1712
  if (name === "Dup")
1677
1713
  out.dup = true;
1714
+ if (name === "Signed")
1715
+ out.signed = true;
1678
1716
  if (name === "Address") {
1679
1717
  const text = lit(args[1])[0];
1680
1718
  const bytes = text === undefined ? undefined : decodeAddress(text);
@@ -1719,6 +1757,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
1719
1757
  const s = ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) ? structs.get(t.typeName.text) : undefined;
1720
1758
  if (s && s.size === undefined)
1721
1759
  reporter.fail(t, `${s.name} has a variable-length string field and cannot be account data; use FixedString<N>`);
1760
+ if (s)
1761
+ checkAccountMembers(s, t, reporter);
1722
1762
  return s;
1723
1763
  };
1724
1764
  switch (outer) {
@@ -1831,9 +1871,7 @@ function resolveAccountKind(node, reporter, imports, structs) {
1831
1871
  if (!s)
1832
1872
  reporter.fail(node, "Zeroed<T> needs a struct declared in this program");
1833
1873
  if (s.vec)
1834
- reporter.fail(node, `${s.name} has a growable Vec; Zeroed<T> is for fixed-size (large) accounts`);
1835
- if (s.layout === "borsh")
1836
- reporter.fail(node, `${s.name} is @layout borsh; Zeroed<T> reads large accounts in place, so it takes fixed layouts only`);
1874
+ reporter.fail(node, `${s.name} has a growable Vec; Zeroed<T> is for fixed-size accounts (or @layout borsh with FixedVec)`);
1837
1875
  return { kind: "zeroed", struct: s };
1838
1876
  }
1839
1877
  case "Mut": {
@@ -0,0 +1,48 @@
1
+ import ts from "typescript";
2
+ import { type FieldType } from "../model.js";
3
+ import { EmitterBase } from "./base.js";
4
+ /**
5
+ * Aliasing, in one place. A struct read from account data is a reference into that data, not a copy, so code that
6
+ * replaces or moves the data under a reference still in use would let it read a value JS would not show. The rules:
7
+ *
8
+ * - `pathsOf` names the storage an expression refers to (`acct.a.b`, `v[]` for a Vec element, a reference local's
9
+ * paths); every reference local records its paths when it is declared (statements.ts).
10
+ * - `assertNotAliased(paths, at)` refuses replacing a place while a reference into it is read later (`usedAfter`).
11
+ * Called for: assigning a struct or list (statements.ts `assign`); `set` of a struct element of an array or Vec,
12
+ * `pop` and `clear` (calls.ts); any push / pop / clear that moves the growable Vecs stored after the one it resizes
13
+ * (calls.ts `tailStart`); a helper taking a writable struct account (calls.ts); `acct.migrate(…)` (calls.ts).
14
+ * - `mayResizeVecs(node)` decides whether evaluating a value may resize a growable Vec (moving the Vecs after it); an
15
+ * assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
16
+ *
17
+ * Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
18
+ * unless `Dup<…>` allows it for in-place accounts.
19
+ */
20
+ export declare abstract class AliasEmitter extends EmitterBase {
21
+ protected abstract peekKind(node: ts.Expression): FieldType["kind"] | undefined;
22
+ /**
23
+ * Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
24
+ * a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
25
+ */
26
+ protected pathsOf(node: ts.Expression): string[] | undefined;
27
+ /**
28
+ * In JS, replacing an object (`acct.pos = {...}`, `v.set(i, {...})`, `v.pop()`) leaves earlier references
29
+ * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
30
+ * value. Refuse when a live reference into the replaced place is still used afterwards.
31
+ */
32
+ protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string): void;
33
+ /**
34
+ * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
35
+ * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
36
+ * `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
37
+ */
38
+ protected usedAfter(decl: ts.VariableDeclaration | ts.ParameterDeclaration, at: ts.Node): boolean;
39
+ /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
40
+ protected writesThroughVec(node: ts.Expression): boolean;
41
+ protected helperTakesMutAccounts(node: ts.CallExpression): boolean;
42
+ /**
43
+ * Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
44
+ * realloc or close, a helper taking a writable account or a function argument, or a closure (its body is not
45
+ * looked into: it may capture the account). Conservative: it only decides whether a Vec element may be the target.
46
+ */
47
+ protected mayResizeVecs(node: ts.Node): boolean;
48
+ }
@@ -0,0 +1,166 @@
1
+ import ts from "typescript";
2
+ import { isWritable } from "../model.js";
3
+ import { EmitterBase } from "./base.js";
4
+ /**
5
+ * Aliasing, in one place. A struct read from account data is a reference into that data, not a copy, so code that
6
+ * replaces or moves the data under a reference still in use would let it read a value JS would not show. The rules:
7
+ *
8
+ * - `pathsOf` names the storage an expression refers to (`acct.a.b`, `v[]` for a Vec element, a reference local's
9
+ * paths); every reference local records its paths when it is declared (statements.ts).
10
+ * - `assertNotAliased(paths, at)` refuses replacing a place while a reference into it is read later (`usedAfter`).
11
+ * Called for: assigning a struct or list (statements.ts `assign`); `set` of a struct element of an array or Vec,
12
+ * `pop` and `clear` (calls.ts); any push / pop / clear that moves the growable Vecs stored after the one it resizes
13
+ * (calls.ts `tailStart`); a helper taking a writable struct account (calls.ts); `acct.migrate(…)` (calls.ts).
14
+ * - `mayResizeVecs(node)` decides whether evaluating a value may resize a growable Vec (moving the Vecs after it); an
15
+ * assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
16
+ *
17
+ * Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
18
+ * unless `Dup<…>` allows it for in-place accounts.
19
+ */
20
+ export class AliasEmitter extends EmitterBase {
21
+ /**
22
+ * Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
23
+ * a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
24
+ */
25
+ pathsOf(node) {
26
+ if (ts.isParenthesizedExpression(node))
27
+ return this.pathsOf(node.expression);
28
+ if (ts.isIdentifier(node)) {
29
+ const l = this.lookup(node.text);
30
+ if (l)
31
+ return l.paths ?? (l.type.kind === "array" ? [`@${l.c}`] : undefined);
32
+ return this.accounts.has(node.text) ? [node.text] : undefined;
33
+ }
34
+ if (ts.isPropertyAccessExpression(node))
35
+ return this.pathsOf(node.expression)?.map((p) => `${p}.${node.name.text}`);
36
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "get")
37
+ return this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`);
38
+ if (ts.isConditionalExpression(node)) {
39
+ const a = this.pathsOf(node.whenTrue);
40
+ const b = this.pathsOf(node.whenFalse);
41
+ return a && b ? [...a, ...b] : undefined;
42
+ }
43
+ return undefined;
44
+ }
45
+ /**
46
+ * In JS, replacing an object (`acct.pos = {...}`, `v.set(i, {...})`, `v.pop()`) leaves earlier references
47
+ * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
48
+ * value. Refuse when a live reference into the replaced place is still used afterwards.
49
+ */
50
+ assertNotAliased(replaced, at, helper) {
51
+ if (!replaced)
52
+ return;
53
+ for (const scope of this.scopes)
54
+ for (const [name, l] of scope) {
55
+ if (!l.paths || !l.decl)
56
+ continue;
57
+ const hit = replaced.find((r) => l.paths.some((p) => p === r || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
58
+ if (!hit || !this.usedAfter(l.decl, at))
59
+ continue;
60
+ this.fail(at, helper
61
+ ? `"${name}" still refers to data in ${hit}, and ${helper}() may replace it (then "${name}" would read the new value; in JS it keeps the old one). Copy the fields you need into locals first`
62
+ : `"${name}" still refers to ${hit}; replacing it here would change what "${name}" reads (in JS it keeps the old value). Copy the fields you need into locals first`);
63
+ }
64
+ }
65
+ /**
66
+ * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
67
+ * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
68
+ * `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
69
+ */
70
+ usedAfter(decl, at) {
71
+ const symbol = this.checker.getSymbolAtLocation(decl.name);
72
+ if (!symbol)
73
+ return true;
74
+ if (ts.isParameter(decl)) {
75
+ const fn = decl.parent;
76
+ const inside = at.getSourceFile() === fn.getSourceFile() && at.pos >= fn.pos && at.end <= fn.end;
77
+ let read = false;
78
+ const visitParam = (n) => {
79
+ if (read)
80
+ return;
81
+ if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
82
+ if (!inside || n.pos >= at.end)
83
+ read = true;
84
+ // A loop inside the function, around `at`, reads it again on its next turn.
85
+ for (let p = at.parent; inside && p && p !== fn; p = p.parent)
86
+ if ((ts.isForStatement(p) || ts.isForOfStatement(p) || ts.isWhileStatement(p) || ts.isDoStatement(p)) && n.pos >= p.pos && n.end <= p.end)
87
+ read = true;
88
+ }
89
+ ts.forEachChild(n, visitParam);
90
+ };
91
+ const body = fn.body;
92
+ if (body)
93
+ visitParam(body);
94
+ return read;
95
+ }
96
+ // Loops around `at` that do not also contain the declaration run their earlier statements again later.
97
+ let loop;
98
+ for (let n = at.parent; n && n !== decl.parent; n = n.parent)
99
+ if ((ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n)) && !(decl.pos >= n.pos && decl.end <= n.end))
100
+ loop = n;
101
+ let found = false;
102
+ const scope = decl.parent.parent.parent; // VariableDeclaration -> List -> Statement -> enclosing block
103
+ const visit = (n) => {
104
+ if (found)
105
+ return;
106
+ if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
107
+ if (n.pos >= at.end || (loop && n.pos >= loop.pos && n.end <= loop.end))
108
+ found = true;
109
+ }
110
+ ts.forEachChild(n, visit);
111
+ };
112
+ visit(scope);
113
+ return found;
114
+ }
115
+ /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
116
+ writesThroughVec(node) {
117
+ for (let n = node;;) {
118
+ if (ts.isParenthesizedExpression(n))
119
+ n = n.expression;
120
+ else if (ts.isPropertyAccessExpression(n))
121
+ n = n.expression;
122
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get") {
123
+ if (this.peekKind(n.expression.expression) === "vec")
124
+ return true;
125
+ n = n.expression.expression;
126
+ }
127
+ else
128
+ return false;
129
+ }
130
+ }
131
+ helperTakesMutAccounts(node) {
132
+ const h = this.helperOf(node);
133
+ return !!h?.params.some((p) => p.account && isWritable(p.account));
134
+ }
135
+ /**
136
+ * Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
137
+ * realloc or close, a helper taking a writable account or a function argument, or a closure (its body is not
138
+ * looked into: it may capture the account). Conservative: it only decides whether a Vec element may be the target.
139
+ */
140
+ mayResizeVecs(node) {
141
+ let found = false;
142
+ const isClosure = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e) || (ts.isIdentifier(e) && !!this.lookup(e.text)?.closure);
143
+ const visit = (n) => {
144
+ if (found)
145
+ return;
146
+ if (ts.isCallExpression(n)) {
147
+ const callee = n.expression;
148
+ if (ts.isPropertyAccessExpression(callee) && ["push", "pop", "clear"].includes(callee.name.text))
149
+ found = true;
150
+ else if (ts.isCallExpression(callee))
151
+ found = true; // a function a function returns
152
+ else if (ts.isIdentifier(callee)) {
153
+ if (this.lookup(callee.text)?.closure)
154
+ found = true;
155
+ else if (["realloc", "close"].includes(this.exportName(callee) ?? ""))
156
+ found = true;
157
+ else if (this.helperOf(n) && (this.helperTakesMutAccounts(n) || n.arguments.some(isClosure)))
158
+ found = true;
159
+ }
160
+ }
161
+ ts.forEachChild(n, visit);
162
+ };
163
+ visit(node);
164
+ return found;
165
+ }
166
+ }
@@ -131,6 +131,7 @@ export declare abstract class EmitterBase {
131
131
  protected abstract coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
132
132
  protected abstract bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
133
133
  protected abstract invoke(node: ts.CallExpression): undefined;
134
+ protected abstract invokeInstruction(node: ts.CallExpression): undefined;
134
135
  protected abstract emitEvent(node: ts.CallExpression, cpi?: {
135
136
  authority: string;
136
137
  program: string;
@@ -106,10 +106,13 @@ export function emitBorshCodecs(model) {
106
106
  }
107
107
  case "vec": {
108
108
  const l = tmp("n");
109
+ // A heap Vec (Anchor's Vec<T>) gets room on the heap for what the bytes hold; a FixedVec has its capacity.
109
110
  const head = [
110
111
  `${pad}uint32_t ${l} = (uint32_t)ts_read_le(src + at, 4);`,
111
112
  `${pad}at += 4;`,
112
- `${pad}if (${l} > ${t.cap}) ${DESER};`,
113
+ ...(t.heap
114
+ ? [need(`(uint64_t)${l} * ${fixedBytes(t.elem, model)}`, rest, pad), `${pad}TS_TRY(ts_hvec_reserve(&${lv}, ${l}, ${fixedBytes(t.elem, model)}));`]
115
+ : [`${pad}if (${l} > ${t.cap}) ${DESER};`]),
113
116
  `${pad}${lv}.len = ${l};`,
114
117
  ];
115
118
  if (borshIdentical(t.elem, model)) {
@@ -207,7 +210,7 @@ export function emitBorshCodecs(model) {
207
210
  if (borshIdentical(t.elem, model)) {
208
211
  const n = fixedBytes(t.elem, model);
209
212
  return [
210
- `${pad}uint32_t ${l} = ${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len;`,
213
+ `${pad}uint32_t ${l} = ${t.heap ? `${lv}.len` : `${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len`};`,
211
214
  room(`4 + (uint64_t)${l} * ${n}`, rest, pad),
212
215
  `${pad}ts_write_le(dst + at, ${l}, 4);`,
213
216
  `${pad}ts_memcpy(dst + at + 4, ${lv}.items, (uint64_t)${l} * ${n});`,
@@ -216,7 +219,7 @@ export function emitBorshCodecs(model) {
216
219
  }
217
220
  const i = tmp("i");
218
221
  return [
219
- `${pad}uint32_t ${l} = ${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len;`,
222
+ `${pad}uint32_t ${l} = ${t.heap ? `${lv}.len` : `${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len`};`,
220
223
  room("4", rest, pad),
221
224
  `${pad}ts_write_le(dst + at, ${l}, 4);`,
222
225
  `${pad}at += 4;`,
@@ -26,6 +26,8 @@ export class CallEmitter extends ExpressionEmitter {
26
26
  this.fail(node, "stackHeight() takes no arguments");
27
27
  return { c: "sol_get_stack_height()", type: U64 };
28
28
  }
29
+ case "constraint":
30
+ this.fail(node, "constraint(account, condition, error?) goes at the start of an instruction's body, before any other statement");
29
31
  case "require": {
30
32
  if (args.length !== 2)
31
33
  this.fail(node, "require(condition, error) takes two arguments");
@@ -288,6 +290,8 @@ export class CallEmitter extends ExpressionEmitter {
288
290
  }
289
291
  case "invoke":
290
292
  return this.invoke(node);
293
+ case "invokeInstruction":
294
+ return this.invokeInstruction(node);
291
295
  case "sha256":
292
296
  case "keccak256":
293
297
  return this.hashCall(node, builtin);
@@ -641,8 +645,8 @@ export class CallEmitter extends ExpressionEmitter {
641
645
  // Elements removed or replaced here must not be referenced afterwards.
642
646
  const elemPaths = () => (ts.isPropertyAccessExpression(node.expression) ? this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`) : undefined);
643
647
  const resize = (newLen, payer) => {
644
- if (info.cap !== undefined)
645
- return; // a FixedVec has its room already
648
+ if (info.cap !== undefined || info.heap)
649
+ return; // a FixedVec has its room already; a heap Vec is not in the account
646
650
  if (!info.resizable || !v.account)
647
651
  this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
648
652
  this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
@@ -676,6 +680,21 @@ export class CallEmitter extends ExpressionEmitter {
676
680
  return undefined;
677
681
  }
678
682
  case "push": {
683
+ if (info.heap) {
684
+ // A Vec in a @layout borsh account: room on the heap, which may move the elements (no references may
685
+ // outlive it); the account bounds the list when it is written back (3004), as under Anchor.
686
+ if (args.length !== 1)
687
+ this.fail(node, "push(value) on a Vec of a @layout borsh account takes the value only (the account is resized by realloc)");
688
+ needWritable();
689
+ this.assertNotAliased(elemPaths(), node);
690
+ const write = stageElem(args[0]);
691
+ const n = this.tmp("n");
692
+ this.line(`uint64_t ${n} = (uint64_t)${info.len};`);
693
+ this.line(`TS_TRY(ts_hvec_reserve(&${info.len.replace(/\.len$/, "")}, ${n} + 1, ${info.elemSize}));`);
694
+ this.line(`${info.len} = (uint32_t)(${n} + 1);`);
695
+ write(elemRef(n));
696
+ return undefined;
697
+ }
679
698
  if (info.cap !== undefined) {
680
699
  if (args.length !== 1)
681
700
  this.fail(node, "push(value) on a FixedVec takes the value (it has room for its capacity already)");
@@ -731,7 +750,7 @@ export class CallEmitter extends ExpressionEmitter {
731
750
  this.line(`${valueC(st)} ${out} = ${val.c};`);
732
751
  result = st.kind === "pubkey" ? { c: `(&${out})`, type: st } : { c: out, type: st };
733
752
  }
734
- const t = info.cap === undefined ? tailStart() : undefined;
753
+ const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
735
754
  if (t)
736
755
  this.line(`ts_memmove(${t.at} - ${info.elemSize}, ${t.at}, ${t.n});`);
737
756
  this.line(`${info.len} = (uint32_t)(${n} - 1);`);
@@ -743,7 +762,7 @@ export class CallEmitter extends ExpressionEmitter {
743
762
  this.fail(node, "clear() takes no arguments");
744
763
  needWritable();
745
764
  this.assertNotAliased(elemPaths(), node);
746
- const t = info.cap === undefined ? tailStart() : undefined;
765
+ const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
747
766
  if (t)
748
767
  this.line(`ts_memmove((uint8_t *)${info.items}, ${t.at}, ${t.n});`);
749
768
  this.line(`${info.len} = 0;`);