@typesol/cli 0.28.0 → 0.30.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 (48) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +2 -2
  3. package/dist/cli.js +13 -20
  4. package/dist/compiler/analyze.d.ts +6 -2
  5. package/dist/compiler/analyze.js +57 -15
  6. package/dist/compiler/diagnostics.d.ts +2 -0
  7. package/dist/compiler/diagnostics.js +3 -2
  8. package/dist/compiler/emit/alias.d.ts +48 -0
  9. package/dist/compiler/emit/alias.js +166 -0
  10. package/dist/compiler/emit/borsh.js +6 -3
  11. package/dist/compiler/emit/calls.js +21 -4
  12. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  13. package/dist/compiler/emit/cpi-core.js +356 -0
  14. package/dist/compiler/emit/cpi.d.ts +3 -177
  15. package/dist/compiler/emit/cpi.js +13 -2721
  16. package/dist/compiler/emit/create.d.ts +39 -0
  17. package/dist/compiler/emit/create.js +548 -0
  18. package/dist/compiler/emit/function.d.ts +11 -2
  19. package/dist/compiler/emit/function.js +42 -7
  20. package/dist/compiler/emit/metaplex.d.ts +78 -0
  21. package/dist/compiler/emit/metaplex.js +1345 -0
  22. package/dist/compiler/emit/program.js +24 -4
  23. package/dist/compiler/emit/shared.d.ts +7 -1
  24. package/dist/compiler/emit/shared.js +11 -2
  25. package/dist/compiler/emit/statements.d.ts +0 -9
  26. package/dist/compiler/emit/statements.js +2 -53
  27. package/dist/compiler/emit/storage.d.ts +5 -20
  28. package/dist/compiler/emit/storage.js +40 -106
  29. package/dist/compiler/emit/token.d.ts +8 -0
  30. package/dist/compiler/emit/token.js +493 -0
  31. package/dist/compiler/index.js +1 -1
  32. package/dist/compiler/model.d.ts +10 -2
  33. package/dist/compiler/model.js +7 -1
  34. package/dist/tools/portgen.js +3 -0
  35. package/dist/workspace.d.ts +1 -1
  36. package/dist/workspace.js +3 -1
  37. package/docs/architecture.md +30 -2
  38. package/docs/audit.md +3 -2
  39. package/docs/case-study-multisig.md +31 -29
  40. package/docs/cli.md +7 -4
  41. package/docs/errors.md +3 -2
  42. package/docs/language.md +4 -3
  43. package/docs/migrate-from-anchor.md +3 -3
  44. package/docs/security-model.md +1 -1
  45. package/lib/typesol.d.ts +17 -6
  46. package/package.json +1 -1
  47. package/runtime/typesol_rt.h +85 -1
  48. package/ts-plugin/index.js +75 -39
@@ -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
+ }
@@ -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
+ }