@typesol/cli 0.28.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.
- package/CHANGELOG.md +22 -0
- package/README.md +1 -1
- package/dist/compiler/analyze.d.ts +3 -1
- package/dist/compiler/analyze.js +21 -7
- package/dist/compiler/emit/alias.d.ts +48 -0
- package/dist/compiler/emit/alias.js +166 -0
- package/dist/compiler/emit/borsh.js +6 -3
- package/dist/compiler/emit/calls.js +21 -4
- package/dist/compiler/emit/cpi-core.d.ts +70 -0
- package/dist/compiler/emit/cpi-core.js +356 -0
- package/dist/compiler/emit/cpi.d.ts +3 -177
- package/dist/compiler/emit/cpi.js +13 -2721
- package/dist/compiler/emit/create.d.ts +39 -0
- package/dist/compiler/emit/create.js +548 -0
- package/dist/compiler/emit/function.d.ts +11 -2
- package/dist/compiler/emit/function.js +42 -7
- package/dist/compiler/emit/metaplex.d.ts +78 -0
- package/dist/compiler/emit/metaplex.js +1345 -0
- package/dist/compiler/emit/program.js +24 -4
- package/dist/compiler/emit/shared.d.ts +5 -1
- package/dist/compiler/emit/shared.js +11 -2
- package/dist/compiler/emit/statements.d.ts +0 -9
- package/dist/compiler/emit/statements.js +2 -53
- package/dist/compiler/emit/storage.d.ts +5 -20
- package/dist/compiler/emit/storage.js +40 -106
- package/dist/compiler/emit/token.d.ts +8 -0
- package/dist/compiler/emit/token.js +493 -0
- package/dist/compiler/model.d.ts +10 -2
- package/dist/compiler/model.js +7 -1
- package/dist/tools/portgen.js +3 -0
- package/docs/architecture.md +29 -1
- package/docs/audit.md +3 -2
- package/docs/case-study-multisig.md +31 -29
- package/docs/errors.md +3 -2
- package/docs/language.md +4 -3
- package/docs/migrate-from-anchor.md +3 -3
- package/docs/security-model.md +1 -1
- package/lib/typesol.d.ts +17 -6
- package/package.json +1 -1
- package/runtime/typesol_rt.h +85 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,28 @@ 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
|
+
|
|
9
31
|
## 0.28.0 — 2026-10-29
|
|
10
32
|
|
|
11
33
|
A port of coral-xyz/multisig, checked against the program deployed on mainnet, and the features it needed. The
|
package/README.md
CHANGED
|
@@ -176,7 +176,7 @@ program's address.
|
|
|
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
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;
|
|
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
|
|
180
180
|
mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
|
|
181
181
|
|
|
182
182
|
## How it works
|
|
@@ -1,6 +1,6 @@
|
|
|
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
5
|
/** A struct used as account data: none of its fields may shadow an account member. */
|
|
6
6
|
export declare function checkAccountMembers(s: StructDef, at: ts.Node, reporter: Reporter): void;
|
|
@@ -64,6 +64,8 @@ export declare function resolveOptionType(node: ts.TypeNode, scope: TypeScope):
|
|
|
64
64
|
}) | undefined;
|
|
65
65
|
/** Values a local, argument or helper parameter can hold. */
|
|
66
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;
|
|
67
69
|
/** The helper (or generic) a call's callee names: a local function by its declaration, others by name. */
|
|
68
70
|
export declare function calleeName(callee: ts.Identifier, decls: Map<ts.Node, string>, checker: ts.TypeChecker): string | undefined;
|
|
69
71
|
export { isScalar };
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -621,10 +621,13 @@ export function analyze(entry) {
|
|
|
621
621
|
collectStructs(a.type, structs, dataEnums, seen);
|
|
622
622
|
// A @layout borsh struct is decoded as a whole argument; inside lists or enums it would need a fixed size.
|
|
623
623
|
const whole = a.type.kind === "structRef" ? a.type.struct : undefined;
|
|
624
|
-
for (const s of seen)
|
|
624
|
+
for (const s of seen) {
|
|
625
625
|
if (structs.get(s).layout === "borsh" && s !== whole)
|
|
626
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
|
+
}
|
|
627
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`);
|
|
628
631
|
// A returned struct goes out in its fixed layout, like an argument comes in: it cannot also be a Borsh event.
|
|
629
632
|
if (ix.returns?.kind === "struct")
|
|
630
633
|
collectStructs(ix.returns, structs, dataEnums, argStructs);
|
|
@@ -984,11 +987,12 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
984
987
|
if (layoutTag && layoutText !== "borsh" && layoutText !== "fixed")
|
|
985
988
|
reporter.fail(layoutTag, "@layout is borsh (Anchor's account bytes) or fixed (the default)");
|
|
986
989
|
const growable = (f) => f.type.kind === "vec" && f.type.cap === undefined;
|
|
987
|
-
//
|
|
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.
|
|
988
992
|
if (layoutText === "borsh")
|
|
989
|
-
for (const f of fields
|
|
993
|
+
for (const f of fields)
|
|
990
994
|
if (growable(f))
|
|
991
|
-
|
|
995
|
+
f.type = { ...f.type, heap: true };
|
|
992
996
|
// The fixed layout stores the growable Vecs after the fixed-size fields, in the order declared, so every other
|
|
993
997
|
// field keeps a fixed offset; the IDL lists the fields in this stored order.
|
|
994
998
|
const stored = layoutText === "borsh" ? fields : [...fields.filter((f) => !growable(f)), ...fields.filter(growable)];
|
|
@@ -1098,6 +1102,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1098
1102
|
return 1 + e.payload;
|
|
1099
1103
|
}
|
|
1100
1104
|
case "vec": {
|
|
1105
|
+
if (t.heap)
|
|
1106
|
+
return 16; // TSH_*: u32 length, u32 capacity, a pointer to the elements on the heap
|
|
1101
1107
|
if (t.cap === undefined)
|
|
1102
1108
|
return 4; // the u32 length; elements live past the fixed part
|
|
1103
1109
|
const e = sizeOf(t.elem, at);
|
|
@@ -1149,7 +1155,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
|
|
|
1149
1155
|
// Growable Vecs (stored last, see above): the first one's length and elements end the C struct; the others follow
|
|
1150
1156
|
// it in the account, each a u32 length and its elements.
|
|
1151
1157
|
for (const f of s.fields)
|
|
1152
|
-
if (f.type.kind === "vec" && f.type.cap === undefined) {
|
|
1158
|
+
if (f.type.kind === "vec" && f.type.cap === undefined && !f.type.heap) {
|
|
1153
1159
|
const elemSize = sizeOf(f.type.elem, s.node);
|
|
1154
1160
|
if (elemSize === undefined)
|
|
1155
1161
|
reporter.fail(s.node, "Vec elements must have a fixed size");
|
|
@@ -1269,6 +1275,10 @@ function references(l, decls, checker) {
|
|
|
1269
1275
|
visit(l.node.body);
|
|
1270
1276
|
return found;
|
|
1271
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
|
+
}
|
|
1272
1282
|
/**
|
|
1273
1283
|
* A `@layout borsh` struct: its own fields may be FixedString (Borsh String), FixedVec (Borsh Vec) and Option; anything
|
|
1274
1284
|
* nested must already be Borsh-identical (fixed-size scalars, Pubkeys, enums, arrays and structs of them).
|
|
@@ -1289,8 +1299,12 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
|
|
|
1289
1299
|
reporter.fail(at, `${t.name}.${v.name}.${vf.name} in a @layout borsh struct: enum variants hold fixed-size values and strings`);
|
|
1290
1300
|
continue;
|
|
1291
1301
|
}
|
|
1292
|
-
if (t.kind === "vec" && t.
|
|
1293
|
-
|
|
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
|
+
}
|
|
1294
1308
|
if (t.kind === "vec" && (fixed(t.elem) || t.elem.kind === "fstring"))
|
|
1295
1309
|
continue;
|
|
1296
1310
|
if (t.kind === "option" && fixed(t.inner))
|
|
@@ -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
|
+
}
|
|
@@ -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
|
-
|
|
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");
|
|
@@ -643,8 +645,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
643
645
|
// Elements removed or replaced here must not be referenced afterwards.
|
|
644
646
|
const elemPaths = () => (ts.isPropertyAccessExpression(node.expression) ? this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`) : undefined);
|
|
645
647
|
const resize = (newLen, payer) => {
|
|
646
|
-
if (info.cap !== undefined)
|
|
647
|
-
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
|
|
648
650
|
if (!info.resizable || !v.account)
|
|
649
651
|
this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
|
|
650
652
|
this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
|
|
@@ -678,6 +680,21 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
678
680
|
return undefined;
|
|
679
681
|
}
|
|
680
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
|
+
}
|
|
681
698
|
if (info.cap !== undefined) {
|
|
682
699
|
if (args.length !== 1)
|
|
683
700
|
this.fail(node, "push(value) on a FixedVec takes the value (it has room for its capacity already)");
|
|
@@ -733,7 +750,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
733
750
|
this.line(`${valueC(st)} ${out} = ${val.c};`);
|
|
734
751
|
result = st.kind === "pubkey" ? { c: `(&${out})`, type: st } : { c: out, type: st };
|
|
735
752
|
}
|
|
736
|
-
const t = info.cap === undefined ? tailStart() : undefined;
|
|
753
|
+
const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
|
|
737
754
|
if (t)
|
|
738
755
|
this.line(`ts_memmove(${t.at} - ${info.elemSize}, ${t.at}, ${t.n});`);
|
|
739
756
|
this.line(`${info.len} = (uint32_t)(${n} - 1);`);
|
|
@@ -745,7 +762,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
745
762
|
this.fail(node, "clear() takes no arguments");
|
|
746
763
|
needWritable();
|
|
747
764
|
this.assertNotAliased(elemPaths(), node);
|
|
748
|
-
const t = info.cap === undefined ? tailStart() : undefined;
|
|
765
|
+
const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
|
|
749
766
|
if (t)
|
|
750
767
|
this.line(`ts_memmove((uint8_t *)${info.items}, ${t.at}, ${t.n});`);
|
|
751
768
|
this.line(`${info.len} = 0;`);
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { type AccountParam, type IdlSeed } from "../model.js";
|
|
3
|
+
import { type Value } from "./shared.js";
|
|
4
|
+
import { CallEmitter } from "./calls.js";
|
|
5
|
+
/** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
|
|
6
|
+
export declare abstract class CpiCoreEmitter extends CallEmitter {
|
|
7
|
+
/**
|
|
8
|
+
* Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
|
|
9
|
+
* the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
|
|
10
|
+
*/
|
|
11
|
+
protected seeds(node: ts.Expression, extra: number): {
|
|
12
|
+
name: string;
|
|
13
|
+
count: number;
|
|
14
|
+
idl: IdlSeed[] | undefined;
|
|
15
|
+
};
|
|
16
|
+
protected describeSeed(el: ts.Expression): IdlSeed | undefined;
|
|
17
|
+
protected recordPda(account: AccountParam, idl: IdlSeed[] | undefined): void;
|
|
18
|
+
/**
|
|
19
|
+
* Emit a CPI to the program account `program` with these metas (account, writable, signer), and then (`tail`) a range
|
|
20
|
+
* of the remaining accounts, read-only (a Merkle proof).
|
|
21
|
+
*/
|
|
22
|
+
protected cpi(program: string, metas: [string, boolean, boolean][], buf: string, len: string, seeds: {
|
|
23
|
+
name: string;
|
|
24
|
+
count: number | string;
|
|
25
|
+
}, tail?: {
|
|
26
|
+
from: string;
|
|
27
|
+
to: string;
|
|
28
|
+
asPassed?: boolean;
|
|
29
|
+
}): void;
|
|
30
|
+
protected signerSeeds(node: ts.Expression | undefined, authority: AccountParam, at: ts.Node): {
|
|
31
|
+
name: string;
|
|
32
|
+
count: number | string;
|
|
33
|
+
};
|
|
34
|
+
/** Seeds to sign a CPI with: an array literal, or a helper's SignerSeeds parameter. */
|
|
35
|
+
protected signingSeeds(node: ts.Expression): {
|
|
36
|
+
name: string;
|
|
37
|
+
count: number | string;
|
|
38
|
+
};
|
|
39
|
+
/** Object literal properties by name, refusing others. */
|
|
40
|
+
protected literalProps(o: ts.ObjectLiteralExpression, allowed: string[], what: string): Map<string, ts.Expression>;
|
|
41
|
+
/** `acct.key` of an account parameter, as an expression to serialize. */
|
|
42
|
+
protected keyOf(n: ts.Expression): ts.Expression;
|
|
43
|
+
/**
|
|
44
|
+
* `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
|
|
45
|
+
* (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
|
|
46
|
+
*/
|
|
47
|
+
protected remainingRange(node: ts.Expression): {
|
|
48
|
+
from: string;
|
|
49
|
+
to: string;
|
|
50
|
+
} | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* A byte buffer written front to back. Its C declaration is patched in afterwards so it is
|
|
53
|
+
* exactly as large as the fixed content, and only falls back to `max` when strings make it dynamic.
|
|
54
|
+
*/
|
|
55
|
+
protected byteBuffer(prefix: string, max: number, errorCode: string, what: string): {
|
|
56
|
+
buf: string;
|
|
57
|
+
len: string;
|
|
58
|
+
put: (src: string, n: string, bytes?: number) => void;
|
|
59
|
+
finish: (at: ts.Node) => void;
|
|
60
|
+
};
|
|
61
|
+
/** Append a value's Borsh encoding through `put(srcPointer, byteCount)`. */
|
|
62
|
+
protected serialize(v: Value, node: ts.Node, put: (src: string, n: string, bytes?: number) => void): void;
|
|
63
|
+
/** Borsh-encode a data-enum place: the tag byte, then the active variant's fields. */
|
|
64
|
+
protected serializeDataEnum(node: ts.Expression, name: string, put: (src: string, n: string, bytes?: number) => void): void;
|
|
65
|
+
protected serializeDataEnumLv(lv: string, name: string, put: (src: string, n: string, bytes?: number) => void): void;
|
|
66
|
+
/** Structs reachable through the fields of struct `name` (not including itself unless it recurses). */
|
|
67
|
+
protected nestedStructs(name: string): Set<string>;
|
|
68
|
+
/** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
|
|
69
|
+
protected fixedLayoutStructs(): Set<string>;
|
|
70
|
+
}
|