@typesol/cli 0.43.0 → 0.44.1

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 (66) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/NOTICE +71 -0
  3. package/README.md +25 -11
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +4 -0
  9. package/dist/compiler/emit/alias.d.ts +16 -2
  10. package/dist/compiler/emit/alias.js +70 -6
  11. package/dist/compiler/emit/base.d.ts +3 -1
  12. package/dist/compiler/emit/base.js +20 -3
  13. package/dist/compiler/emit/borsh.js +11 -5
  14. package/dist/compiler/emit/calls.d.ts +13 -0
  15. package/dist/compiler/emit/calls.js +105 -14
  16. package/dist/compiler/emit/cpi-core.d.ts +9 -1
  17. package/dist/compiler/emit/cpi-core.js +51 -10
  18. package/dist/compiler/emit/create.js +22 -11
  19. package/dist/compiler/emit/expressions.js +6 -1
  20. package/dist/compiler/emit/function.js +15 -5
  21. package/dist/compiler/emit/metaplex.js +17 -4
  22. package/dist/compiler/emit/shared.d.ts +17 -0
  23. package/dist/compiler/emit/shared.js +36 -3
  24. package/dist/compiler/emit/statements.js +17 -4
  25. package/dist/compiler/emit/storage.d.ts +2 -0
  26. package/dist/compiler/emit/storage.js +16 -8
  27. package/dist/compiler/emit/token.js +64 -39
  28. package/dist/compiler/index.d.ts +15 -1
  29. package/dist/compiler/index.js +40 -3
  30. package/dist/compiler/toolchain.d.ts +41 -1
  31. package/dist/compiler/toolchain.js +102 -3
  32. package/dist/testing-stake.d.ts +2 -1
  33. package/dist/testing-stake.js +2 -1
  34. package/dist/testing.js +6 -4
  35. package/dist/tools/clientgen.d.ts +15 -0
  36. package/dist/tools/clientgen.js +173 -7
  37. package/dist/tools/cpigen.d.ts +0 -15
  38. package/dist/tools/cpigen.js +19 -8
  39. package/dist/tools/doctor.d.ts +17 -2
  40. package/dist/tools/doctor.js +64 -4
  41. package/dist/tools/portgen.js +43 -18
  42. package/dist/workspace.d.ts +20 -0
  43. package/dist/workspace.js +173 -6
  44. package/docs/ai.md +10 -5
  45. package/docs/architecture.md +1 -1
  46. package/docs/audit.md +103 -18
  47. package/docs/case-study-escrow.md +1 -1
  48. package/docs/case-study-phoenix.md +10 -10
  49. package/docs/case-study-raydium-amm.md +3 -3
  50. package/docs/case-study-spl-stake-pool.md +5 -5
  51. package/docs/cli.md +17 -8
  52. package/docs/client.md +11 -3
  53. package/docs/errors.md +2 -2
  54. package/docs/language.md +16 -9
  55. package/docs/mainnet.md +21 -10
  56. package/docs/migrate-from-anchor.md +2 -1
  57. package/docs/runtime.md +11 -1
  58. package/docs/security-model.md +79 -12
  59. package/docs/stability.md +21 -2
  60. package/docs/testing.md +25 -0
  61. package/docs/troubleshooting.md +12 -0
  62. package/llms-full.txt +216 -63
  63. package/llms.txt +1 -1
  64. package/package.json +3 -1
  65. package/runtime/typesol_rt.h +30 -18
  66. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { calleeName, resolveScalarType, structNameOf } from "../analyze.js";
3
3
  import { isScalar, } from "../model.js";
4
- import { isStable, cString, valueC, fixedVecC, } from "./shared.js";
4
+ import { isStable, cString, valueC, fixedVecC, passedByPointer, } from "./shared.js";
5
5
  /**
6
6
  * State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
7
7
  * scopes, evaluation-order snapshots and account lookups.
@@ -122,6 +122,9 @@ export class EmitterBase {
122
122
  this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type.array, mutable: false, readonly: true, ...owned });
123
123
  else if (p.type.kind === "dataEnumArg")
124
124
  this.args.set(p.name, { c: `p_${p.name}`, type: { kind: "enumRef", name: p.type.name, writable: false }, mutable: false, ...owned });
125
+ // A Pubkey, Option, string or u256 comes as a const pointer (see passedByPointer): read through it.
126
+ else if (passedByPointer(p.type))
127
+ this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type, mutable: false });
125
128
  else
126
129
  this.args.set(p.name, { c: `p_${p.name}`, type: p.type, mutable: false, ...(p.type.kind === "structRef" ? owned : {}) });
127
130
  }
@@ -265,8 +268,13 @@ export class EmitterBase {
265
268
  settle(v, mark) {
266
269
  if (this.lines.length === mark || v.isNull || v.literal !== undefined || v.stringLiteral !== undefined)
267
270
  return v;
268
- if (isStable(v.c))
269
- return v;
271
+ // A local (or a temporary) is stable unless what was emitted since writes it: a closure or list callback expanded
272
+ // in the later operand (`x + bump()` with `bump` doing `x += 1n`), or an outlined loop given its address.
273
+ if (isStable(v.c)) {
274
+ const name = /^(?:\w+|\(&(\w+)\))$/.exec(v.c) ? (/^\w+$/.test(v.c) ? v.c : v.c.slice(2, -1)) : undefined;
275
+ if (!name || !this.writtenSince(name, mark))
276
+ return v;
277
+ }
270
278
  const t = this.tmp("snap");
271
279
  const pad = " ".repeat(this.indent);
272
280
  const decl = [];
@@ -297,6 +305,15 @@ export class EmitterBase {
297
305
  this.lines.splice(mark, 0, ...decl.map((l) => pad + l));
298
306
  return out;
299
307
  }
308
+ /** Whether a C line emitted from `mark` on assigns, increments or takes the address of the C variable `name`. */
309
+ writtenSince(name, mark) {
310
+ const n = name.replace(/\W/g, "");
311
+ const w = new RegExp(`(?:\\b${n}(?:\\.\\w+|\\[[^\\]]*\\])*\\s*(?:[-+*/%&|^]|<<|>>)?=(?!=)|&\\s*\\(?\\s*${n}\\b|\\b${n}\\s*(?:\\+\\+|--)|(?:\\+\\+|--)\\s*${n}\\b)`);
312
+ for (let i = mark; i < this.lines.length; i++)
313
+ if (this.lines[i].includes(n) && w.test(this.lines[i]))
314
+ return true;
315
+ return false;
316
+ }
300
317
  /** A string that stays valid when account data changes: views of account text are copied to the heap. */
