@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.
- package/CHANGELOG.md +327 -2
- package/README.md +29 -15
- package/SECURITY.md +1 -1
- package/dist/compiler/analyze.d.ts +6 -11
- package/dist/compiler/analyze.js +323 -31
- package/dist/compiler/emit/alias.js +3 -2
- package/dist/compiler/emit/base.d.ts +5 -0
- package/dist/compiler/emit/base.js +2 -0
- package/dist/compiler/emit/borsh.js +63 -2
- package/dist/compiler/emit/calls.d.ts +9 -1
- package/dist/compiler/emit/calls.js +147 -18
- package/dist/compiler/emit/cpi-core.js +17 -5
- package/dist/compiler/emit/cpi.js +81 -27
- package/dist/compiler/emit/create.d.ts +7 -0
- package/dist/compiler/emit/create.js +27 -0
- package/dist/compiler/emit/expressions.js +7 -4
- package/dist/compiler/emit/function.d.ts +7 -0
- package/dist/compiler/emit/function.js +164 -29
- package/dist/compiler/emit/program.js +15 -2
- package/dist/compiler/emit/shared.d.ts +5 -5
- package/dist/compiler/emit/shared.js +5 -0
- package/dist/compiler/emit/statements.d.ts +8 -0
- package/dist/compiler/emit/statements.js +93 -6
- package/dist/compiler/emit/storage.d.ts +10 -1
- package/dist/compiler/emit/storage.js +50 -11
- package/dist/compiler/idl.d.ts +1 -1
- package/dist/compiler/idl.js +42 -11
- package/dist/compiler/model.d.ts +47 -10
- package/dist/compiler/model.js +14 -4
- package/dist/testing.js +8 -0
- package/dist/tools/clientgen.js +10 -1
- package/dist/tools/portgen.d.ts +6 -0
- package/dist/tools/portgen.js +68 -17
- package/docs/architecture.md +5 -4
- package/docs/audit.md +31 -19
- package/docs/case-study-escrow.md +5 -5
- package/docs/case-study-jito-mev.md +9 -5
- package/docs/case-study-marginfi.md +797 -0
- package/docs/case-study-multisig.md +3 -3
- package/docs/case-study-raydium-clmm.md +44 -33
- package/docs/case-study-raydium-cp-swap.md +3 -3
- package/docs/cli.md +5 -5
- package/docs/client.md +1 -1
- package/docs/errors.md +13 -5
- package/docs/language.md +38 -25
- package/docs/migrate-from-anchor.md +4 -1
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +2 -1
- package/docs/testing.md +33 -1
- package/lib/typesol.d.ts +46 -9
- package/package.json +9 -7
- package/runtime/typesol_rt.h +111 -17
|
@@ -34,6 +34,8 @@ export class EmitterBase {
|
|
|
34
34
|
inlining = new Set();
|
|
35
35
|
/** Enclosing loops, innermost last; each has a `continue` label. */
|
|
36
36
|
loops = [];
|
|
37
|
+
/** loadAccountMut calls whose claim a loop drops at each iteration's end: the C variable that records it. */
|
|
38
|
+
claimSlots = new Map();
|
|
37
39
|
ix;
|
|
38
40
|
helper;
|
|
39
41
|
/** Type names in effect (a generic helper expanded where it is called binds its type parameters here). */
|
|
@@ -49,18 +49,27 @@ export function borshMinSize(s, model) {
|
|
|
49
49
|
n += 4;
|
|
50
50
|
else if (t.kind === "option" || t.kind === "dataEnum")
|
|
51
51
|
n += 1;
|
|
52
|
+
else if (t.kind === "struct" && !borshIdentical(t, model))
|
|
53
|
+
n += borshMinSize(model.structs.get(t.name), model);
|
|
52
54
|
else
|
|
53
55
|
n += fixedBytes(t, model);
|
|
54
56
|
}
|
|
55
57
|
return n;
|
|
56
58
|
}
|
|
59
|
+
/** A struct (not itself @layout borsh) whose Borsh form is variable: it holds an Option, at any depth. */
|
|
60
|
+
function variableStruct(t, model) {
|
|
61
|
+
if (t.kind !== "struct" || borshIdentical(t, model))
|
|
62
|
+
return undefined;
|
|
63
|
+
const s = model.structs.get(t.name);
|
|
64
|
+
return s && s.layout !== "borsh" ? s : undefined;
|
|
65
|
+
}
|
|
57
66
|
const DESER = `TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: bytes are not a valid Borsh value")`;
|
|
58
67
|
const SER = `TS_FAIL(TS_ERR_DID_NOT_SERIALIZE, "TypeSOL: account data too small for the value")`;
|
|
59
68
|
/** C for `ts_unpack_<S>` and `ts_pack_<S>` of every `@layout borsh` struct. */
|
|
60
69
|
export function emitBorshCodecs(model) {
|
|
61
70
|
const out = [];
|
|
62
71
|
for (const s of model.structs.values()) {
|
|
63
|
-
if (s.layout !== "borsh" || s.size === undefined)
|
|
72
|
+
if ((s.layout !== "borsh" && s.wire !== "borsh") || s.size === undefined)
|
|
64
73
|
continue;
|
|
65
74
|
let k = 0;
|
|
66
75
|
const tmp = (p) => `${p}${k++}`;
|
|
@@ -84,7 +93,13 @@ export function emitBorshCodecs(model) {
|
|
|
84
93
|
};
|
|
85
94
|
// Bounds: the caller checked `len >= MIN` (the smallest Borsh form). Fixed-size pieces then always fit; only a
|
|
86
95
|
// String / Vec / Option payload is checked, against what is left after the fields that follow it still need.
|
|
87
|
-
const minOf = (t) => t.kind === "fstring" || t.kind === "vec" || t.kind === "string"
|
|
96
|
+
const minOf = (t) => t.kind === "fstring" || t.kind === "vec" || t.kind === "string"
|
|
97
|
+
? 4
|
|
98
|
+
: t.kind === "option" || t.kind === "dataEnum"
|
|
99
|
+
? 1
|
|
100
|
+
: variableStruct(t, model)
|
|
101
|
+
? borshMinSize(variableStruct(t, model), model)
|
|
102
|
+
: fixedBytes(t, model);
|
|
88
103
|
const minAfter = s.fields.map((_, i) => s.fields.slice(i + 1).reduce((n, f) => n + minOf(f.type), 0));
|
|
89
104
|
const need = (n, rest, pad) => `${pad}if (${n} > len - at - ${rest}) ${DESER};`;
|
|
90
105
|
const room = (n, rest, pad) => `${pad}if (${n} > cap - at - ${rest}) ${SER};`;
|
|
@@ -137,8 +152,35 @@ export function emitBorshCodecs(model) {
|
|
|
137
152
|
`${pad}}`,
|
|
138
153
|
];
|
|
139
154
|
}
|
|
155
|
+
case "struct": {
|
|
156
|
+
// A struct holding Options, nested: its fields one by one, each checked against what is left.
|
|
157
|
+
const sub = variableStruct(t, model);
|
|
158
|
+
const after = (i) => sub.fields.slice(i + 1).reduce((n, f) => n + minOf(f.type), rest);
|
|
159
|
+
return sub.fields.flatMap((f, i) => {
|
|
160
|
+
if (borshIdentical(f.type, model)) {
|
|
161
|
+
const n = fixedBytes(f.type, model);
|
|
162
|
+
return [
|
|
163
|
+
need(String(n), after(i), pad),
|
|
164
|
+
`${pad}ts_memcpy(&${lv}.${f.name}, src + at, ${n});`,
|
|
165
|
+
`${pad}at += ${n};`,
|
|
166
|
+
...validate(f.type, `${lv}.${f.name}`, pad),
|
|
167
|
+
];
|
|
168
|
+
}
|
|
169
|
+
return unpackVar(f.type, `${lv}.${f.name}`, after(i), pad);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
140
172
|
case "option": {
|
|
141
173
|
const tag = tmp("tag");
|
|
174
|
+
if (variableStruct(t.inner, model))
|
|
175
|
+
return [
|
|
176
|
+
need("1", rest, pad),
|
|
177
|
+
`${pad}uint8_t ${tag} = src[at++];`,
|
|
178
|
+
`${pad}if (${tag} > 1) ${DESER};`,
|
|
179
|
+
`${pad}${lv}.some = ${tag};`,
|
|
180
|
+
`${pad}if (${tag}) {`,
|
|
181
|
+
...unpackVar(t.inner, `${lv}.v`, rest, `${pad} `),
|
|
182
|
+
`${pad}}`,
|
|
183
|
+
];
|
|
142
184
|
const n = fixedBytes(t.inner, model);
|
|
143
185
|
return [
|
|
144
186
|
`${pad}uint8_t ${tag} = src[at++];`,
|
|
@@ -228,7 +270,26 @@ export function emitBorshCodecs(model) {
|
|
|
228
270
|
`${pad}}`,
|
|
229
271
|
];
|
|
230
272
|
}
|
|
273
|
+
case "struct": {
|
|
274
|
+
const sub = variableStruct(t, model);
|
|
275
|
+
const after = (i) => sub.fields.slice(i + 1).reduce((n, f) => n + minOf(f.type), rest);
|
|
276
|
+
return sub.fields.flatMap((f, i) => {
|
|
277
|
+
if (borshIdentical(f.type, model)) {
|
|
278
|
+
const n = fixedBytes(f.type, model);
|
|
279
|
+
return [room(String(n), after(i), pad), `${pad}ts_memcpy(dst + at, &${lv}.${f.name}, ${n});`, `${pad}at += ${n};`];
|
|
280
|
+
}
|
|
281
|
+
return packVar(f.type, `${lv}.${f.name}`, after(i), pad);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
231
284
|
case "option": {
|
|
285
|
+
if (variableStruct(t.inner, model))
|
|
286
|
+
return [
|
|
287
|
+
room("1", rest, pad),
|
|
288
|
+
`${pad}dst[at++] = ${lv}.some ? 1 : 0;`,
|
|
289
|
+
`${pad}if (${lv}.some) {`,
|
|
290
|
+
...packVar(t.inner, `${lv}.v`, rest, `${pad} `),
|
|
291
|
+
`${pad}}`,
|
|
292
|
+
];
|
|
232
293
|
const n = fixedBytes(t.inner, model);
|
|
233
294
|
return [
|
|
234
295
|
room(`(uint64_t)(${lv}.some ? ${1 + n} : 1)`, rest, pad),
|
|
@@ -19,6 +19,8 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
|
|
|
19
19
|
name: string;
|
|
20
20
|
count: number;
|
|
21
21
|
};
|
|
22
|
+
/** The index of the first remaining account among the instruction's accounts, as C: a constant, or a helper's parameter. */
|
|
23
|
+
protected remainingBase(node: ts.Expression): string;
|
|
22
24
|
/** `remainingAccounts()` or a const bound to it. */
|
|
23
25
|
protected isRemaining(node: ts.Expression): boolean;
|
|
24
26
|
/** C pointer (`TsAccount *`) for an expression naming a remaining account, or undefined. */
|
|
@@ -36,6 +38,8 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
|
|
|
36
38
|
protected anyAccount(node: ts.Expression, what: string): string;
|
|
37
39
|
/** `readData<T>(account, offset)`: a bounds-checked little-endian read of any account's data. */
|
|
38
40
|
protected readData(node: ts.CallExpression): Value;
|
|
41
|
+
/** `writeData<T>(account, offset, value)`: a little-endian store into a writable AccountInfo's data. */
|
|
42
|
+
protected writeData(node: ts.CallExpression): undefined;
|
|
39
43
|
/** `loadForeign<T>(account, owner)`: read-only view of another program's Anchor account. */
|
|
40
44
|
protected loadForeign(node: ts.CallExpression): Value;
|
|
41
45
|
/** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
|
|
@@ -72,12 +76,16 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
|
|
|
72
76
|
* A struct/array/data-enum helper argument. Helpers that take accounts may change account data, so they get a
|
|
73
77
|
* copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
|
|
74
78
|
*/
|
|
75
|
-
protected snapshotPlace(lv: string, type: FieldType, h: Helper): string;
|
|
79
|
+
protected snapshotPlace(lv: string, type: FieldType, h: Helper, node?: ts.Expression): string;
|
|
80
|
+
/** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
|
|
81
|
+
protected ownedRoot(node: ts.Expression): boolean;
|
|
76
82
|
/** `signer([...seeds])` (one PDA signature), or a SignerSeeds parameter passed on. */
|
|
77
83
|
protected signerSeedsArg(n: ts.Expression): {
|
|
78
84
|
name: string;
|
|
79
85
|
count: number | string;
|
|
80
86
|
};
|
|
87
|
+
/** Whether `require`'s error is named in the source (an error enum member, AnchorError.X or a message). */
|
|
88
|
+
protected namesError(node: ts.Expression): boolean;
|
|
81
89
|
protected errorRef(node: ts.Expression): ErrorDef;
|
|
82
90
|
/** The struct of `returnData<Quote>(…)`, when T is one; refused when its bytes are not its Borsh form. */
|
|
83
91
|
protected returnedStruct(node: ts.CallExpression): StructDef | undefined;
|
|
@@ -4,7 +4,7 @@ import { borshIdentical } from "./borsh.js";
|
|
|
4
4
|
import { ANCHOR_ERRORS } from "../anchor-errors.js";
|
|
5
5
|
import { decodeAddress } from "../../keys.js";
|
|
6
6
|
import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
|
|
7
|
-
import { U64, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, } from "./shared.js";
|
|
7
|
+
import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, } from "./shared.js";
|
|
8
8
|
import { ExpressionEmitter } from "./expressions.js";
|
|
9
9
|
/**
|
|
10
10
|
* Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
|
|
@@ -33,6 +33,13 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
33
33
|
if (args.length !== 2)
|
|
34
34
|
this.fail(node, "require(condition, error) takes two arguments");
|
|
35
35
|
const cond = this.expect(this.expr(args[0], BOOL), BOOL, args[0]);
|
|
36
|
+
if (!this.namesError(args[1])) {
|
|
37
|
+
// A code computed at run time (a helper that returns its error as a value): u32, the program error it names.
|
|
38
|
+
const v = this.expr(args[1], U32);
|
|
39
|
+
const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
|
|
40
|
+
this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
36
43
|
const err = this.errorRef(args[1]);
|
|
37
44
|
this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(`Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`)});`);
|
|
38
45
|
return undefined;
|
|
@@ -124,11 +131,12 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
124
131
|
}
|
|
125
132
|
case "currentSlot":
|
|
126
133
|
case "currentEpoch":
|
|
134
|
+
case "epochStartTimestamp":
|
|
127
135
|
case "now": {
|
|
128
136
|
if (args.length !== 0)
|
|
129
137
|
this.fail(node, `${builtin}() takes no arguments`);
|
|
130
138
|
// Clock { slot, epoch_start_timestamp, epoch, leader_schedule_epoch, unix_timestamp }
|
|
131
|
-
const field = builtin === "currentSlot" ? 0 : builtin === "currentEpoch" ? 2 : 4;
|
|
139
|
+
const field = builtin === "currentSlot" ? 0 : builtin === "currentEpoch" ? 2 : builtin === "epochStartTimestamp" ? 1 : 4;
|
|
132
140
|
const t = this.tmp();
|
|
133
141
|
if (this.ix) {
|
|
134
142
|
// The Clock does not change within a transaction: an instruction reads it once, on first use.
|
|
@@ -137,6 +145,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
137
145
|
this.line(`if (!ts_clk_ok) { TS_TRY(ts_read_clock(ts_clk)); ts_clk_ok = true; }`);
|
|
138
146
|
if (builtin === "now")
|
|
139
147
|
return { c: `((int64_t)ts_clk[4])`, type: I64 };
|
|
148
|
+
if (builtin === "epochStartTimestamp")
|
|
149
|
+
return { c: `((int64_t)ts_clk[1])`, type: I64 };
|
|
140
150
|
this.line(`uint64_t ${t} = ts_clk[${field}];`);
|
|
141
151
|
return { c: t, type: U64 };
|
|
142
152
|
}
|
|
@@ -147,6 +157,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
147
157
|
}
|
|
148
158
|
this.line(`uint64_t ${t};`);
|
|
149
159
|
this.line(`TS_TRY(ts_clock_u64(${field}, &${t}));`);
|
|
160
|
+
if (builtin === "epochStartTimestamp")
|
|
161
|
+
return { c: `((int64_t)${t})`, type: I64 };
|
|
150
162
|
return { c: t, type: U64 };
|
|
151
163
|
}
|
|
152
164
|
case "pubkey": {
|
|
@@ -193,6 +205,15 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
193
205
|
this.line(`TS_TRY(ts_mul_div${wide ? "_u128" : ""}(${x.c}, ${y.c}, ${z.c}, ${builtin === "mulDivCeil"}, &${t}));`);
|
|
194
206
|
return { c: t, type: ty };
|
|
195
207
|
}
|
|
208
|
+
case "f64FromBits":
|
|
209
|
+
case "f64Bits": {
|
|
210
|
+
// An f64 is its IEEE bits held as a u64: both are the same value, typed for the IDL and for TypeScript.
|
|
211
|
+
if (args.length !== 1)
|
|
212
|
+
this.fail(node, `${builtin}(x) takes one ${builtin === "f64Bits" ? "f64" : "u64"}`);
|
|
213
|
+
const v = this.expr(args[0]);
|
|
214
|
+
const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : this.expect(v, U64, args[0]);
|
|
215
|
+
return { c: x.c, type: builtin === "f64Bits" ? U64 : { kind: "int", name: "u64", f64: true } };
|
|
216
|
+
}
|
|
196
217
|
case "isqrt": {
|
|
197
218
|
if (args.length !== 1)
|
|
198
219
|
this.fail(node, "isqrt(x) takes one unsigned integer");
|
|
@@ -535,10 +556,24 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
535
556
|
}
|
|
536
557
|
case "remainingAccounts":
|
|
537
558
|
if (!this.ix)
|
|
538
|
-
this.fail(node, "remainingAccounts() is only available in instructions");
|
|
539
|
-
return { c:
|
|
559
|
+
this.fail(node, "remainingAccounts() is only available in instructions; pass it to a helper that takes RemainingAccounts");
|
|
560
|
+
return { c: String(this.ix.accounts.length), type: { kind: "remaining" } };
|
|
540
561
|
case "readData":
|
|
541
562
|
return this.readData(node);
|
|
563
|
+
case "writeData":
|
|
564
|
+
return this.writeData(node);
|
|
565
|
+
case "resizeAccount": {
|
|
566
|
+
if (args.length !== 2)
|
|
567
|
+
this.fail(node, "resizeAccount(account, newSize) takes the account and its new size");
|
|
568
|
+
if (!this.ix)
|
|
569
|
+
this.fail(node, "resizeAccount() is only available in instructions");
|
|
570
|
+
const acct = this.accountParam(args[0], "resizeAccount's account");
|
|
571
|
+
if (acct.kind.kind !== "info" || !isWritable(acct.kind))
|
|
572
|
+
this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter");
|
|
573
|
+
const size = this.expect(this.expr(args[1], U64), U64, args[1]);
|
|
574
|
+
this.line(`TS_TRY(ts_resize_raw(a_${acct.name}, ${size.c}, entry_${acct.name}));`);
|
|
575
|
+
return undefined;
|
|
576
|
+
}
|
|
542
577
|
case "bigEndian":
|
|
543
578
|
this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
|
|
544
579
|
case "loadAccount":
|
|
@@ -710,6 +745,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
710
745
|
return this.systemTransfer(node);
|
|
711
746
|
if (target?.kind.kind === "system" && method === "createAccount")
|
|
712
747
|
return this.createAccount(node, target);
|
|
748
|
+
if (target?.kind.kind === "system" && method === "createPda")
|
|
749
|
+
return this.createPda(node);
|
|
713
750
|
if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
|
|
714
751
|
return this.allocateOrAssign(node, target, method);
|
|
715
752
|
if (target?.kind.kind === "tokenProgram")
|
|
@@ -1069,6 +1106,17 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1069
1106
|
this.line(`ts_memcpy(${name} + ${f.offset}, ${f.c}, 32);`);
|
|
1070
1107
|
return { name, count };
|
|
1071
1108
|
}
|
|
1109
|
+
/** The index of the first remaining account among the instruction's accounts, as C: a constant, or a helper's parameter. */
|
|
1110
|
+
remainingBase(node) {
|
|
1111
|
+
if (ts.isIdentifier(node)) {
|
|
1112
|
+
const l = this.lookup(node.text);
|
|
1113
|
+
if (l?.type.kind === "remaining" && l.c)
|
|
1114
|
+
return l.c;
|
|
1115
|
+
}
|
|
1116
|
+
if (!this.ix)
|
|
1117
|
+
this.fail(node, "remainingAccounts() is only available in instructions; pass it to a helper that takes RemainingAccounts");
|
|
1118
|
+
return String(this.ix.accounts.length);
|
|
1119
|
+
}
|
|
1072
1120
|
/** `remainingAccounts()` or a const bound to it. */
|
|
1073
1121
|
isRemaining(node) {
|
|
1074
1122
|
if (ts.isIdentifier(node))
|
|
@@ -1173,11 +1221,9 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1173
1221
|
ts.isPropertyAccessExpression(node.expression) &&
|
|
1174
1222
|
node.expression.name.text === "get" &&
|
|
1175
1223
|
this.isRemaining(node.expression.expression)) {
|
|
1176
|
-
if (!this.ix)
|
|
1177
|
-
this.fail(node, "remainingAccounts() is only available in instructions");
|
|
1178
1224
|
if (node.arguments.length !== 1)
|
|
1179
1225
|
this.fail(node, "get(index) takes one argument");
|
|
1180
|
-
const n = this.
|
|
1226
|
+
const n = this.remainingBase(node.expression.expression);
|
|
1181
1227
|
const idx = this.index(node.arguments[0], `(uint64_t)(params->ka_num - ${n})`);
|
|
1182
1228
|
const t = this.tmp("acct");
|
|
1183
1229
|
this.line(`TsAccount *${t} = params->ka[${n} + ${idx}];`);
|
|
@@ -1219,12 +1265,41 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1219
1265
|
this.line(`if (${out} >= ${this.model.enums.get(t.name).variants.length}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: invalid enum value");`);
|
|
1220
1266
|
return { c: out, type: t };
|
|
1221
1267
|
}
|
|
1268
|
+
/** `writeData<T>(account, offset, value)`: a little-endian store into a writable AccountInfo's data. */
|
|
1269
|
+
writeData(node) {
|
|
1270
|
+
const targ = node.typeArguments?.[0];
|
|
1271
|
+
const t = targ && resolveScalarType(targ, this.scope);
|
|
1272
|
+
if (!t)
|
|
1273
|
+
this.fail(node, "writeData needs a value type: writeData<u64>(account, offset, value)");
|
|
1274
|
+
if (node.arguments.length !== 3)
|
|
1275
|
+
this.fail(node, "writeData<T>(account, offset, value) takes an account, a byte offset and a value");
|
|
1276
|
+
const acct = this.accountParam(node.arguments[0], "writeData's account");
|
|
1277
|
+
if (acct.kind.kind !== "info" || !isWritable(acct.kind))
|
|
1278
|
+
this.fail(node.arguments[0], "writeData needs a Mut<AccountInfo> parameter");
|
|
1279
|
+
const off = this.expect(this.expr(node.arguments[1], U64), U64, node.arguments[1]);
|
|
1280
|
+
const o = this.tmp("off");
|
|
1281
|
+
this.line(`uint64_t ${o} = ${off.c};`);
|
|
1282
|
+
const v = this.expect(this.expr(node.arguments[2], t), t, node.arguments[2]);
|
|
1283
|
+
const size = scalarSize(t);
|
|
1284
|
+
const a = `a_${acct.name}`;
|
|
1285
|
+
this.line(`if (${o} > ${a}->data_len || ${a}->data_len - ${o} < ${size}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: write past the end of the account data");`);
|
|
1286
|
+
if (t.kind === "pubkey")
|
|
1287
|
+
this.line(`ts_memcpy(${a}->data + ${o}, ${v.c}, 32);`);
|
|
1288
|
+
else {
|
|
1289
|
+
const w = this.tmp("wr");
|
|
1290
|
+
this.line(`${scalarStorageC(t)} ${w} = (${scalarStorageC(t)})(${v.c});`);
|
|
1291
|
+
this.line(`ts_memcpy(${a}->data + ${o}, &${w}, ${size});`);
|
|
1292
|
+
}
|
|
1293
|
+
return undefined;
|
|
1294
|
+
}
|
|
1222
1295
|
/** `loadForeign<T>(account, owner)`: read-only view of another program's Anchor account. */
|
|
1223
1296
|
loadForeign(node) {
|
|
1224
1297
|
const targ = node.typeArguments?.[0];
|
|
1225
1298
|
const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
|
|
1226
1299
|
if (!s || s.size === undefined || s.vec)
|
|
1227
1300
|
this.fail(node, "loadForeign needs a fixed-size struct type: loadForeign<Pool>(account, owner)");
|
|
1301
|
+
if (s.accountDiscriminator.length !== 8)
|
|
1302
|
+
this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
|
|
1228
1303
|
if (s.layout === "borsh")
|
|
1229
1304
|
this.fail(node, `${s.name} is @layout borsh: loadForeign reads fixed layouts only`);
|
|
1230
1305
|
if (node.arguments.length !== 2)
|
|
@@ -1244,10 +1319,20 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1244
1319
|
}
|
|
1245
1320
|
/** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
|
|
1246
1321
|
loadAccount(node, mut) {
|
|
1247
|
-
|
|
1322
|
+
let targ = node.typeArguments?.[0];
|
|
1323
|
+
// loadAccountMut<Dup<T>>: the account may be passed more than once among the remaining accounts (a route back
|
|
1324
|
+
// through one pool), loaded once per loop iteration; two live views of it are still refused.
|
|
1325
|
+
const dup = !!targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) && targ.typeName.text === "Dup" && targ.typeArguments?.length === 1;
|
|
1326
|
+
if (dup) {
|
|
1327
|
+
if (!mut)
|
|
1328
|
+
this.fail(node, "Dup<…> is for loadAccountMut (loadAccount reads, any number of times)");
|
|
1329
|
+
targ = targ.typeArguments[0];
|
|
1330
|
+
}
|
|
1248
1331
|
const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
|
|
1249
1332
|
if (!s || s.size === undefined)
|
|
1250
1333
|
this.fail(node, "loadAccount needs an account struct type: loadAccount<MyStruct>(account)");
|
|
1334
|
+
if (s.accountDiscriminator.length !== 8)
|
|
1335
|
+
this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
|
|
1251
1336
|
if (s.layout === "borsh")
|
|
1252
1337
|
this.fail(node, `${s.name} is @layout borsh: declare it as an instruction parameter (remaining accounts are read in place)`);
|
|
1253
1338
|
if (node.arguments.length !== 1)
|
|
@@ -1270,13 +1355,21 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1270
1355
|
if (this.model.events.has(s.name) && s.fields.some((f) => f.type.kind === "option" || f.type.kind === "dataEnum"))
|
|
1271
1356
|
this.fail(node, `${s.name} is emitted as an event and has Option or enum fields; declare a separate event struct`);
|
|
1272
1357
|
this.model.accountStructs.add(s.name);
|
|
1273
|
-
this.line(`TS_TRY(ts_check_program_account(${h}, params->program_id, TS_DISC_${s.name}, ${emptySizeC(s)}));`);
|
|
1358
|
+
this.line(`TS_TRY(${s.idlMeta?.serialization?.startsWith("bytemuck") ? "ts_check_loader_account" : "ts_check_program_account"}(${h}, params->program_id, TS_DISC_${s.name}, ${emptySizeC(s)}));`);
|
|
1274
1359
|
if (s.vec)
|
|
1275
1360
|
for (const l of vecLenCheck(s, h, `((TSS_${s.name} *)(${h}->data + 8))`, ""))
|
|
1276
1361
|
this.line(l);
|
|
1277
1362
|
if (mut) {
|
|
1278
1363
|
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
1279
|
-
|
|
1364
|
+
const slot = this.claimSlots.get(node);
|
|
1365
|
+
// Repeats may come only after the instruction's own accounts, and only for Dup<…>: otherwise any repeat is refused.
|
|
1366
|
+
const declared = dup && this.ix ? String(this.ix.accounts.length) : "params->ka_num";
|
|
1367
|
+
if (dup && (param !== undefined || !slot))
|
|
1368
|
+
this.fail(node, "loadAccountMut<Dup<T>> is for remaining accounts loaded in a loop (one view per iteration)");
|
|
1369
|
+
if (slot)
|
|
1370
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, ${declared}));` : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
|
|
1371
|
+
else
|
|
1372
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
|
|
1280
1373
|
}
|
|
1281
1374
|
return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: mut } };
|
|
1282
1375
|
}
|
|
@@ -1456,7 +1549,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1456
1549
|
this.fail(node, `${h.display}() takes ${h.params.length} argument(s)`);
|
|
1457
1550
|
// Arguments are evaluated left to right: settle earlier ones when a later one runs statements.
|
|
1458
1551
|
// A helper that takes accounts may change account data, so account text it gets is copied first.
|
|
1459
|
-
|
|
1552
|
+
// A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
|
|
1553
|
+
const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
|
|
1460
1554
|
const values = [];
|
|
1461
1555
|
const pieces = [];
|
|
1462
1556
|
h.params.forEach((p, i) => {
|
|
@@ -1530,20 +1624,25 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1530
1624
|
case "structRef":
|
|
1531
1625
|
case "arrayArg": {
|
|
1532
1626
|
const want = p.type.kind === "structRef" ? { kind: "struct", name: p.type.struct } : p.type.array;
|
|
1533
|
-
|
|
1627
|
+
let r = this.ref(n);
|
|
1628
|
+
// A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): its value.
|
|
1629
|
+
if (r && r.type.kind === "option" && sameType(r.type.inner, want))
|
|
1630
|
+
r = this.someValue(r);
|
|
1534
1631
|
if (!r || !sameType(r.type, want))
|
|
1535
1632
|
this.fail(n, `expected a ${typeName(want)}`);
|
|
1536
|
-
return this.snapshotPlace(r.lv, want, h);
|
|
1633
|
+
return this.snapshotPlace(r.lv, want, h, n);
|
|
1537
1634
|
}
|
|
1538
1635
|
case "dataEnumArg": {
|
|
1539
1636
|
const r = this.ref(n);
|
|
1540
1637
|
if (!r || r.type.kind !== "dataEnum" || r.type.name !== p.type.name)
|
|
1541
1638
|
this.fail(n, `expected a ${p.type.name}`);
|
|
1542
|
-
return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h);
|
|
1639
|
+
return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h, n);
|
|
1543
1640
|
}
|
|
1544
1641
|
case "vecArg": {
|
|
1545
1642
|
const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
|
|
1546
|
-
|
|
1643
|
+
// An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
|
|
1644
|
+
const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
|
|
1645
|
+
if (!l || !t || !sameType(t, p.type))
|
|
1547
1646
|
this.fail(n, `expected a ${typeName(p.type)} instruction argument`);
|
|
1548
1647
|
return l.c;
|
|
1549
1648
|
}
|
|
@@ -1555,8 +1654,12 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1555
1654
|
* A struct/array/data-enum helper argument. Helpers that take accounts may change account data, so they get a
|
|
1556
1655
|
* copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
|
|
1557
1656
|
*/
|
|
1558
|
-
snapshotPlace(lv, type, h) {
|
|
1559
|
-
if (!h.params.some((p) => p.account))
|
|
1657
|
+
snapshotPlace(lv, type, h, node) {
|
|
1658
|
+
if (!h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining"))
|
|
1659
|
+
return `(&${lv})`;
|
|
1660
|
+
// A struct this function owns (a literal, or a helper's result it holds), or part of one, is not account data: what
|
|
1661
|
+
// the helper writes cannot change it, so the helper reads it in place.
|
|
1662
|
+
if (node && this.ownedRoot(node))
|
|
1560
1663
|
return `(&${lv})`;
|
|
1561
1664
|
const n = this.fieldBytes(type);
|
|
1562
1665
|
// One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
|
|
@@ -1567,6 +1670,21 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1567
1670
|
this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
|
|
1568
1671
|
return t;
|
|
1569
1672
|
}
|
|
1673
|
+
/** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
|
|
1674
|
+
ownedRoot(node) {
|
|
1675
|
+
let n = node;
|
|
1676
|
+
for (;;) {
|
|
1677
|
+
if (ts.isParenthesizedExpression(n))
|
|
1678
|
+
n = n.expression;
|
|
1679
|
+
else if (ts.isPropertyAccessExpression(n))
|
|
1680
|
+
n = n.expression;
|
|
1681
|
+
else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get")
|
|
1682
|
+
n = n.expression.expression;
|
|
1683
|
+
else
|
|
1684
|
+
break;
|
|
1685
|
+
}
|
|
1686
|
+
return ts.isIdentifier(n) && !!this.lookup(n.text)?.owned;
|
|
1687
|
+
}
|
|
1570
1688
|
/** `signer([...seeds])` (one PDA signature), or a SignerSeeds parameter passed on. */
|
|
1571
1689
|
signerSeedsArg(n) {
|
|
1572
1690
|
if (ts.isIdentifier(n)) {
|
|
@@ -1581,6 +1699,16 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1581
1699
|
}
|
|
1582
1700
|
this.fail(n, "pass signer([...seeds with the bump]) or a SignerSeeds parameter");
|
|
1583
1701
|
}
|
|
1702
|
+
/** Whether `require`'s error is named in the source (an error enum member, AnchorError.X or a message). */
|
|
1703
|
+
namesError(node) {
|
|
1704
|
+
if (ts.isStringLiteral(node))
|
|
1705
|
+
return true;
|
|
1706
|
+
if (!ts.isPropertyAccessExpression(node))
|
|
1707
|
+
return false;
|
|
1708
|
+
if (this.exportName(node.expression) === "AnchorError")
|
|
1709
|
+
return true;
|
|
1710
|
+
return ts.isIdentifier(node.expression) && this.model.errorEnums.has(node.expression.text);
|
|
1711
|
+
}
|
|
1584
1712
|
errorRef(node) {
|
|
1585
1713
|
// `AnchorError.X`: one of Anchor's own codes (not one of this program's errors, so not in the IDL).
|
|
1586
1714
|
if (ts.isPropertyAccessExpression(node) && this.exportName(node.expression) === "AnchorError") {
|
|
@@ -1598,7 +1726,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1598
1726
|
const existing = this.model.errors.find((e) => e.msg === node.text && e.name.startsWith("RequireFailed"));
|
|
1599
1727
|
if (existing)
|
|
1600
1728
|
return existing;
|
|
1601
|
-
const
|
|
1729
|
+
const code = Math.max(5999, ...this.model.errors.map((e) => e.code)) + 1;
|
|
1730
|
+
const def = { code, name: `RequireFailed${code - 6000}`, msg: node.text };
|
|
1602
1731
|
this.model.errors.push(def);
|
|
1603
1732
|
return def;
|
|
1604
1733
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { argIdlName, snakeCase } from "../analyze.js";
|
|
2
|
+
import { argIdlName, fieldIdlName, snakeCase } from "../analyze.js";
|
|
3
3
|
import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
|
|
4
4
|
import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
|
|
5
5
|
import { CallEmitter } from "./calls.js";
|
|
@@ -113,6 +113,15 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
113
113
|
b.writeBigUInt64LE(value);
|
|
114
114
|
return { kind: "const", value: [...b] };
|
|
115
115
|
}
|
|
116
|
+
// `opt ?? 0n` on an Option argument: Anchor's IDL keeps the Rust expression's text, `opt.unwrap_or(0)`.
|
|
117
|
+
if (ts.isBinaryExpression(el) &&
|
|
118
|
+
el.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken &&
|
|
119
|
+
ts.isBigIntLiteral(el.right) &&
|
|
120
|
+
ts.isIdentifier(el.left)) {
|
|
121
|
+
const arg = this.describeSeed(el.left);
|
|
122
|
+
if (arg?.kind === "arg")
|
|
123
|
+
return { kind: "arg", path: `${arg.path}.unwrap_or(${BigInt(el.right.text.slice(0, -1).replace(/_/g, ""))})` };
|
|
124
|
+
}
|
|
116
125
|
// Only the argument itself, not a local that shadows its name.
|
|
117
126
|
if (ts.isIdentifier(el) && this.ix?.args.some((a) => a.name === el.text) && this.lookup(el.text) === this.args.get(el.text))
|
|
118
127
|
return {
|
|
@@ -139,7 +148,7 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
139
148
|
if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
|
|
140
149
|
const f = a.kind.struct.fields.find((x) => x.name === el.name.text);
|
|
141
150
|
if (f && isScalar(f.type))
|
|
142
|
-
return { kind: "account", path: `${snakeCase(a.name)}.${
|
|
151
|
+
return { kind: "account", path: `${snakeCase(a.name)}.${f.idlName ?? fieldIdlName(f.name)}`, account: a.kind.struct.name };
|
|
143
152
|
}
|
|
144
153
|
}
|
|
145
154
|
return undefined;
|
|
@@ -230,13 +239,16 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
230
239
|
* (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
|
|
231
240
|
*/
|
|
232
241
|
remainingRange(node) {
|
|
242
|
+
const sliced = ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "slice";
|
|
243
|
+
if (!this.isRemaining(node) && !(sliced && this.isRemaining(node.expression.expression)))
|
|
244
|
+
return undefined;
|
|
245
|
+
if (!this.ix)
|
|
246
|
+
this.fail(node, "pass the remaining accounts to a CPI from the instruction; a helper reads them one at a time with .get(i)");
|
|
233
247
|
const n = this.ix.accounts.length;
|
|
234
248
|
const count = `(params->ka_num - ${n})`;
|
|
235
249
|
if (this.isRemaining(node))
|
|
236
250
|
return { from: "0", to: count };
|
|
237
|
-
if (!ts.isCallExpression(node)
|
|
238
|
-
return undefined;
|
|
239
|
-
if (!this.isRemaining(node.expression.expression))
|
|
251
|
+
if (!ts.isCallExpression(node))
|
|
240
252
|
return undefined;
|
|
241
253
|
if (node.arguments.length < 1 || node.arguments.length > 2)
|
|
242
254
|
this.fail(node, "slice(start, end?) takes one or two indexes");
|