@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
@@ -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
+ }
@@ -0,0 +1,356 @@
1
+ import ts from "typescript";
2
+ import { snakeCase } from "../analyze.js";
3
+ import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
4
+ import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
5
+ import { CallEmitter } from "./calls.js";
6
+ /** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
7
+ export class CpiCoreEmitter extends CallEmitter {
8
+ /**
9
+ * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
10
+ * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
11
+ */
12
+ seeds(node, extra) {
13
+ if (!ts.isArrayLiteralExpression(node))
14
+ this.fail(node, "seeds must be an array literal");
15
+ if (node.elements.length > MAX_SEEDS)
16
+ this.fail(node, `at most ${MAX_SEEDS} seeds`);
17
+ const parts = [];
18
+ let idl = [];
19
+ // Without calls or writes among the seeds, nothing can change a seed before the CPI reads it: account fields are
20
+ // then passed in place instead of copied.
21
+ const mutates = (n) => ts.isCallExpression(n) ||
22
+ (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
23
+ ts.isPrefixUnaryExpression(n) ||
24
+ ts.isPostfixUnaryExpression(n) ||
25
+ ts.forEachChild(n, mutates) === true;
26
+ const inPlace = !node.elements.some(mutates);
27
+ const mark = this.lines.length;
28
+ for (const el of node.elements) {
29
+ const desc = this.describeSeed(el);
30
+ if (!desc)
31
+ idl = undefined;
32
+ else
33
+ idl?.push(desc);
34
+ if (ts.isStringLiteral(el)) {
35
+ const len = Buffer.byteLength(el.text, "utf8");
36
+ if (len > 32)
37
+ this.fail(el, "a seed can be at most 32 bytes");
38
+ parts.push(`{(const uint8_t *)${cString(el.text)}, ${len}}`);
39
+ continue;
40
+ }
41
+ // Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
42
+ const v = this.expr(el);
43
+ if (v.type.kind === "pubkey" && (isStable(v.c) || (inPlace && /^\(&d_\w+(->\w+)+\)$/.test(v.c))))
44
+ parts.push(`{(const uint8_t *)${v.c.startsWith("(") ? v.c : `(${v.c})`}, 32}`);
45
+ else if (v.type.kind === "int" && inPlace && v.literal === undefined && /^d_\w+(->\w+)+$/.test(v.c))
46
+ parts.push(`{(const uint8_t *)&${v.c}, ${INT_INFO[v.type.name].bytes}}`);
47
+ else if (v.type.kind === "pubkey") {
48
+ const t = this.tmp("seed");
49
+ this.line(`SolPubkey ${t} = *(${v.c});`);
50
+ parts.push(`{(const uint8_t *)&${t}, 32}`);
51
+ }
52
+ else if (v.type.kind === "string") {
53
+ const t = this.tmp("seed");
54
+ this.line(`TS_Str ${t} = ${this.ownedString(v).c};`);
55
+ parts.push(`{${t}.ptr, ${t}.len}`);
56
+ }
57
+ else if (v.type.kind === "int") {
58
+ const typed = v.literal !== undefined ? this.literal(v.literal, U64, el) : v;
59
+ const info = INT_INFO[typed.type.name];
60
+ const t = this.tmp("seed");
61
+ this.line(`${info.c} ${t} = ${typed.c};`);
62
+ parts.push(`{(const uint8_t *)&${t}, ${info.bytes}}`);
63
+ }
64
+ else if (v.type.kind === "enum") {
65
+ // A unit enum value is its variant index, one byte (as in Seeds<…> and Borsh).
66
+ const t = this.tmp("seed");
67
+ this.line(`uint8_t ${t} = (uint8_t)(${v.c});`);
68
+ parts.push(`{(const uint8_t *)&${t}, 1}`);
69
+ }
70
+ else
71
+ this.fail(el, "seeds can be strings, Pubkeys, integers or unit enum values");
72
+ }
73
+ // The same list again (escrow: the vault transfer, then its close) reuses the array declared for the first, when
74
+ // nothing was copied into temporaries (every entry points at a literal or at the place itself, so the array reads
75
+ // what a new one would), it has no spare slot (callers never write into those arrays) and it is still in scope.
76
+ const key = parts.join(", ");
77
+ const reusable = extra === 0 && parts.length > 0 && this.lines.length === mark;
78
+ const known = reusable ? this.seedArrays.get(key) : undefined;
79
+ if (known && this.scopes.includes(known.scope) && this.lines[known.at]?.trim() === known.text)
80
+ return { name: known.name, count: parts.length, idl };
81
+ const name = this.tmp("seeds");
82
+ const slots = parts.length + extra;
83
+ this.line(`SolSignerSeed ${name}[${Math.max(slots, 1)}] = {${parts.join(", ")}};`);
84
+ if (reusable)
85
+ this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
86
+ return { name, count: parts.length, idl };
87
+ }
88
+ describeSeed(el) {
89
+ if (ts.isStringLiteral(el))
90
+ return { kind: "const", value: [...Buffer.from(el.text, "utf8")] };
91
+ if (ts.isBigIntLiteral(el)) {
92
+ const value = BigInt(el.text.slice(0, -1).replace(/_/g, ""));
93
+ if (value > INT_INFO.u64.max)
94
+ this.fail(el, `${value} does not fit in u64`);
95
+ const b = Buffer.alloc(8);
96
+ b.writeBigUInt64LE(value);
97
+ return { kind: "const", value: [...b] };
98
+ }
99
+ // Only the argument itself, not a local that shadows its name.
100
+ if (ts.isIdentifier(el) && this.ix?.args.some((a) => a.name === el.text) && this.lookup(el.text) === this.args.get(el.text))
101
+ return { kind: "arg", path: snakeCase(el.text) };
102
+ if (ts.isIdentifier(el) && !this.lookup(el.text)) {
103
+ const k = this.model.constants.get(el.text);
104
+ if (k && typeof k.value === "string")
105
+ return { kind: "const", value: [...Buffer.from(k.value, "utf8")] };
106
+ if (k && typeof k.value === "object")
107
+ return { kind: "const", value: k.value.pubkey };
108
+ if (k && typeof k.value === "bigint") {
109
+ // Little-endian two's complement in the constant's width (16 bytes for u128/i128), as the program hashes it.
110
+ const bytes = k.type ? scalarSize(k.type) : 8;
111
+ const v = BigInt.asUintN(bytes * 8, k.value);
112
+ return { kind: "const", value: Array.from({ length: bytes }, (_, i) => Number((v >> BigInt(8 * i)) & 0xffn)) };
113
+ }
114
+ }
115
+ if (ts.isPropertyAccessExpression(el) && ts.isIdentifier(el.expression)) {
116
+ const a = this.accounts.get(el.expression.text);
117
+ if (a && el.name.text === "key")
118
+ return { kind: "account", path: snakeCase(a.name) };
119
+ if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
120
+ const f = a.kind.struct.fields.find((x) => x.name === el.name.text);
121
+ if (f && isScalar(f.type))
122
+ return { kind: "account", path: `${snakeCase(a.name)}.${snakeCase(f.name)}`, account: a.kind.struct.name };
123
+ }
124
+ }
125
+ return undefined;
126
+ }
127
+ recordPda(account, idl) {
128
+ if (this.ix && idl && !this.ix.pdas.has(account.name))
129
+ this.ix.pdas.set(account.name, idl);
130
+ }
131
+ /**
132
+ * Emit a CPI to the program account `program` with these metas (account, writable, signer), and then (`tail`) a range
133
+ * of the remaining accounts, read-only (a Merkle proof).
134
+ */
135
+ cpi(program, metas, buf, len, seeds, tail) {
136
+ const m = this.tmp("metas");
137
+ const fixed = metas.map(([acc, w, sg]) => `{&${acc}->key, ${w}, ${sg}}`).join(", ");
138
+ if (!tail) {
139
+ this.line(`SolAccountMeta ${m}[${metas.length}] = {${fixed}};`);
140
+ this.line(`TS_TRY(ts_cpi(params, ${program}, ${buf}, ${len}, ${m}, ${metas.length}, ${seeds.name}, ${seeds.count}));`);
141
+ return;
142
+ }
143
+ const n = this.ix.accounts.length;
144
+ const cnt = this.tmp("nmetas");
145
+ const i = this.tmp("ri");
146
+ this.line(`if (${metas.length} + (${tail.to} - ${tail.from}) > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: the CPI lists more than ${accountLimit(this.model)} accounts");`);
147
+ this.line(`TS_METAS(${m}, ${fixed});`);
148
+ this.line(`uint64_t ${cnt} = ${metas.length};`);
149
+ this.line(`for (uint64_t ${i} = ${n} + ${tail.from}; ${i} < ${n} + ${tail.to}; ${i}++) ${m}[${cnt}++] = (SolAccountMeta){&params->ka[${i}]->key, ${tail.asPassed ? `params->ka[${i}]->is_writable` : 0}, 0};`);
150
+ this.line(`TS_TRY(ts_cpi(params, ${program}, ${buf}, ${len}, ${m}, ${cnt}, ${seeds.name}, ${seeds.count}));`);
151
+ }
152
+ signerSeeds(node, authority, at) {
153
+ if (!node) {
154
+ if (authority.kind.kind !== "signer")
155
+ this.fail(at, "the authority must be a Signer, or pass signerSeeds for a PDA authority");
156
+ return { name: "NULL", count: 0 };
157
+ }
158
+ return this.signingSeeds(node);
159
+ }
160
+ /** Seeds to sign a CPI with: an array literal, or a helper's SignerSeeds parameter. */
161
+ signingSeeds(node) {
162
+ if (ts.isIdentifier(node)) {
163
+ const l = this.lookup(node.text);
164
+ if (l?.type.kind === "signerSeeds")
165
+ return { name: l.c, count: `${l.c}__n` };
166
+ }
167
+ return this.seeds(node, 0);
168
+ }
169
+ /** Object literal properties by name, refusing others. */
170
+ literalProps(o, allowed, what) {
171
+ const props = new Map();
172
+ for (const q of o.properties) {
173
+ if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
174
+ props.set(q.name.text, q.initializer);
175
+ else if (ts.isShorthandPropertyAssignment(q))
176
+ props.set(q.name.text, q.name);
177
+ else
178
+ this.fail(q, `write ${what}'s fields as name: value`);
179
+ }
180
+ for (const [k, v] of props)
181
+ if (!allowed.includes(k))
182
+ this.fail(v, `${what} has no field ${k} (${allowed.join(", ")})`);
183
+ return props;
184
+ }
185
+ /** `acct.key` of an account parameter, as an expression to serialize. */
186
+ keyOf(n) {
187
+ const f = ts.factory;
188
+ const e = f.createPropertyAccessExpression(n, "key");
189
+ ts.setTextRange(e, n);
190
+ e.parent = n.parent;
191
+ return e;
192
+ }
193
+ /**
194
+ * `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
195
+ * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
196
+ */
197
+ remainingRange(node) {
198
+ const n = this.ix.accounts.length;
199
+ const count = `(params->ka_num - ${n})`;
200
+ if (this.isRemaining(node))
201
+ return { from: "0", to: count };
202
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "slice")
203
+ return undefined;
204
+ if (!this.isRemaining(node.expression.expression))
205
+ return undefined;
206
+ if (node.arguments.length < 1 || node.arguments.length > 2)
207
+ this.fail(node, "slice(start, end?) takes one or two indexes");
208
+ // Both ends may equal the count (an empty slice at the end).
209
+ const from = this.index(node.arguments[0], `${count} + 1`);
210
+ const to = node.arguments[1] ? this.index(node.arguments[1], `${count} + 1`) : count;
211
+ this.line(`if (${from} > ${to}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: remaining accounts slice out of range");`);
212
+ return { from, to };
213
+ }
214
+ /**
215
+ * A byte buffer written front to back. Its C declaration is patched in afterwards so it is
216
+ * exactly as large as the fixed content, and only falls back to `max` when strings make it dynamic.
217
+ */
218
+ byteBuffer(prefix, max, errorCode, what) {
219
+ const buf = this.tmp(prefix);
220
+ const len = this.tmp(`${prefix}len`);
221
+ const declAt = this.lines.length;
222
+ this.line(`/* ${buf} */`);
223
+ this.line(`uint64_t ${len} = 0;`);
224
+ let fixed = 0;
225
+ let dynamic = false;
226
+ const put = (src, n, bytes) => {
227
+ // Once a variable-size piece was written the offset is only known at runtime: check every later write,
228
+ // fixed-size ones included, so nothing lands past the buffer.
229
+ if (bytes === undefined)
230
+ dynamic = true;
231
+ else
232
+ fixed += bytes;
233
+ if (dynamic)
234
+ this.line(`if (${len} + ${n} > ${max}) TS_FAIL(${errorCode}, "TypeSOL: ${what} too large");`);
235
+ this.line(`ts_memcpy(${buf} + ${len}, ${src}, ${n});`);
236
+ this.line(`${len} += ${n};`);
237
+ };
238
+ const finish = (at) => {
239
+ if (fixed > max)
240
+ this.fail(at, `${what} is at least ${fixed} bytes; the limit is ${max}`);
241
+ this.lines[declAt] = this.lines[declAt].replace(`/* ${buf} */`, `uint8_t ${buf}[${dynamic ? max : Math.max(fixed, 1)}];`);
242
+ };
243
+ return { buf, len, put, finish };
244
+ }
245
+ /** Append a value's Borsh encoding through `put(srcPointer, byteCount)`. */
246
+ serialize(v, node, put) {
247
+ if (v.isNull)
248
+ this.fail(node, "a bare null has no type here; pass an Option value (e.g. a local declared `const x: u64 | null = null`)");
249
+ const typed = v.literal !== undefined ? this.literal(v.literal, U64, node) : v;
250
+ if (typed.type.kind === "pubkey") {
251
+ put(`(${typed.c})`, "32", 32);
252
+ }
253
+ else if (typed.type.kind === "string") {
254
+ const t = this.tmp("s");
255
+ const l = this.tmp("slen");
256
+ this.line(`TS_Str ${t} = ${typed.c};`);
257
+ this.line(`uint32_t ${l} = (uint32_t)${t}.len;`);
258
+ put(`&${l}`, "4", 4);
259
+ put(`${t}.ptr`, `${t}.len`);
260
+ }
261
+ else if (typed.type.kind === "option") {
262
+ // Borsh Option: tag byte, then the value only when Some (so the size is dynamic).
263
+ const inner = typed.type.inner;
264
+ const t = this.tmp("o");
265
+ this.line(`${optC(inner)} ${t} = ${typed.c};`);
266
+ put(`&${t}.some`, "1", 1);
267
+ put(`&${t}.v`, `(${t}.some ? ${inner.kind === "struct" ? this.fieldBytes(inner) : scalarSize(inner)} : 0)`);
268
+ }
269
+ else if (isScalar(typed.type)) {
270
+ const ct = scalarStorageC(typed.type);
271
+ const bytes = scalarSize(typed.type);
272
+ const t = this.tmp("arg");
273
+ this.line(`${ct} ${t} = (${ct})(${typed.c});`);
274
+ put(`&${t}`, String(bytes), bytes);
275
+ }
276
+ else
277
+ this.fail(node, `${typeName(typed.type)} cannot be serialized here`);
278
+ }
279
+ /** Borsh-encode a data-enum place: the tag byte, then the active variant's fields. */
280
+ serializeDataEnum(node, name, put) {
281
+ const src = this.ref(node);
282
+ if (!src || src.type.kind !== "dataEnum" || src.type.name !== name)
283
+ this.fail(node, `expected a ${name}`);
284
+ this.serializeDataEnumLv(src.lv, name, put);
285
+ }
286
+ serializeDataEnumLv(lv, name, put) {
287
+ const src = { lv };
288
+ const e = this.model.dataEnums.get(name);
289
+ put(`&${src.lv}.tag`, "1", 1);
290
+ this.line(`switch (${src.lv}.tag) {`);
291
+ e.variants.forEach((v, i) => {
292
+ this.line(`case ${i}: {`);
293
+ for (const f of v.fields) {
294
+ const at = `${src.lv}.v.${v.name}.${f.name}`;
295
+ if (f.type.kind === "string") {
296
+ // Borsh String: u32 length, then the bytes.
297
+ const n = this.tmp("sl");
298
+ this.line(`uint32_t ${n} = (uint32_t)${at}.len;`);
299
+ put(`&${n}`, "4");
300
+ put(`${at}.ptr`, `${at}.len`);
301
+ continue;
302
+ }
303
+ if (f.type.kind === "dataEnum" && this.model.dataEnums.get(f.type.name)?.variable) {
304
+ this.serializeDataEnumLv(at, f.type.name, put);
305
+ continue;
306
+ }
307
+ const n = this.fieldBytes(f.type);
308
+ // put() with no static size: the payload differs by variant.
309
+ put(`&${at}`, String(n));
310
+ }
311
+ this.line(`break; }`);
312
+ });
313
+ this.line(`}`);
314
+ }
315
+ /** Structs reachable through the fields of struct `name` (not including itself unless it recurses). */
316
+ nestedStructs(name) {
317
+ const out = new Set();
318
+ const visit = (t) => {
319
+ if (t.kind === "struct") {
320
+ if (out.has(t.name))
321
+ return;
322
+ out.add(t.name);
323
+ this.model.structs.get(t.name)?.fields.forEach((f) => visit(f.type));
324
+ }
325
+ else if (t.kind === "array" || t.kind === "vec")
326
+ visit(t.elem);
327
+ else if (t.kind === "option" && t.inner.kind === "struct")
328
+ visit(t.inner);
329
+ else if (t.kind === "dataEnum")
330
+ this.model.dataEnums.get(t.name)?.variants.forEach((v) => v.fields.forEach((f) => visit(f.type)));
331
+ };
332
+ this.model.structs.get(name)?.fields.forEach((f) => visit(f.type));
333
+ return out;
334
+ }
335
+ /** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
336
+ fixedLayoutStructs() {
337
+ const out = new Set();
338
+ const visit = (t) => {
339
+ if (t.kind === "struct") {
340
+ if (out.has(t.name))
341
+ return;
342
+ out.add(t.name);
343
+ this.model.structs.get(t.name)?.fields.forEach((f) => visit(f.type));
344
+ }
345
+ else if (t.kind === "array" || t.kind === "vec")
346
+ visit(t.elem);
347
+ else if (t.kind === "option" && t.inner.kind === "struct")
348
+ visit(t.inner);
349
+ else if (t.kind === "dataEnum")
350
+ this.model.dataEnums.get(t.name)?.variants.forEach((v) => v.fields.forEach((f) => visit(f.type)));
351
+ };
352
+ for (const name of [...this.model.accountStructs, ...this.model.argStructs])
353
+ visit({ kind: "struct", name });
354
+ return out;
355
+ }
356
+ }
@@ -1,177 +1,17 @@
1
1
  import ts from "typescript";
2
- import { type AccountParam, type IdlSeed, type ValueType } from "../model.js";
3
- import { type Value } from "./shared.js";
4
- import { CallEmitter } from "./calls.js";
5
- /** One piece of a Metaplex instruction's Borsh data: fixed bytes, or a value lowered and serialized in source order. */
6
- type MplField = {
7
- bytes: number[];
8
- } | {
9
- value: ts.Expression;
10
- type: ValueType;
11
- } | {
12
- c: string;
13
- n: string;
14
- };
15
- /**
16
- * Other programs: PDAs and seeds, account creation, System/Token/ATA/Metaplex CPIs, generic invoke, Borsh
17
- * serialization and events.
18
- */
19
- export declare abstract class CpiEmitter extends CallEmitter {
20
- /**
21
- * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
22
- * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
23
- */
24
- protected seeds(node: ts.Expression, extra: number): {
25
- name: string;
26
- count: number;
27
- idl: IdlSeed[] | undefined;
28
- };
29
- protected describeSeed(el: ts.Expression): IdlSeed | undefined;
30
- protected recordPda(account: AccountParam, idl: IdlSeed[] | undefined): void;
31
- protected create(node: ts.CallExpression, target: AccountParam, topLevel: boolean, ifNeeded?: boolean): Value;
32
- /**
33
- * `vault.create(payer, seeds | null, mint, authority)` on `Init<TokenAccount>` and `mint.create(payer, seeds | null,
34
- * decimals, authority, freezeAuthority | null)` on `Init<Mint>` (Anchor's `init` with `token::` / `mint::`
35
- * constraints): a PDA of this program (or, with `null`, a new keypair account that signs), created owned by the
36
- * instruction's token program and initialized. `createIfNeeded` on `InitIfNeeded<…>` does that unless the account
37
- * exists, and then checks it is that PDA, owned by the token program, and has that mint and owner / those
38
- * authorities and decimals (Anchor's init_if_needed checks). create returns the bump (0 for a keypair),
39
- * createIfNeeded whether it created the account.
40
- */
41
- protected createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
42
- /**
43
- * The extensions in `mint.create(…, { … })` (Anchor's `extensions::…` constraints): their values are evaluated now,
44
- * in source order; the returned lines (each extension's Token-2022 initializer, mint writable, before
45
- * InitializeMint2) run after the account is created, sized for exactly these extensions.
46
- */
47
- protected mintExtensions(lit: ts.ObjectLiteralExpression, tp: string, acct: string, ifNeeded?: boolean): {
48
- space: number;
49
- lines: string[];
50
- checks: string[];
51
- };
52
- /**
53
- * `ata.create(payer)` / `ata.createIfNeeded(payer)` on `Ata<Init|InitIfNeeded<TokenAccount>, "owner", "mint">`
54
- * (Anchor's `init` / `init_if_needed` with `associated_token::…`). create always calls the ATA program's Create, which
55
- * fails if the account exists. createIfNeeded calls it only when the account is still a System account (Anchor's
56
- * test) and otherwise checks that the existing account is that ATA. Either way the account is then checked as an
57
- * initialized token account of that mint and owner, and is a TokenAccount from here on.
58
- */
59
- protected createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
60
- protected systemTransfer(node: ts.CallExpression): undefined;
61
- /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
62
- protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
63
- /**
64
- * Emit a CPI to the program account `program` with these metas (account, writable, signer), and then (`tail`) a range
65
- * of the remaining accounts, read-only (a Merkle proof).
66
- */
67
- protected cpi(program: string, metas: [string, boolean, boolean][], buf: string, len: string, seeds: {
68
- name: string;
69
- count: number | string;
70
- }, tail?: {
71
- from: string;
72
- to: string;
73
- asPassed?: boolean;
74
- }): void;
75
- protected signerSeeds(node: ts.Expression | undefined, authority: AccountParam, at: ts.Node): {
76
- name: string;
77
- count: number | string;
78
- };
79
- /** Seeds to sign a CPI with: an array literal, or a helper's SignerSeeds parameter. */
80
- protected signingSeeds(node: ts.Expression): {
81
- name: string;
82
- count: number | string;
83
- };
84
- protected tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
85
- protected ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
86
- protected metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
87
- /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
88
- protected metadataCollectionOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
89
- /**
90
- * One account of a Metaplex CPI: an account parameter, or `null` for an optional account left out
91
- * (Metaplex programs take their own id in its place).
92
- */
93
- protected mplMeta(n: ts.Expression, program: AccountParam, what: string, writable: boolean, signer: boolean): [string, boolean, boolean];
94
- /** Borsh fields into a fresh buffer: raw bytes ("u8:N" style) or lowered values. */
95
- protected mplData(at: ts.Node, max: number, fields: MplField[]): {
96
- buf: string;
97
- len: string;
98
- };
99
- /**
100
- * Borsh of one Metaplex Core plugin literal (`{ kind: "FreezeDelegate", frozen: true, authority?: … }`): the Plugin
101
- * enum, then (`withAuthority`) the Option<PluginAuthority> that CreateV1's PluginAuthorityPair and AddPluginV1 take.
102
- */
103
- protected corePlugin(n: ts.Expression, withAuthority: boolean): MplField[];
104
- /** CreateV1 / CreateCollectionV1 plugins: Option<Vec<PluginAuthorityPair>>. */
105
- protected corePluginList(n: ts.Expression | undefined): MplField[];
106
- /**
107
- * Metaplex Core: assets and collections (with plugins), plugins and external plugin adapters added, updated, written
108
- * and removed, transfer and burn. Each method is a row of CORE_OPS below: its accounts in order, its data.
109
- */
110
- protected coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
111
- /**
112
- * Core instructions: `args` fixed arguments (then an optional plugin list when `plugins`, then optional signer
113
- * seeds), accounts in order (`[argument, label, writable, signer]`, or "self": the Core program, Core's "none" for an
114
- * optional account), at most `max` bytes of data.
115
- */
116
- private coreOps;
117
- /** The fields of a Core object literal (`{ kind: "AppData", … }`) by name. */
118
- private coreProps;
119
- /** PluginAuthority: "none" | "owner" | "updateAuthority" (literals), or an address. */
120
- private coreAuthority;
121
- private coreOption;
122
- private coreSchema;
123
- /** Vec<(HookableLifecycleEvent, ExternalCheckResult)>: `[{ event: "transfer", canReject: true }, …]`. */
124
- private coreChecks;
125
- /** ExtraAccount: `{ kind: "address", address, isSigner?, isWritable? }` or a preconfigured one (`{ kind: "owner" }`, …). */
126
- private coreExtraAccount;
127
- /**
128
- * ExternalPluginAdapterInitInfo from a literal: `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle",
129
- * baseAddress, checks, resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram, checks,
130
- * extraAccounts?, dataAuthority?, schema? }` and the Linked forms (collections); `authority?` is the plugin's own.
131
- */
132
- protected coreExternalPlugin(n: ts.Expression): MplField[];
133
- /** ExternalPluginAdapterKey: `{ kind: "AppData", dataAuthority }`, `{ kind: "Oracle", address }`, `{ kind: "LifecycleHook", address }`, … */
134
- protected coreExternalKey(n: ts.Expression): MplField[];
135
- /** The data written: Option<Vec<u8>> from a string, a Vec<u8> argument, or null (clears it). */
136
- protected coreExternalData(n: ts.Expression): MplField[];
137
- /** PluginType (u8) from a kind string literal: removePlugin(…, "FreezeDelegate"). */
138
- protected corePluginType(n: ts.Expression): MplField;
139
- /** Bubblegum (compressed NFTs on SPL account compression): createTree, mint (MintV1, no collection, no creators). */
140
- protected bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
141
- /** Bubblegum V2 (trees on mpl-account-compression with mpl-noop; optional Metaplex Core collections). */
142
- protected bubblegumV2(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
143
- /** Object literal properties by name, refusing others. */
144
- protected literalProps(o: ts.ObjectLiteralExpression, allowed: string[], what: string): Map<string, ts.Expression>;
145
- /** Vec<Creator> (address, verified, share) from a literal list; shares add up to 100 when literal. */
146
- protected bubblegumCreators(creators: ts.Expression | undefined): MplField[];
147
- /** UpdateArgs: every field optional (left out or null: unchanged). */
148
- protected bubblegumUpdateArgs(n: ts.Expression): MplField[];
149
- /** `acct.key` of an account parameter, as an expression to serialize. */
150
- protected keyOf(n: ts.Expression): ts.Expression;
151
- /**
152
- * `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
153
- * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
154
- */
155
- protected remainingRange(node: ts.Expression): {
156
- from: string;
157
- to: string;
158
- } | undefined;
2
+ import { MetaplexEmitter } from "./metaplex.js";
3
+ /** Generic CPIs (`invoke`, `invokeInstruction`) and events (`emit`, `emitCpi`). */
4
+ export declare abstract class CpiEmitter extends MetaplexEmitter {
159
5
  protected invoke(node: ts.CallExpression): undefined;
160
6
  /**
161
- * A byte buffer written front to back. Its C declaration is patched in afterwards so it is
162
- * exactly as large as the fixed content, and only falls back to `max` when strings make it dynamic.
7
+ * `invokeInstruction(programId, metas, data, infos, signerSeeds?)`: a CPI decided at run time (Rust's
8
+ * `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`), e.g. one stored in account data. Each
9
+ * meta is a struct with `pubkey`, `isSigner` and `isWritable`; `data` a list of u8; every account in `infos` (the
10
+ * remaining accounts, or a slice of them) goes to the runtime, which finds each meta's account there by key (an
11
+ * account missing there fails the CPI, as under Rust) and checks the privileges: a meta may only be a signer or
12
+ * writable as the transaction passed it, or a PDA of this program that `signerSeeds` sign for.
163
13
  */
164
- protected byteBuffer(prefix: string, max: number, errorCode: string, what: string): {
165
- buf: string;
166
- len: string;
167
- put: (src: string, n: string, bytes?: number) => void;
168
- finish: (at: ts.Node) => void;
169
- };
170
- /** Append a value's Borsh encoding through `put(srcPointer, byteCount)`. */
171
- protected serialize(v: Value, node: ts.Node, put: (src: string, n: string, bytes?: number) => void): void;
172
- /** Borsh-encode a data-enum place: the tag byte, then the active variant's fields. */
173
- protected serializeDataEnum(node: ts.Expression, name: string, put: (src: string, n: string, bytes?: number) => void): void;
174
- protected serializeDataEnumLv(lv: string, name: string, put: (src: string, n: string, bytes?: number) => void): void;
14
+ protected invokeInstruction(node: ts.CallExpression): undefined;
175
15
  protected emitEvent(node: ts.CallExpression, cpi?: {
176
16
  authority: string;
177
17
  program: string;
@@ -180,9 +20,4 @@ export declare abstract class CpiEmitter extends CallEmitter {
180
20
  private emitBorshEvent;
181
21
  /** Discriminator + `body`, logged (emit) or self-invoked (emitCpi). */
182
22
  private sendEvent;
183
- /** Structs reachable through the fields of struct `name` (not including itself unless it recurses). */
184
- protected nestedStructs(name: string): Set<string>;
185
- /** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
186
- protected fixedLayoutStructs(): Set<string>;
187
23
  }
188
- export {};