301
318
  ownedString(v) {
302
319
  if (v.type.kind !== "string" || !v.c.startsWith("ts_fstr_view"))
@@ -184,8 +184,11 @@ function codec(s, model, o) {
184
184
  ? borshMinSize(variableStruct(t, model), model)
185
185
  : fixedBytes(t, model);
186
186
  const minAfter = s.fields.map((_, i) => s.fields.slice(i + 1).reduce((n, f) => n + minOf(f.type), 0));
187
- const need = (n, rest, pad) => `${pad}if (${n} > len - at - ${rest}) ${DESER};`;
188
- const room = (n, rest, pad) => `${pad}if (${n} > cap - at - ${rest}) ${SER};`;
187
+ // Compared without a subtraction that could wrap: `at` may already be within `rest` of the end (a Some tag or a
188
+ // list element reserves only its own smallest form), and `len - at - rest` would then pass anything. `n` is at
189
+ // most 2^32 elements of at most a few KiB, `at` and `rest` stay near `len`: the sum cannot overflow 64 bits.
190
+ const need = (n, rest, pad) => `${pad}if ((uint64_t)(${n}) + at + ${rest} > len) ${DESER};`;
191
+ const room = (n, rest, pad) => `${pad}if ((uint64_t)(${n}) + at + ${rest} > cap) ${SER};`;
189
192
  // A String / Vec / Option field, `rest` bytes of later fields still to come.
190
193
  const unpackVar = (t, lv, rest, pad) => {
191
194
  switch (t.kind) {
@@ -227,12 +230,13 @@ function codec(s, model, o) {
227
230
  ...(check.length ? [`${pad}for (uint64_t ${i} = 0; ${i} < ${l}; ${i}++) {`, ...check, `${pad}}`] : []),
228
231
  ];
229
232
  }
230
- // Strings: each element's length prefix is checked as it is reached.
233
+ // Strings and structs holding Options: each element's smallest form is checked as it is reached (its length
234
+ // prefix, or its fixed fields and tags), before anything of it is read.
231
235
  const i = tmp("i");
232
236
  return [
233
237
  ...head,
234
238
  `${pad}for (uint64_t ${i} = 0; ${i} < ${l}; ${i}++) {`,
235
- need("4", rest, `${pad} `),
239
+ need(String(minOf(t.elem)), rest, `${pad} `),
236
240
  ...unpackVar(t.elem, `${lv}.items[${i}]`, rest, `${pad} `),
237
241
  `${pad}}`,
238
242
  ];
@@ -263,6 +267,8 @@ function codec(s, model, o) {
263
267
  `${pad}if (${tag} > 1) ${DESER};`,
264
268
  `${pad}${lv}.some = ${tag};`,
265
269
  `${pad}if (${tag}) {`,
270
+ // The tag reserved one byte: the struct's smallest form must be there before its fields are read.
271
+ need(String(minOf(t.inner)), rest, `${pad} `),
266
272
  ...unpackVar(t.inner, `${lv}.v`, rest, `${pad} `),
267
273
  `${pad}}`,
268
274
  ];
@@ -305,7 +311,7 @@ function codec(s, model, o) {
305
311
  for (const f of v.fields) {
306
312
  const flv = `${lv}.v.${v.name}.${f.name}`;
307
313
  if (f.type.kind === "string") {
308
- lines.push(`${pad} if (4 > len - at - ${rest}) ${DESER};`, ...unpackVar(f.type, flv, rest, `${pad} `));
314
+ lines.push(need("4", rest, `${pad} `), ...unpackVar(f.type, flv, rest, `${pad} `));
309
315
  continue;
310
316
  }
311
317
  const n = fixedBytes(f.type, model);
@@ -185,6 +185,12 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
185
185
  protected migrate(node: ts.CallExpression, a: AccountParam, topLevel: boolean): Value | undefined;
186
186
  /** Whether a helper (or one it calls) grows a Vec, which needs the instruction's SystemProgram for rent. */
187
187
  private helperGrows;
188
+ /**
189
+ * After close(acct, dest) the account holds no data and belongs to the System Program: reading or writing it later in
190
+ * the function (or on a later turn of a loop around the close) would read zeros or write bytes that are dropped. The
191
+ * same holds for a reference into it read later. Refused, like a view used after closeRaw (assertNoViewAfter).
192
+ */
193
+ protected assertNotUsedAfterClose(a: AccountParam, at: ts.CallExpression): void;
188
194
  /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
189
195
  private helperResizes;
190
196
  /** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
@@ -209,6 +215,13 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
209
215
  /** A function given for a function parameter of an expanded helper or closure, as something to expand. */
210
216
  protected closureOf(arg: ts.Expression): Closure;
211
217
  protected callHelper(node: ts.CallExpression, h: Helper): Value | undefined;
218
+ /**
219
+ * A Pubkey, Option, string or u256 helper argument, passed as a pointer (see passedByPointer). When the helper can
220
+ * write (it takes accounts or Inout places) and the argument is not a named C object nothing passed can reach (see
221
+ * unreachableArg), the pointer is to a copy taken here: JS gives the helper the value as it is at the call. A
222
+ * helper that writes nothing reads the caller's value in place.
223
+ */
224
+ protected pointerArg(v: Value, mayWrite: boolean): string;
212
225
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
213
226
  protected helperArg(h: Helper, p: Helper["params"][number], n: ts.Expression): Value | string;
214
227
  /**
@@ -4,7 +4,7 @@ import { borshIdentical, borshNativeStructUnsupported } 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, U32, 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, passedByPointer, unreachableArg, } 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.
@@ -219,6 +219,12 @@ export class CallEmitter extends ExpressionEmitter {
219
219
  const d = this.accountParam(args[1], "close's destination");
220
220
  if (!isWritable(d.kind))
221
221
  this.fail(args[1], "the destination must be writable (Mut<...>)");
222
+ // In a helper both may be one account the caller passed twice (Dup<…>): closing into itself is refused.
223
+ if (a.index === -1 || d.index === -1)
224
+ this.line(`if (a_${a.name} == a_${d.name}) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: close's destination is the account itself");`);
225
+ else if (a === d)
226
+ this.fail(args[1], "the destination is the account being closed; name another writable account");
227
+ this.assertNotUsedAfterClose(a, node);
222
228
  this.line(`TS_TRY(ts_close(a_${a.name}, a_${d.name}));`);
223
229
  this.forgetOwners();
224
230
  return undefined;
@@ -372,7 +378,9 @@ export class CallEmitter extends ExpressionEmitter {
372
378
  if (a.type.kind !== "int" || !sameType(a.type, b.type))
373
379
  this.fail(node, `${builtin}(a, b) takes two integers of the same type`);
374
380
  const t = this.tmp("mm");
375
- this.line(`${INT_INFO[a.type.name].c} ${t} = (${a.c} ${builtin === "min" ? "<" : ">"} ${b.c}) ? ${a.c} : ${b.c};`);
381
+ // A u256 is four limbs, compared by the runtime.
382
+ const less = a.type.name === "u256" ? `ts_u256_cmp(${a.c}, ${b.c}) ${builtin === "min" ? "<" : ">"} 0` : `${a.c} ${builtin === "min" ? "<" : ">"} ${b.c}`;
383
+ this.line(`${INT_INFO[a.type.name].c} ${t} = (${less}) ? ${a.c} : ${b.c};`);
376
384
  return { c: t, type: a.type };
377
385
  }
378
386
  case "realloc": {
@@ -709,8 +717,14 @@ export class CallEmitter extends ExpressionEmitter {
709
717
  if (sys.kind.kind !== "system")
710
718
  this.fail(args[3], "pass the SystemProgram parameter");
711
719
  const { name: entries, count } = args[4] ? this.extraAccountMetas(args[4]) : { name: "NULL", count: 0 };
712
- const fn = builtin === "initExtraAccountMetas" ? "ts_init_extra_metas" : "ts_update_extra_metas";
713
- this.line(`TS_TRY(${fn}(params, a_${payer.name}, a_${acct.name}, &a_${mint.name}->key, ${entries}, ${count}));`);
720
+ if (builtin === "initExtraAccountMetas")
721
+ this.line(`TS_TRY(ts_init_extra_metas(params, a_${payer.name}, a_${acct.name}, &a_${mint.name}->key, ${entries}, ${count}));`);
722
+ else {
723
+ // The growth limit counts from the account's length when the instruction started: entry_ in an instruction
724
+ // (function.ts), the length the entrypoint recorded in the record in a helper.
725
+ const entry = this.ix ? `entry_${acct.name}` : `ts_entry_len(a_${acct.name})`;
726
+ this.line(`TS_TRY(ts_update_extra_metas(params, a_${payer.name}, a_${acct.name}, &a_${mint.name}->key, ${entries}, ${count}, ${entry}));`);
727
+ }
714
728
  return undefined;
715
729
  }
716
730
  case "remainingAccounts":
@@ -1138,7 +1152,7 @@ export class CallEmitter extends ExpressionEmitter {
1138
1152
  const tailStart = () => {
1139
1153
  if (!tail)
1140
1154
  return undefined;
1141
- this.assertNotAliased(tail.paths, node);
1155
+ this.assertNotAliased(tail.paths, node, undefined, false, true);
1142
1156
  const at = this.tmp("tail");
1143
1157
  const n = this.tmp("tail_n");
1144
1158
  this.line(`uint8_t *${at} = ${tail.end};`);
@@ -1225,7 +1239,9 @@ export class CallEmitter extends ExpressionEmitter {
1225
1239
  if (args.length !== 0)
1226
1240
  this.fail(node, "pop() takes no arguments");
1227
1241
  needWritable();
1228
- this.assertNotAliased(elemPaths(), node);
1242
+ // A Vec of an account shrinks: the popped element is cut off under every name of the account.
1243
+ const growable = info.cap === undefined && !info.heap;
1244
+ this.assertNotAliased(elemPaths(), node, undefined, false, growable);
1229
1245
  const st = this.storageValueType(vt.elem);
1230
1246
  const n = this.tmp("n");
1231
1247
  this.line(`uint64_t ${n} = ${count};`);
@@ -1246,7 +1262,7 @@ export class CallEmitter extends ExpressionEmitter {
1246
1262
  this.line(`${valueC(st)} ${out} = ${val.c};`);
1247
1263
  result = st.kind === "pubkey" ? { c: `(&${out})`, type: st } : { c: out, type: st };
1248
1264
  }
1249
- const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
1265
+ const t = growable ? tailStart() : undefined;
1250
1266
  if (t)
1251
1267
  this.line(`ts_memmove(${t.at} - ${info.elemSize}, ${t.at}, ${t.n});`);
1252
1268
  this.line(`${info.len} = (uint32_t)(${n} - 1);`);
@@ -1257,7 +1273,7 @@ export class CallEmitter extends ExpressionEmitter {
1257
1273
  if (args.length !== 0)
1258
1274
  this.fail(node, "clear() takes no arguments");
1259
1275
  needWritable();
1260
- this.assertNotAliased(elemPaths(), node);
1276
+ this.assertNotAliased(elemPaths(), node, undefined, false, info.cap === undefined && !info.heap);
1261
1277
  const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
1262
1278
  if (t)
1263
1279
  this.line(`ts_memmove((uint8_t *)${info.items}, ${t.at}, ${t.n});`);
@@ -2346,6 +2362,47 @@ export class CallEmitter extends ExpressionEmitter {
2346
2362
  visit(body);
2347
2363
  return found;
2348
2364
  }
2365
+ /**
2366
+ * After close(acct, dest) the account holds no data and belongs to the System Program: reading or writing it later in
2367
+ * the function (or on a later turn of a loop around the close) would read zeros or write bytes that are dropped. The
2368
+ * same holds for a reference into it read later. Refused, like a view used after closeRaw (assertNoViewAfter).
2369
+ */
2370
+ assertNotUsedAfterClose(a, at) {
2371
+ let fn = at.parent;
2372
+ while (fn && !ts.isFunctionLike(fn))
2373
+ fn = fn.parent;
2374
+ const body = fn && fn.body;
2375
+ if (!body)
2376
+ return;
2377
+ const loops = [];
2378
+ for (let n = at.parent; n && n !== fn; n = n.parent)
2379
+ if (ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n))
2380
+ loops.push(n);
2381
+ const later = (n) => n.pos >= at.end || loops.some((l) => n.pos >= l.pos && n.end <= l.end && !(n.pos >= at.pos && n.end <= at.end));
2382
+ let hit;
2383
+ const visit = (n) => {
2384
+ if (hit)
2385
+ return;
2386
+ // Its address stays what it was: `acct.key` after the close is fine.
2387
+ if (ts.isPropertyAccessExpression(n) && n.name.text === "key" && this.probe(() => this.accountAt(n.expression)) === a)
2388
+ return;
2389
+ // A name or group field naming the account (not a property name: `x.vault`'s `vault` is not `vault`).
2390
+ const named = ts.isPropertyAccessExpression(n) ||
2391
+ (ts.isIdentifier(n) && !(ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) && !ts.isPropertyAssignment(n.parent));
2392
+ if (named && later(n) && this.probe(() => this.accountAt(n)) === a)
2393
+ hit = n;
2394
+ if (!hit)
2395
+ ts.forEachChild(n, visit);
2396
+ };
2397
+ visit(body);
2398
+ if (!hit)
2399
+ for (const scope of this.scopes)
2400
+ for (const l of scope.values())
2401
+ if (l.decl && l.paths?.some((p) => p === a.name || p.startsWith(`${a.name}.`) || p.startsWith(`${a.name}[]`)) && this.usedAfter(l.decl, at))
2402
+ hit = l.decl;
2403
+ if (hit)
2404
+ this.fail(hit, `${a.name} is closed by close(${a.name}, …) and used after it: a closed account has no data (writes to it are dropped, reads see zeros). Do everything with ${a.name} before closing it (its key stays readable)`);
2405
+ }
2349
2406
  /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
2350
2407
  helperResizes(body) {
2351
2408
  return this.helperCalls(body, ["closeRaw", "resizeAccount"]);
@@ -2503,6 +2560,8 @@ export class CallEmitter extends ExpressionEmitter {
2503
2560
  // A helper that takes accounts may change account data, so account text it gets is copied first.
2504
2561
  // A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
2505
2562
  const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
2563
+ // What a helper can write: account data (through its accounts) and the caller's places it takes as Inout<T>.
2564
+ const mayWrite = takesAccounts || h.params.some((p) => p.inout);
2506
2565
  // A helper that closes or resizes an account it is given ends the caller's views of it (any account it may be).
2507
2566
  if (takesAccounts && this.helperResizes(h.node))
2508
2567
  this.assertNoViewAfter("?", node, `${h.display}() (it may close or resize an account it is given)`);
@@ -2521,16 +2580,21 @@ export class CallEmitter extends ExpressionEmitter {
2521
2580
  pieces.push(raw);
2522
2581
  else {
2523
2582
  pieces.push(values.length);
2524
- values.push(takesAccounts ? this.ownedString(raw) : raw);
2583
+ // Text viewing account data or an Inout place may change under the helper: it gets the bytes as they are now.
2584
+ values.push(mayWrite ? this.ownedString(raw) : raw);
2525
2585
  }
2526
2586
  });
2527
2587
  if (h.params.some((p) => p.inout))
2528
2588
  this.checkInoutCall(node, h, argNodes, pieces.map((x) => (typeof x === "string" ? x : undefined)));
2529
- // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased).
2589
+ // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased): the
2590
+ // account however it is named here (a parameter, an account group's field, a struct loaded with loadAccountMut).
2530
2591
  for (const [i, p] of h.params.entries())
2531
- if (p.account && p.account.kind === "account" && p.account.mut && ts.isIdentifier(argNodes[i]))
2532
- this.assertNotAliased([argNodes[i].text], node, h.display);
2533
- const args = ["params", ...pieces.map((x) => (typeof x === "number" ? (values[x].type.kind === "pubkey" ? `*(${values[x].c})` : values[x].c) : x))];
2592
+ if (p.account && p.account.kind === "account" && p.account.mut)
2593
+ this.assertNotAliased(this.pathsOf(argNodes[i]), node, h.display, true, true);
2594
+ const args = [
2595
+ "params",
2596
+ ...pieces.map((x) => (typeof x === "number" ? (passedByPointer(values[x].type) ? this.pointerArg(values[x], mayWrite) : values[x].c) : x)),
2597
+ ];
2534
2598
  if (!h.returns) {
2535
2599
  this.line(`TS_TRY(fn_${h.name}(${args.join(", ")}));`);
2536
2600
  return undefined;
@@ -2552,6 +2616,32 @@ export class CallEmitter extends ExpressionEmitter {
2552
2616
  this.line(`TS_TRY(fn_${h.name}(${[...args, `&${t}`].join(", ")}));`);
2553
2617
  return h.returns.kind === "pubkey" ? { c: `(&${t})`, type: h.returns } : { c: t, type: h.returns };
2554
2618
  }
2619
+ /**
2620
+ * A Pubkey, Option, string or u256 helper argument, passed as a pointer (see passedByPointer). When the helper can
2621
+ * write (it takes accounts or Inout places) and the argument is not a named C object nothing passed can reach (see
2622
+ * unreachableArg), the pointer is to a copy taken here: JS gives the helper the value as it is at the call. A
2623
+ * helper that writes nothing reads the caller's value in place.
2624
+ */
2625
+ pointerArg(v, mayWrite) {
2626
+ if (v.type.kind === "pubkey") {
2627
+ if (!mayWrite || unreachableArg(v.c, true))
2628
+ return v.c;
2629
+ const t = this.tmp("argk");
2630
+ this.line(`SolPubkey ${t} = *(${v.c});`);
2631
+ return `(&${t})`;
2632
+ }
2633
+ const own = /^\(\*(p_\w+)\)$/.exec(v.c);
2634
+ if (own)
2635
+ return own[1];
2636
+ if (/^\w+$/.test(v.c))
2637
+ return `(&${v.c})`;
2638
+ // A field read in place (`d_x->opt`): an Option's C struct is packed, so its address is fine to take.
2639
+ if (!mayWrite && v.type.kind === "option" && /^\w+(?:(?:->|\.)\w+)+$/.test(v.c))
2640
+ return `(&${v.c})`;
2641
+ const t = this.tmp("argv");
2642
+ this.line(`${valueC(v.type)} ${t} = ${v.c};`);
2643
+ return `(&${t})`;
2644
+ }
2555
2645
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
2556
2646
  helperArg(h, p, n) {
2557
2647
  if (p.account) {
@@ -2952,7 +3042,8 @@ export class CallEmitter extends ExpressionEmitter {
2952
3042
  if (ts.isCallExpression(n) && this.exportName(n.expression) === "signer") {
2953
3043
  if (n.arguments.length !== 1)
2954
3044
  this.fail(n, "signer([...seeds]) takes the seeds (with the bump) as an array; signer([]) signs for nothing");
2955
- return this.seeds(n.arguments[0], 0);
3045
+ // Bound to a name or given to a helper: the list outlives this expression, so its seeds are copied now.
3046
+ return this.seeds(n.arguments[0], 0, true);
2956
3047
  }
2957
3048
  this.fail(n, "pass signer([...seeds with the bump]) or a SignerSeeds parameter");
2958
3049
  }
@@ -8,11 +8,19 @@ export declare abstract class CpiCoreEmitter extends ViewEmitter {
8
8
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
9
9
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
10
10
  */
11
- protected seeds(node: ts.Expression, extra: number): {
11
+ protected seeds(node: ts.Expression, extra: number, bound?: boolean): {
12
12
  name: string;
13
13
  count: number;
14
14
  idl: IdlSeed[] | undefined;
15
15
  };
16
+ /**
17
+ * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
18
+ * also count as pure the byte readers (`data.readU64(i)`) and a stake sysvar slot's `named(account, address)`
19
+ * marker, which only read (their arguments still count).
20
+ */
21
+ protected runsCode(n: ts.Node, readers?: boolean): boolean;
22
+ /** A call that runs none of the program's code and writes nothing: an integer cast, min / max, a list's get(i). */
23
+ protected pureCall(n: ts.CallExpression): boolean;
16
24
  protected describeSeed(el: ts.Expression): IdlSeed | undefined;
17
25
  protected recordPda(account: AccountParam, idl: IdlSeed[] | undefined): void;
18
26
  /**
@@ -10,21 +10,38 @@ export class CpiCoreEmitter extends ViewEmitter {
10
10
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
11
11
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
12
12
  */
13
- seeds(node, extra) {
13
+ seeds(node, extra, bound = false) {
14
14
  if (!ts.isArrayLiteralExpression(node))
15
15
  this.fail(node, "seeds must be an array literal");
16
16
  if (node.elements.length > MAX_SEEDS)
17
17
  this.fail(node, `at most ${MAX_SEEDS} seeds`);
18
18
  const parts = [];
19
19
  let idl = [];
20
- // Without calls or writes among the seeds, nothing can change a seed before the CPI reads it: account fields are
21
- // then passed in place instead of copied.
22
- const mutates = (n) => ts.isCallExpression(n) ||
23
- (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
24
- ts.isPrefixUnaryExpression(n) ||
25
- ts.isPostfixUnaryExpression(n) ||
26
- ts.forEachChild(n, mutates) === true;
27
- const inPlace = !node.elements.some(mutates);
20
+ // The array points at its seeds, which are read when the CPI runs. Seeds that are not constants are copied when
21
+ // the list is written, as JS reads them then, unless nothing can run between the list and the CPI that reads it:
22
+ // no calls or writes among the seeds, nor in the other arguments of the call consuming the list (evaluated before
23
+ // or after it). A list bound to a name or passed to a helper (`bound`) outlives its expression: always copied.
24
+ const mutates = (n) => this.runsCode(n);
25
+ // The argument holding the list (`signer([…])`, a list of signer lists, an object of CPI options) and the call it
26
+ // is an argument of.
27
+ let consumer = node.parent;
28
+ let list = node;
29
+ const wraps = (n) => ts.isParenthesizedExpression(n) ||
30
+ ts.isArrayLiteralExpression(n) ||
31
+ ts.isObjectLiteralExpression(n) ||
32
+ ts.isPropertyAssignment(n) ||
33
+ (ts.isCallExpression(n) && this.exportName(n.expression) === "signer");
34
+ while (consumer && wraps(consumer)) {
35
+ list = consumer;
36
+ consumer = consumer.parent;
37
+ }
38
+ const others = consumer && ts.isCallExpression(consumer) ? consumer.arguments.filter((a) => a !== list) : [];
39
+ const inPlace = !bound && !mutates(list) && !others.some(mutates);
40
+ // Seeds no write can change: account keys, constants, instruction arguments, a helper's by-pointer parameters.
41
+ const constant = (el, c) => /^\(?&\w+->key\)?$/.test(c) ||
42
+ /^\(&(?:TSK_|arg_)\w+\)$/.test(c) ||
43
+ /^\(&\(\*p_\w+\)\)$/.test(c) ||
44
+ (ts.isIdentifier(el) && /^\(&\w+\)$/.test(c) && this.lookup(el.text)?.mutable === false);
28
45
  const mark = this.lines.length;
29
46
  for (const el of node.elements) {
30
47
  const desc = this.describeSeed(el);
@@ -55,7 +72,7 @@ export class CpiCoreEmitter extends ViewEmitter {
55
72
  }
56
73
  // Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
57
74
  const v = this.expr(el);
58
- if (v.type.kind === "pubkey" && (isStable(v.c) || (inPlace && /^\(&d_\w+(->\w+)+\)$/.test(v.c))))
75
+ if (v.type.kind === "pubkey" && (constant(el, v.c) || (inPlace && (isStable(v.c) || /^\(&d_\w+(->\w+)+\)$/.test(v.c)))))
59
76
  parts.push(`{(const uint8_t *)${v.c.startsWith("(") ? v.c : `(${v.c})`}, 32}`);
60
77
  else if (v.type.kind === "int" && inPlace && v.literal === undefined && /^d_\w+(->\w+)+$/.test(v.c))
61
78
  parts.push(`{(const uint8_t *)&${v.c}, ${INT_INFO[v.type.name].bytes}}`);
@@ -100,6 +117,30 @@ export class CpiCoreEmitter extends ViewEmitter {
100
117
  this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
101
118
  return { name, count: parts.length, idl };
102
119
  }
120
+ /**
121
+ * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
122
+ * also count as pure the byte readers (`data.readU64(i)`) and a stake sysvar slot's `named(account, address)`
123
+ * marker, which only read (their arguments still count).
124
+ */
125
+ runsCode(n, readers = false) {
126
+ if (readers &&
127
+ ts.isCallExpression(n) &&
128
+ ((ts.isPropertyAccessExpression(n.expression) && /^read(?:U8|U16|U32|U64|U128|Pubkey)$/.test(n.expression.name.text)) ||
129
+ this.exportName(n.expression) === "named"))
130
+ return ts.forEachChild(n, (c) => this.runsCode(c, true)) === true;
131
+ return ((ts.isCallExpression(n) && !this.pureCall(n)) ||
132
+ (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
133
+ (ts.isPrefixUnaryExpression(n) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) ||
134
+ ts.isPostfixUnaryExpression(n) ||
135
+ ts.forEachChild(n, (c) => this.runsCode(c, readers)) === true);
136
+ }
137
+ /** A call that runs none of the program's code and writes nothing: an integer cast, min / max, a list's get(i). */
138
+ pureCall(n) {
139
+ const fn = this.exportName(n.expression);
140
+ if (fn && (Object.hasOwn(INT_INFO, fn) || fn === "min" || fn === "max" || fn === "bigEndian"))
141
+ return true;
142
+ return ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get" && n.arguments.length === 1;
143
+ }
103
144
  describeSeed(el) {
104
145
  // Anchor's IDL records `x.to_be_bytes()` as the argument (or field) itself, without the byte order.
105
146
  if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian" && el.arguments.length === 1)
@@ -321,18 +321,20 @@ export class CreateEmitter extends CpiCoreEmitter {
321
321
  // Each initializer: its bytes, then a CPI with the mint as the only (writable) account.
322
322
  const lines = [];
323
323
  const cpi = (bytes) => {
324
- const total = bytes.reduce((n, [, k]) => n + k, 0);
324
+ const total = bytes.reduce((n, b) => n + (Array.isArray(b) ? b[1] : 33), 0);
325
325
  const buf = this.tmp("xd");
326
326
  lines.push(`{ uint8_t ${buf}[${total}]; uint64_t at = 0;`);
327
- for (const [src, n] of bytes)
328
- lines.push(` ts_memcpy(${buf} + at, ${src}, ${n}); at += ${n};`);
327
+ for (const b of bytes)
328
+ if (Array.isArray(b))
329
+ lines.push(` ts_memcpy(${buf} + at, ${b[0]}, ${b[1]}); at += ${b[1]};`);
330
+ else
331
+ lines.push(` ${buf}[at++] = ${b.option}.some ? 1 : 0;`, ` if (${b.option}.some) { ts_memcpy(${buf} + at, &${b.option}.v, 32); at += 32; }`);
329
332
  lines.push(` SolAccountMeta m[1] = {{&${acct}->key, true, false}};`, ` TS_TRY(ts_cpi(params, ${tp}, ${buf}, at, m, 1, NULL, 0)); }`);
330
333
  };
331
334
  const tag = (n) => `(const uint8_t[]){${n}}`;
332
- const coption = (t) => [
333
- [`(const uint8_t[]){${t}.some ? 1 : 0}`, 1],
334
- [`&${t}.v`, 32],
335
- ];
335
+ // Token-2022's COption<Pubkey> in instruction data (pack_pubkey_option): a tag byte, then the key only when Some.
336
+ // A None is one byte, and Token-2022 reads the next field right after it.
337
+ const coption = (t) => [{ option: t }];
336
338
  let space = 0;
337
339
  for (const name of Object.keys(KINDS)) {
338
340
  const v = held.get(name);
@@ -441,8 +443,11 @@ export class CreateEmitter extends CpiCoreEmitter {
441
443
  checks.push(`{ SolPubkey k, w = ${want}; if (!ts_t22_key(${acct}, ${c.type}, ${at}, &k)) ts_memzero(&k, 32); if (!ts_key_eq(&k, &w)) TS_FAIL(${c.code + 1 + i}, "TypeSOL: the mint's ${name} ${f === "v" ? "key" : f} differs"); }`);
442
444
  });
443
445
  }
444
- // Base account (165, the mint padded to an account's size), the account type byte, then each TLV entry.
445
- return { space: 165 + 1 + space, lines, checks };
446
+ // Base account (165, the mint padded to an account's size), the account type byte, then each TLV entry. A total of
447
+ // 355 is a Multisig's length, which Token-2022 never gives a mint: its own size calculation adds 2 bytes then
448
+ // (try_calculate_account_len), and InitializeMint2 refuses an account of any other size.
449
+ const total = 165 + 1 + space;
450
+ return { space: total === 355 ? total + 2 : total, lines, checks };
446
451
  }
447
452
  /**
448
453
  * `ata.create(payer)` / `ata.createIfNeeded(payer)` on `Ata<Init|InitIfNeeded<TokenAccount>, "owner", "mint">`
@@ -490,6 +495,9 @@ export class CreateEmitter extends CpiCoreEmitter {
490
495
  this.fail(node, `${call}(...) needs to know the token program: pass it, ${call}(payer, ${tokenPrograms[0].name}) (found ${tokenPrograms.map((o) => o.name).join(", ")})`);
491
496
  }
492
497
  const { owner, mint } = target.constraints.ata;
498
+ // The Associated Token Account program takes the owner as an account of the instruction, not as a key.
499
+ if (owner.startsWith("@"))
500
+ this.fail(node, `${call}(...) creates the account through the Associated Token Account program, which needs the owner as an account: "${owner}" is a stored key. Take the owner as a parameter (checked against ${owner.slice(1)}) and name it in Ata<…>`);
493
501
  const a = `a_${target.name}`;
494
502
  const create = `TS_TRY(ts_ata_create(params, a_${ataProgram.name}, a_${payer.name}, ${a}, a_${owner}, a_${mint}, a_${system.name}, a_${tokenProgram.name}, false));`;
495
503
  let result;
@@ -533,9 +541,12 @@ export class CreateEmitter extends CpiCoreEmitter {
533
541
  if (a.length === 3)
534
542
  this.line(`TS_TRY(ts_system_transfer(params, ${from.c}, ${to.c}, ${amt.c}));`);
535
543
  else {
536
- // A system-owned PDA of this program (a SOL vault) pays.
544
+ // A system-owned PDA of this program (a SOL vault) pays. JS reads the amount before the seed list: copied first
545
+ // when the list runs code that may change it.
546
+ const mark = this.lines.length;
537
547
  const s = this.signingSeeds(a[3]);
538
- this.line(`TS_TRY(ts_system_transfer_signed(params, ${from.c}, ${to.c}, ${amt.c}, ${s.name}, ${s.count}));`);
548
+ const lamports = this.runsCode(a[3], true) ? this.settle(amt, mark) : amt;
549
+ this.line(`TS_TRY(ts_system_transfer_signed(params, ${from.c}, ${to.c}, ${lamports.c}, ${s.name}, ${s.count}));`);
539
550
  }
540
551
  return undefined;
541
552
  }
@@ -885,10 +885,13 @@ export class ExpressionEmitter extends StorageEmitter {
885
885
  }
886
886
  if (exp.type.kind !== "int")
887
887
  this.fail(node.right, "the exponent of ** must be an integer");
888
+ // Any exponent past 255 overflows unless the base is 0 or 1: a u256 one is not needed, and has no C shift.
889
+ if (exp.type.name === "u256")
890
+ this.fail(node.right, "the exponent of ** is a u128 or smaller integer: convert it (u64(e))");
888
891
  const r = this.tmp("pr");
889
892
  const sq = this.tmp("ps");
890
893
  const e = this.tmp("pe");
891
- this.line(`${ct} ${r} = 1;`);
894
+ this.line(`${ct} ${r} = ${type.name === "u256" ? intLiteral(1n, "u256") : "1"};`);
892
895
  this.line(`${ct} ${sq} = ${base.c};`);
893
896
  if (INT_INFO[exp.type.name].signed)
894
897
  this.line(`if (${exp.c} < 0) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: negative exponent");`);
@@ -1131,6 +1134,8 @@ export class ExpressionEmitter extends StorageEmitter {
1131
1134
  // (in JS the bigint would just grow). `>>` on signed types is arithmetic, as in JS.
1132
1135
  if (right.type.kind !== "int")
1133
1136
  this.fail(node, "shift amounts must be integers");
1137
+ if (right.type.name === "u256")
1138
+ this.fail(node, "shift by a u64 (or smaller) amount");
1134
1139
  const bits = INT_INFO[type.name].bytes * 8;
1135
1140
  const sh = this.tmp("sh");
1136
1141
  const rinfo = INT_INFO[right.type.name];
@@ -152,14 +152,14 @@ export class FunctionEmitter extends StatementEmitter {
152
152
  head.push(...vecLenCheck(k.struct, v, `d_${a.name}`));
153
153
  }
154
154
  }
155
- // realloc(x, …) needs the size the account had when the instruction started (the 10 KiB growth limit).
155
+ // realloc(x, …) needs the size the account had when the instruction started (the 10 KiB growth limit), as does
156
+ // updateExtraAccountMetas(payer, x, …).
156
157
  const reallocated = (() => {
157
158
  let found = false;
158
159
  const visit = (nd) => {
159
- if (ts.isCallExpression(nd) &&
160
- ["realloc", "resizeAccount"].includes(this.exportName(nd.expression) ?? "") &&
161
- nd.arguments[0] &&
162
- this.accountAt(nd.arguments[0]) === a)
160
+ const fn = ts.isCallExpression(nd) ? (this.exportName(nd.expression) ?? "") : "";
161
+ const target = ts.isCallExpression(nd) ? nd.arguments[fn === "updateExtraAccountMetas" ? 1 : 0] : undefined;
162
+ if (["realloc", "resizeAccount", "updateExtraAccountMetas"].includes(fn) && target && this.accountAt(target) === a)
163
163
  found = true;
164
164
  ts.forEachChild(nd, visit);
165
165
  };
@@ -197,6 +197,16 @@ export class FunctionEmitter extends StatementEmitter {
197
197
  // here, not closed, not a @layout borsh heap copy (a lost update when packed back). A close destination is in place:
198
198
  // a duplicate shares its record, so the rent lands in both views.
199
199
  const closing = new Set(ix.accounts.flatMap((a) => (a.constraints.closeTo ? [a.name] : [])));
200
+ // An account the body closes with close(account, destination) is closed too.
201
+ const visitClose = (nd) => {
202
+ if (ts.isCallExpression(nd) && this.exportName(nd.expression) === "close" && nd.arguments[0]) {
203
+ const closed = this.accountAt(nd.arguments[0]);
204
+ if (closed)
205
+ closing.add(closed.name);
206
+ }
207
+ ts.forEachChild(nd, visitClose);
208
+ };
209
+ visitClose(ix.node.body);
200
210
  const inPlace = (a) => {
201
211
  const k = a.kind;
202
212
  if (closing.has(a.name))
@@ -327,9 +327,12 @@ export class MetaplexEmitter extends TokenEmitter {
327
327
  for (const k of ["name", "symbol", "uri", "sellerFeeBasisPoints"])
328
328
  if (!props.has(k))
329
329
  this.fail(a[2], `data needs ${k} (it replaces the whole DataV2)`);
330
+ // A view of account text is read at the call: copied first when another argument runs code that may rewrite it.
331
+ const others = (n) => [...props.values(), ...a.slice(3)].some((o) => o !== n && this.runsCode(o, true));
330
332
  const text = (k) => {
331
333
  const t = this.tmp("md");
332
- this.line(`TS_Str ${t} = ${this.expect(this.expr(props.get(k), STRING), STRING, props.get(k)).c};`);
334
+ const v = this.expect(this.expr(props.get(k), STRING), STRING, props.get(k));
335
+ this.line(`TS_Str ${t} = ${(others(props.get(k)) ? this.ownedString(v) : v).c};`);
333
336
  return t;
334
337
  };
335
338
  [name, symbol, uri] = ["name", "symbol", "uri"].map(text);
@@ -353,9 +356,19 @@ export class MetaplexEmitter extends TokenEmitter {
353
356
  this.line(`SolPubkey ${t} = *(${key.c});`);
354
357
  next = `&${t}`;
355
358
  }
356
- const flag = (n) => (isNull(n) ? "-1" : `((${this.expect(this.expr(n, BOOL), BOOL, n).c}) ? 1 : 0)`);
357
- const primary = flag(a[4]);
358
- const mutable = flag(a[5]);
359
+ const flag = (i) => {
360
+ if (isNull(a[i]))
361
+ return "-1";
362
+ const f = `((${this.expect(this.expr(a[i], BOOL), BOOL, a[i]).c}) ? 1 : 0)`;
363
+ if (!a.slice(i + 1).some((n) => this.runsCode(n, true)))
364
+ return f;
365
+ // Read before a later argument that runs code, as JS reads it.
366
+ const t = this.tmp("flag");
367
+ this.line(`int ${t} = ${f};`);
368
+ return t;
369
+ };
370
+ const primary = flag(4);
371
+ const mutable = flag(5);
359
372
  const seeds = this.signerSeeds(a[6], ua, a[1]);
360
373
  this.line(`TS_TRY(ts_mpl_update_v2(params, a_${program.name}, a_${metadata.name}, a_${ua.name}, ${hasData}, ${name}, ${symbol}, ${uri}, ${fee}, ${creators}, ${ncreators}, ${collection}, ${next}, ${primary}, ${mutable}, ${seeds.name}, ${seeds.count}));`);
361
374
  return undefined;