@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
@@ -177,6 +177,23 @@ export declare function fieldC(t: FieldType): string;
177
177
  export declare function storageDecl(t: FieldType, name: string): string;
178
178
  /** Why an account of kind `have` cannot be passed where a helper takes `want`, or undefined when it can. */
179
179
  export declare function accountMismatch(have: ParamKind, want: ParamKind): string | undefined;
180
+ /**
181
+ * Helper parameters held in a C struct (a Pubkey, an Option, a string view, a u256) that are passed as a const pointer
182
+ * instead of by value. The SBF target passes every C struct argument `byval`, as a pointer to the caller's object, and
183
+ * its backend makes no copy: a helper that is not inlined then reads the caller's object itself, and sees its own writes
184
+ * to it (`rotate(v, v.admin)` reading v.admin after `v.admin = …`). A copy written in C does not help either: clang
185
+ * forwards it into the byval argument, as byval promises a copy. So these are pointers, and the call site copies what
186
+ * the helper could write (see Calls.pointerArg); a pointer to a copy is kept, as the helper may write the original.
187
+ */
188
+ export declare const passedByPointer: (t: ValueType) => boolean;
189
+ /**
190
+ * Whether a C argument names memory that no helper can write: a named C object (a local, a temporary, an instruction
191
+ * argument, a constant), a field of a struct instruction argument (decoded into memory of its own, read-only), an
192
+ * account's key, the program's id, or a helper's own by-pointer parameter. `c` is the pointer for a Pubkey, the
193
+ * value otherwise. A helper's by-pointer parameter points at a copy, or at an object the helper cannot reach: helpers
194
+ * reach memory only through the accounts, remaining accounts and Inout places they are given, and pass on a subset.
195
+ */
196
+ export declare const unreachableArg: (c: string, pubkey: boolean) => boolean;
180
197
  /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
181
198
  export declare function helperSignature(h: Helper): string;
182
199
  export interface EmitOptions {
@@ -26,7 +26,14 @@ export const STRING = { kind: "string" };
26
26
  export const HASH = { kind: "pubkey", hash: true };
27
27
  export const cBytes = (bytes) => `{${bytes.join(", ")}}`;
28
28
  /** C expressions that nothing in a TypeSOL expression can change: temporaries, locals, arguments, account keys, constants. */
29
- export const isStable = (c) => /^\w+$/.test(c) || /^\(&\w+\)$/.test(c) || /^&\w+->key$/.test(c) || /^\(\(uint8_t\)\d+\)$/.test(c) || /^\(?-?\d+U?LL\)?$/.test(c);
29
+ export const isStable = (c) => /^\w+$/.test(c) ||
30
+ /^\(&\w+\)$/.test(c) ||
31
+ /^&\w+->key$/.test(c) ||
32
+ /^\(\(uint8_t\)\d+\)$/.test(c) ||
33
+ /^\(?-?\d+U?LL\)?$/.test(c) ||
34
+ // A helper's by-pointer parameter (see passedByPointer): nothing the helper does changes what it points at.
35
+ /^\(&?\(\*p_\w+\)\)$/.test(c) ||
36
+ /^\(\*p_\w+\)$/.test(c);
30
37
  /** A C string literal of the UTF-8 bytes. Octal escapes (at most three digits) cannot swallow following characters. */
31
38
  export const cString = (s) => `"${[...Buffer.from(s, "utf8")].map((b) => (b >= 0x20 && b < 0x7f && b !== 0x22 && b !== 0x5c && b !== 0x3f ? String.fromCharCode(b) : `\\${b.toString(8).padStart(3, "0")}`)).join("")}"`;
32
39
  export function intLiteral(value, name) {
@@ -203,6 +210,29 @@ export function accountMismatch(have, want) {
203
210
  }
204
211
  return ok && mutOk ? undefined : name(want);
205
212
  }
213
+ /**
214
+ * Helper parameters held in a C struct (a Pubkey, an Option, a string view, a u256) that are passed as a const pointer
215
+ * instead of by value. The SBF target passes every C struct argument `byval`, as a pointer to the caller's object, and
216
+ * its backend makes no copy: a helper that is not inlined then reads the caller's object itself, and sees its own writes
217
+ * to it (`rotate(v, v.admin)` reading v.admin after `v.admin = …`). A copy written in C does not help either: clang
218
+ * forwards it into the byval argument, as byval promises a copy. So these are pointers, and the call site copies what
219
+ * the helper could write (see Calls.pointerArg); a pointer to a copy is kept, as the helper may write the original.
220
+ */
221
+ export const passedByPointer = (t) => t.kind === "pubkey" || t.kind === "option" || t.kind === "string" || (t.kind === "int" && t.name === "u256");
222
+ /**
223
+ * Whether a C argument names memory that no helper can write: a named C object (a local, a temporary, an instruction
224
+ * argument, a constant), a field of a struct instruction argument (decoded into memory of its own, read-only), an
225
+ * account's key, the program's id, or a helper's own by-pointer parameter. `c` is the pointer for a Pubkey, the
226
+ * value otherwise. A helper's by-pointer parameter points at a copy, or at an object the helper cannot reach: helpers
227
+ * reach memory only through the accounts, remaining accounts and Inout places they are given, and pass on a subset.
228
+ */
229
+ export const unreachableArg = (c, pubkey) => pubkey
230
+ ? /^\(&\w+\)$/.test(c) ||
231
+ /^\(?&\w+->key\)?$/.test(c) ||
232
+ /^\(&\(\*p_\w+\)\)$/.test(c) ||
233
+ c === "params->program_id" ||
234
+ /^\(&\(\*arg_\w+\)(?:\.\w+)+\)$/.test(c)
235
+ : /^\w+$/.test(c) || /^\(\*p_\w+\)$/.test(c) || /^\(\*arg_\w+\)(?:\.\w+)+$/.test(c);
206
236
  /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
207
237
  export function helperSignature(h) {
208
238
  const params = ["TsParams *params"];
@@ -222,8 +252,11 @@ export function helperSignature(h) {
222
252
  // The remaining accounts: the index of the first one among the instruction's accounts.
223
253
  else if (p.type.kind === "remaining")
224
254
  params.push(`uint64_t p_${p.name}`);
225
- else if (p.type.kind === "pubkey")
226
- params.push(`SolPubkey p_${p.name}`); // by value: a copy taken at the call
255
+ // Pubkeys, Options, strings and u256s by pointer (see passedByPointer), never as a C struct by value. `restrict`:
256
+ // nothing changes what it points at while the helper runs (a copy taken for the call, or memory the helper cannot
257
+ // write), so clang may keep what it read in registers across the helper's other writes, as it did for byval.
258
+ else if (passedByPointer(p.type))
259
+ params.push(`const ${p.type.kind === "pubkey" ? "SolPubkey" : valueC(p.type)} *restrict p_${p.name}`);
227
260
  else if (p.type.kind === "arrayArg")
228
261
  params.push(storageDecl(p.type.array, `(*p_${p.name})`));
229
262
  else
@@ -183,8 +183,9 @@ export class StatementEmitter extends CpiEmitter {
183
183
  const typed = subject.literal !== undefined ? this.literal(subject.literal, U64, stmt.expression) : subject;
184
184
  if (typed.type.kind !== "int" && typed.type.kind !== "enum")
185
185
  this.fail(stmt.expression, "switch works on integers and enums");
186
- // C cannot switch on 128-bit values: pick the case's index with comparisons, then switch on that.
187
- const wide = typed.type.kind === "int" && INT_INFO[typed.type.name].bytes === 16;
186
+ // C cannot switch on 128-bit values or u256 limbs: pick the case's index with comparisons, then switch on that.
187
+ const limbs = typed.type.kind === "int" && typed.type.name === "u256";
188
+ const wide = limbs || (typed.type.kind === "int" && INT_INFO[typed.type.name].bytes === 16);
188
189
  const t = this.tmp("sw");
189
190
  this.line(`${scalarC(typed.type)} ${t} = ${typed.c};`);
190
191
  const pick = wide ? this.tmp("swi") : undefined;
@@ -225,7 +226,8 @@ export class StatementEmitter extends CpiEmitter {
225
226
  this.line(`}`);
226
227
  if (pick && cases.length) {
227
228
  const pad = " ".repeat(this.indent);
228
- this.lines.splice(pickAt + 1, 0, ...cases.map((c, i) => `${pad}${i ? "else " : ""}if (${t} == ${c}) ${pick} = ${i};`));
229
+ const eq = (c) => (limbs ? `ts_u256_cmp(${t}, ${c}) == 0` : `${t} == ${c}`);
230
+ this.lines.splice(pickAt + 1, 0, ...cases.map((c, i) => `${pad}${i ? "else " : ""}if (${eq(c)}) ${pick} = ${i};`));
229
231
  }
230
232
  }
231
233
  forLoop(stmt) {
@@ -1990,7 +1992,18 @@ export class StatementEmitter extends CpiEmitter {
1990
1992
  return;
1991
1993
  }
1992
1994
  const mark = this.lines.length;
1993
- const rhs = this.expect(this.expr(valueNode, place.type), place.type, valueNode);
1995
+ // `x <<= n` / `x >>= n`: the amount has a type of its own, as in `x << n` (a literal is a u64).
1996
+ const shift = op === ts.SyntaxKind.LessThanLessThanToken || op === ts.SyntaxKind.GreaterThanGreaterThanToken;
1997
+ let rhs;
1998
+ if (shift) {
1999
+ rhs = this.expr(valueNode);
2000
+ if (rhs.literal !== undefined)
2001
+ rhs = this.literal(rhs.literal, U64, valueNode);
2002
+ if (rhs.type.kind !== "int")
2003
+ this.fail(valueNode, "shift amounts must be integers");
2004
+ }
2005
+ else
2006
+ rhs = this.expect(this.expr(valueNode, place.type), place.type, valueNode);
1994
2007
  current = this.settle(current, mark);
1995
2008
  this.line(place.write(this.arith(op, current, rhs, target).c) + ";");
1996
2009
  return;
@@ -67,6 +67,8 @@ export declare abstract class StorageEmitter extends AliasEmitter {
67
67
  protected lowerInOrder(nodes: readonly ts.Expression[], types: ValueType[]): Value[];
68
68
  /** An index evaluated into a temporary (sign and 128-bit range checked), bounds not yet checked. */
69
69
  protected indexValue(n: ts.Expression): string;
70
+ /** An integer index in a u64 temporary: a negative one, or one past u64 (128-bit, u256 limbs), is out of bounds. */
71
+ private indexTemp;
70
72
  protected checkIndex(t: string, len: string): void;
71
73
  /** Bounds-checked index into a temporary. `len` is a C expression. */
72
74
  protected index(n: ts.Expression, len: string | number): string;
@@ -470,11 +470,24 @@ export class StorageEmitter extends AliasEmitter {
470
470
  const idx = v.literal !== undefined ? this.literal(v.literal, U64, n) : v;
471
471
  if (idx.type.kind !== "int")
472
472
  this.fail(n, "array index must be an integer");
473
+ const t = this.indexTemp(idx);
474
+ return t;
475
+ }
476
+ /** An integer index in a u64 temporary: a negative one, or one past u64 (128-bit, u256 limbs), is out of bounds. */
477
+ indexTemp(idx) {
478
+ if (idx.type.kind !== "int")
479
+ throw new Error("unreachable: an index is an integer");
473
480
  const t = this.tmp("idx");
481
+ const oob = `TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds")`;
482
+ if (idx.type.name === "u256") {
483
+ this.line(`if (!ts_u256_fits(${idx.c}, 64)) ${oob};`);
484
+ this.line(`uint64_t ${t} = (${idx.c}).w[0];`);
485
+ return t;
486
+ }
474
487
  if (INT_INFO[idx.type.name].signed)
475
- this.line(`if (${idx.c} < 0) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
488
+ this.line(`if (${idx.c} < 0) ${oob};`);
476
489
  if (INT_INFO[idx.type.name].bytes === 16)
477
- this.line(`if (${idx.c} > UINT64_MAX) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
490
+ this.line(`if (${idx.c} > UINT64_MAX) ${oob};`);
478
491
  this.line(`uint64_t ${t} = (uint64_t)(${idx.c});`);
479
492
  return t;
480
493
  }
@@ -487,12 +500,7 @@ export class StorageEmitter extends AliasEmitter {
487
500
  const idx = v.literal !== undefined ? this.literal(v.literal, U64, n) : v;
488
501
  if (idx.type.kind !== "int")
489
502
  this.fail(n, "array index must be an integer");
490
- const t = this.tmp("idx");
491
- if (INT_INFO[idx.type.name].signed)
492
- this.line(`if (${idx.c} < 0) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
493
- if (INT_INFO[idx.type.name].bytes === 16)
494
- this.line(`if (${idx.c} > UINT64_MAX) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
495
- this.line(`uint64_t ${t} = (uint64_t)(${idx.c});`);
503
+ const t = this.indexTemp(idx);
496
504
  this.line(`if (${t} >= ${typeof len === "number" ? `${len}ULL` : len}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: array index out of bounds");`);
497
505
  return t;
498
506
  }
@@ -24,15 +24,23 @@ export class TokenEmitter extends CreateEmitter {
24
24
  if (a.length !== fixed && a.length !== fixed + 1)
25
25
  this.fail(node, `${method} takes ${fixed} arguments plus optional signerSeeds`);
26
26
  };
27
- const amount = (n) => this.expect(this.expr(n, U64), U64, n).c;
27
+ /**
28
+ * The amount, then the signer seeds: JS reads the amount first, so it is copied before a seed list that runs code
29
+ * (`["vault", next(st), bump]`) when it reads storage that code may change.
30
+ */
31
+ const amountThenSeeds = (n, seedsNode, auth, at) => {
32
+ const v = this.expect(this.expr(n, U64), U64, n);
33
+ const mark = this.lines.length;
34
+ const s = this.signerSeeds(seedsNode, auth, at);
35
+ return [seedsNode && this.runsCode(seedsNode, true) ? this.settle(v, mark).c : v.c, s];
36
+ };
28
37
  switch (method) {
29
38
  case "transfer": {
30
39
  arity(4);
31
40
  const from = want(a[0], "token", true, "the source");
32
41
  const to = want(a[1], "token", true, "the destination");
33
42
  const auth = this.cpiAccount(a[2], "the authority");
34
- const amt = amount(a[3]);
35
- const s = this.signerSeeds(a[4], auth, a[2]);
43
+ const [amt, s] = amountThenSeeds(a[3], a[4], auth, a[2]);
36
44
  this.line(`TS_TRY(ts_token_transfer(params, ${p}, ${from.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
37
45
  return undefined;
38
46
  }
@@ -42,8 +50,7 @@ export class TokenEmitter extends CreateEmitter {
42
50
  const mint = want(a[1], "mint", false, "the mint");
43
51
  const to = want(a[2], "token", true, "the destination");
44
52
  const auth = this.cpiAccount(a[3], "the authority");
45
- const amt = amount(a[4]);
46
- const s = this.signerSeeds(a[5], auth, a[3]);
53
+ const [amt, s] = amountThenSeeds(a[4], a[5], auth, a[3]);
47
54
  this.line(`TS_TRY(ts_token_transfer_checked(params, ${p}, ${from.c}, ${mint.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
48
55
  return undefined;
49
56
  }
@@ -56,8 +63,7 @@ export class TokenEmitter extends CreateEmitter {
56
63
  this.fail(a[0], "the mint must be a Mut<Mint>, or a Mut<Signer> / Mut<AccountInfo> mint this instruction created");
57
64
  const to = want(a[1], "token", true, "the destination");
58
65
  const auth = this.cpiAccount(a[2], "the mint authority");
59
- const amt = amount(a[3]);
60
- const s = this.signerSeeds(a[4], auth, a[2]);
66
+ const [amt, s] = amountThenSeeds(a[3], a[4], auth, a[2]);
61
67
  this.line(`TS_TRY(ts_token_mint_to(params, ${p}, ${mint.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
62
68
  return undefined;
63
69
  }
@@ -66,8 +72,7 @@ export class TokenEmitter extends CreateEmitter {
66
72
  const from = want(a[0], "token", true, "the burned account");
67
73
  const mint = want(a[1], "mint", true, "the mint");
68
74
  const auth = this.cpiAccount(a[2], "the authority");
69
- const amt = amount(a[3]);
70
- const s = this.signerSeeds(a[4], auth, a[2]);
75
+ const [amt, s] = amountThenSeeds(a[3], a[4], auth, a[2]);
71
76
  this.line(`TS_TRY(ts_token_burn(params, ${p}, ${from.c}, ${mint.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
72
77
  return undefined;
73
78
  }
@@ -82,7 +87,11 @@ export class TokenEmitter extends CreateEmitter {
82
87
  this.fail(a[0], "the mint must be writable (Mut<...>)");
83
88
  const ua = this.cpiAccount(a[1], "the update authority");
84
89
  const ma = this.cpiAccount(a[2], "the mint authority");
85
- const [nm, sym, uri] = [a[3], a[4], a[5]].map((n) => this.expect(this.expr(n, STRING), STRING, n).c);
90
+ // Read at the call: a view of account text is copied first when a later argument runs code that may rewrite it.
91
+ const [nm, sym, uri] = [3, 4, 5].map((i) => {
92
+ const v = this.expect(this.expr(a[i], STRING), STRING, a[i]);
93
+ return (a.slice(i + 1).some((n) => this.runsCode(n, true)) ? this.ownedString(v) : v).c;
94
+ });
86
95
  const s = this.signerSeeds(a[6], ma, a[2]);
87
96
  this.line(`TS_TRY(ts_t22_init_metadata(params, ${p}, ${mint.c}, ${ua.c}, ${ma.c}, ${nm}, ${sym}, ${uri}, ${s.name}, ${s.count}));`);
88
97
  return undefined;
@@ -110,7 +119,15 @@ export class TokenEmitter extends CreateEmitter {
110
119
  this.fail(n, `${what} must be writable (Mut<...>)`);
111
120
  return acct;
112
121
  };
113
- const simple = (tag, fields, metas, seeds) => {
122
+ /**
123
+ * Signer seeds given as a function are lowered after the fields when an argument runs code (JS evaluates the
124
+ * fields first: `approve(src, d, owner, next(st), ["vault", st.count, bump])` signs for the count next() left), and
125
+ * before them otherwise, which keeps those programs' code as it was.
126
+ */
127
+ const seedsFirst = (seeds, fields) => typeof seeds === "function" && !(fields.length && a.some((n) => this.runsCode(n, true))) ? seeds() : seeds;
128
+ const seedsNow = (seeds) => (typeof seeds === "function" ? seeds() : seeds);
129
+ const simple = (tag, fields, metas, seeds0) => {
130
+ const seeds = seedsFirst(seeds0, fields);
114
131
  const { buf, len, put, finish } = this.byteBuffer("tok", 128, "TS_ERR_INSTRUCTION_DATA", "token instruction");
115
132
  const t = this.tmp("tag");
116
133
  this.line(`uint8_t ${t} = ${tag};`);
@@ -118,7 +135,7 @@ export class TokenEmitter extends CreateEmitter {
118
135
  for (const f of fields)
119
136
  f(put);
120
137
  finish(node);
121
- this.cpi(p, metas.map(([acc, w, sg]) => [acc.c, w, sg]), buf, len, seeds);
138
+ this.cpi(p, metas.map(([acc, w, sg]) => [acc.c, w, sg]), buf, len, seedsNow(seeds));
122
139
  };
123
140
  const value = (n, t) => (put) => this.serialize(this.expect(this.expr(n, t), t, n), n, put);
124
141
  const optKey = { kind: "option", inner: PUBKEY };
@@ -151,7 +168,8 @@ export class TokenEmitter extends CreateEmitter {
151
168
  };
152
169
  const none = { name: "NULL", count: 0 };
153
170
  // The Token Group interface (spl-token-group-interface), which Token-2022 implements: 8-byte discriminators.
154
- const grouped = (disc, fields, metas, seeds) => {
171
+ const grouped = (disc, fields, metas, seeds0) => {
172
+ const seeds = seedsFirst(seeds0, fields);
155
173
  const { buf, len, put, finish } = this.byteBuffer("grp", 96, "TS_ERR_INSTRUCTION_DATA", "token group instruction");
156
174
  const d = this.tmp("disc");
157
175
  this.line(`static const uint8_t ${d}[8] = {${disc.join(", ")}};`);
@@ -159,7 +177,7 @@ export class TokenEmitter extends CreateEmitter {
159
177
  for (const f of fields)
160
178
  f(put);
161
179
  finish(node);
162
- this.cpi(p, metas.map(([acc, w, sg]) => [acc.c, w, sg]), buf, len, seeds);
180
+ this.cpi(p, metas.map(([acc, w, sg]) => [acc.c, w, sg]), buf, len, seedsNow(seeds));
163
181
  };
164
182
  switch (method) {
165
183
  case "initializeTokenGroup": {
@@ -173,7 +191,7 @@ export class TokenEmitter extends CreateEmitter {
173
191
  [group, true, false],
174
192
  [mint, false, false],
175
193
  [auth, false, true],
176
- ], this.signerSeeds(a[5], auth, a[2]));
194
+ ], () => this.signerSeeds(a[5], auth, a[2]));
177
195
  return undefined;
178
196
  }
179
197
  case "initializeGroupMember": {
@@ -203,7 +221,7 @@ export class TokenEmitter extends CreateEmitter {
203
221
  grouped([108, 37, 171, 143, 248, 30, 18, 110], [value(a[2], U64)], [
204
222
  [group, true, false],
205
223
  [auth, false, true],
206
- ], this.signerSeeds(a[3], auth, a[1]));
224
+ ], () => this.signerSeeds(a[3], auth, a[1]));
207
225
  return undefined;
208
226
  }
209
227
  case "updateGroupAuthority": {
@@ -215,7 +233,7 @@ export class TokenEmitter extends CreateEmitter {
215
233
  grouped([161, 105, 88, 1, 237, 221, 216, 203], [nonZeroKey(a[2])], [
216
234
  [group, true, false],
217
235
  [auth, false, true],
218
- ], this.signerSeeds(a[3], auth, a[1]));
236
+ ], () => this.signerSeeds(a[3], auth, a[1]));
219
237
  return undefined;
220
238
  }
221
239
  case "initializeTransferFeeConfig": {
@@ -294,7 +312,7 @@ export class TokenEmitter extends CreateEmitter {
294
312
  simple(28, [byte(1), (put) => put(`&${st}`, "1", 1)], [
295
313
  [mint, true, false],
296
314
  [auth, false, true],
297
- ], this.signerSeeds(a[3], auth, a[1]));
315
+ ], () => this.signerSeeds(a[3], auth, a[1]));
298
316
  return undefined;
299
317
  }
300
318
  case "enableRequiredMemoTransfers":
@@ -307,7 +325,7 @@ export class TokenEmitter extends CreateEmitter {
307
325
  simple(30, [byte(method === "enableRequiredMemoTransfers" ? 0 : 1)], [
308
326
  [acct, true, false],
309
327
  [owner, false, true],
310
- ], this.signerSeeds(a[2], owner, a[1]));
328
+ ], () => this.signerSeeds(a[2], owner, a[1]));
311
329
  return undefined;
312
330
  }
313
331
  case "updateTransferHook": {
@@ -319,7 +337,7 @@ export class TokenEmitter extends CreateEmitter {
319
337
  simple(36, [byte(1), nonZeroKey(a[2])], [
320
338
  [mint, true, false],
321
339
  [auth, false, true],
322
- ], this.signerSeeds(a[3], auth, a[1]));
340
+ ], () => this.signerSeeds(a[3], auth, a[1]));
323
341
  return undefined;
324
342
  }
325
343
  case "updateInterestRate": {
@@ -331,7 +349,7 @@ export class TokenEmitter extends CreateEmitter {
331
349
  simple(33, [byte(1), value(a[2], I16)], [
332
350
  [mint, true, false],
333
351
  [auth, false, true],
334
- ], this.signerSeeds(a[3], auth, a[1]));
352
+ ], () => this.signerSeeds(a[3], auth, a[1]));
335
353
  return undefined;
336
354
  }
337
355
  case "transferCheckedWithFee": {
@@ -353,7 +371,7 @@ export class TokenEmitter extends CreateEmitter {
353
371
  [mint, false, false],
354
372
  [to, true, false],
355
373
  [auth, false, true],
356
- ], this.signerSeeds(a[6], auth, a[3]));
374
+ ], () => this.signerSeeds(a[6], auth, a[3]));
357
375
  return undefined;
358
376
  }
359
377
  case "harvestWithheldTokensToMint": {
@@ -383,7 +401,7 @@ export class TokenEmitter extends CreateEmitter {
383
401
  [mint, true, false],
384
402
  [dest, true, false],
385
403
  [auth, false, true],
386
- ], this.signerSeeds(a[3], auth, a[2]));
404
+ ], () => this.signerSeeds(a[3], auth, a[2]));
387
405
  return undefined;
388
406
  }
389
407
  case "setTransferFee": {
@@ -400,7 +418,7 @@ export class TokenEmitter extends CreateEmitter {
400
418
  simple(26, [byte(5), bps, value(a[3], U64)], [
401
419
  [mint, true, false],
402
420
  [auth, false, true],
403
- ], this.signerSeeds(a[4], auth, a[1]));
421
+ ], () => this.signerSeeds(a[4], auth, a[1]));
404
422
  return undefined;
405
423
  }
406
424
  case "updateMetadataField":
@@ -445,7 +463,9 @@ export class TokenEmitter extends CreateEmitter {
445
463
  this.serialize(this.expect(this.expr(a[3], STRING), STRING, a[3]), a[3], put);
446
464
  }
447
465
  else if (method === "removeMetadataKey") {
448
- const key = this.expect(this.expr(a[2], STRING), STRING, a[2]);
466
+ // Written after `idempotent` is read: a view of account text is copied first when that runs code.
467
+ const key0 = this.expect(this.expr(a[2], STRING), STRING, a[2]);
468
+ const key = this.runsCode(a[3], true) ? this.ownedString(key0) : key0;
449
469
  const idem = this.expect(this.expr(a[3], BOOL), BOOL, a[3]);
450
470
  const t = this.tmp("idem");
451
471
  this.line(`uint8_t ${t} = (${idem.c}) ? 1 : 0;`);
@@ -475,7 +495,7 @@ export class TokenEmitter extends CreateEmitter {
475
495
  const src = want(a[0], "token", true, "the source");
476
496
  const delegate = this.cpiAccount(a[1], "the delegate");
477
497
  const owner = this.cpiAccount(a[2], "the owner");
478
- const s = this.signerSeeds(a[4], owner, a[2]);
498
+ const s = () => this.signerSeeds(a[4], owner, a[2]);
479
499
  const amt = value(a[3], U64);
480
500
  simple(4, [amt], [
481
501
  [src, true, false],
@@ -491,7 +511,7 @@ export class TokenEmitter extends CreateEmitter {
491
511
  const mint = want(a[1], "mint", false, "the mint");
492
512
  const delegate = this.cpiAccount(a[2], "the delegate");
493
513
  const owner = this.cpiAccount(a[3], "the owner");
494
- const s = this.signerSeeds(a[5], owner, a[3]);
514
+ const s = () => this.signerSeeds(a[5], owner, a[3]);
495
515
  simple(13, [value(a[4], U64), decimals(mint)], [
496
516
  [src, true, false],
497
517
  [mint, false, false],
@@ -505,7 +525,7 @@ export class TokenEmitter extends CreateEmitter {
505
525
  const mint = want(a[0], "mint", true, "the mint");
506
526
  const to = want(a[1], "token", true, "the destination");
507
527
  const auth = this.cpiAccount(a[2], "the mint authority");
508
- const s = this.signerSeeds(a[4], auth, a[2]);
528
+ const s = () => this.signerSeeds(a[4], auth, a[2]);
509
529
  simple(14, [value(a[3], U64), decimals(mint)], [
510
530
  [mint, true, false],
511
531
  [to, true, false],
@@ -518,7 +538,7 @@ export class TokenEmitter extends CreateEmitter {
518
538
  const from = want(a[0], "token", true, "the burned account");
519
539
  const mint = want(a[1], "mint", true, "the mint");
520
540
  const auth = this.cpiAccount(a[2], "the authority");
521
- const s = this.signerSeeds(a[4], auth, a[2]);
541
+ const s = () => this.signerSeeds(a[4], auth, a[2]);
522
542
  simple(15, [value(a[3], U64), decimals(mint)], [
523
543
  [from, true, false],
524
544
  [mint, true, false],
@@ -533,7 +553,7 @@ export class TokenEmitter extends CreateEmitter {
533
553
  simple(5, [], [
534
554
  [src, true, false],
535
555
  [owner, false, true],
536
- ], this.signerSeeds(a[2], owner, a[1]));
556
+ ], () => this.signerSeeds(a[2], owner, a[1]));
537
557
  return undefined;
538
558
  }
539
559
  case "setAuthority": {
@@ -541,7 +561,7 @@ export class TokenEmitter extends CreateEmitter {
541
561
  const target = anyAcct(a[0], "the mint or token account", true);
542
562
  const current = this.cpiAccount(a[1], "the current authority");
543
563
  this.model.options.set("pubkey", PUBKEY);
544
- const s = this.signerSeeds(a[4], current, a[1]);
564
+ const s = () => this.signerSeeds(a[4], current, a[1]);
545
565
  simple(6, [value(a[2], U8), value(a[3], optKey)], [
546
566
  [target, true, false],
547
567
  [current, false, true],
@@ -558,7 +578,7 @@ export class TokenEmitter extends CreateEmitter {
558
578
  [acct, true, false],
559
579
  [mint, false, false],
560
580
  [auth, false, true],
561
- ], this.signerSeeds(a[3], auth, a[2]));
581
+ ], () => this.signerSeeds(a[3], auth, a[2]));
562
582
  return undefined;
563
583
  }
564
584
  case "syncNative": {
@@ -668,7 +688,10 @@ export class TokenEmitter extends CreateEmitter {
668
688
  this.fail(n, `pass ${what} as an account, or named(account, address) to name its address with the slot's account`);
669
689
  return acct(i, what);
670
690
  };
671
- const send = (tag, fields, metas, seeds) => {
691
+ // Seeds given as a function: lowered after the fields when an argument runs code, as JS evaluates them (see tokenOp).
692
+ const runs = (n) => this.runsCode(n, true);
693
+ const send = (tag, fields, metas, seeds0) => {
694
+ let seeds = typeof seeds0 === "function" && !(fields.length && a.some(runs)) ? seeds0() : seeds0;
672
695
  const { buf, len, put, finish } = this.byteBuffer("stk", 116, "TS_ERR_INSTRUCTION_DATA", "stake instruction");
673
696
  const t = this.tmp("tag");
674
697
  this.line(`uint32_t ${t} = ${tag};`);
@@ -676,6 +699,8 @@ export class TokenEmitter extends CreateEmitter {
676
699
  for (const f of fields)
677
700
  f(put);
678
701
  finish(node);
702
+ if (typeof seeds === "function")
703
+ seeds = seeds();
679
704
  if (metas.some(([x]) => x.named)) {
680
705
  // Addresses named with the slot's account: the account infos are the CPI's accounts, as passed (ts_cpi_named).
681
706
  const m = this.tmp("metas");
@@ -743,7 +768,7 @@ export class TokenEmitter extends CreateEmitter {
743
768
  [sysvar(1, "the Clock sysvar"), false, false],
744
769
  [auth, false, true],
745
770
  ...(opt.custodian ? [custodian(opt.custodian, opt.seeds)] : []),
746
- ], this.signerSeeds(opt.seeds, auth, a[2]));
771
+ ], () => this.signerSeeds(opt.seeds, auth, a[2]));
747
772
  return undefined;
748
773
  }
749
774
  case "delegate": {
@@ -756,7 +781,7 @@ export class TokenEmitter extends CreateEmitter {
756
781
  [sysvar(3, "the StakeHistory sysvar"), false, false],
757
782
  [sysvar(4, "the stake config account"), false, false],
758
783
  [staker, false, true],
759
- ], this.signerSeeds(a[6], staker, a[5]));
784
+ ], () => this.signerSeeds(a[6], staker, a[5]));
760
785
  return undefined;
761
786
  }
762
787
  case "split": {
@@ -766,7 +791,7 @@ export class TokenEmitter extends CreateEmitter {
766
791
  [acct(0, "the stake account", true), true, false],
767
792
  [acct(1, "the split stake account", true), true, false],
768
793
  [auth, false, true],
769
- ], this.signerSeeds(a[4], auth, a[2]));
794
+ ], () => this.signerSeeds(a[4], auth, a[2]));
770
795
  return undefined;
771
796
  }
772
797
  case "deactivate": {
@@ -776,7 +801,7 @@ export class TokenEmitter extends CreateEmitter {
776
801
  [acct(0, "the stake account", true), true, false],
777
802
  [sysvar(1, "the Clock sysvar"), false, false],
778
803
  [staker, false, true],
779
- ], this.signerSeeds(a[3], staker, a[2]));
804
+ ], () => this.signerSeeds(a[3], staker, a[2]));
780
805
  return undefined;
781
806
  }
782
807
  case "withdraw": {
@@ -794,7 +819,7 @@ export class TokenEmitter extends CreateEmitter {
794
819
  [sysvar(3, "the StakeHistory sysvar"), false, false],
795
820
  [withdrawer, false, true],
796
821
  ...(opt.custodian ? [custodian(opt.custodian, opt.seeds)] : []),
797
- ], this.signerSeeds(opt.seeds, withdrawer, a[4]));
822
+ ], () => this.signerSeeds(opt.seeds, withdrawer, a[4]));
798
823
  return undefined;
799
824
  }
800
825
  case "merge": {
@@ -806,7 +831,7 @@ export class TokenEmitter extends CreateEmitter {
806
831
  [sysvar(2, "the Clock sysvar"), false, false],
807
832
  [sysvar(3, "the StakeHistory sysvar"), false, false],
808
833
  [staker, false, true],
809
- ], this.signerSeeds(a[5], staker, a[4]));
834
+ ], () => this.signerSeeds(a[5], staker, a[4]));
810
835
  return undefined;
811
836
  }
812
837
  case "getMinimumDelegation": {
@@ -5,7 +5,7 @@ import { type Sbpf } from "./toolchain.js";
5
5
  import type { ProgramModel } from "./model.js";
6
6
  export { CompileError, formatDiagnostic, type Diagnostic } from "./diagnostics.js";
7
7
  export type { ProgramModel } from "./model.js";
8
- export { SBPF_VERSIONS, type Sbpf } from "./toolchain.js";
8
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN, type Sbpf } from "./toolchain.js";
9
9
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
10
10
  export declare function typescriptHint(d: ts.Diagnostic): string | undefined;
11
11
  export interface Generated {
@@ -20,7 +20,15 @@ export declare function generate(entry: string, opts?: EmitOptions): Generated;
20
20
  export interface BuildManifest {
21
21
  program: string;
22
22
  compiler: string;
23
+ /** The first line of `clang --version`: the compiler of the generated C. */
23
24
  clang: string;
25
+ /** The platform-tools version (`v1.52`), when the SDK's layout tells it for sure (from 0.44.0). */
26
+ platformTools?: string;
27
+ /** The machine that built it: `process.platform` and `process.arch` (from 0.44.0). */
28
+ host?: {
29
+ os: string;
30
+ arch: string;
31
+ };
24
32
  /** The TypeScript version that type-checked the sources (pinned: it decides what compiles). */
25
33
  typescript: string;
26
34
  sbpf: Sbpf;
@@ -45,6 +53,12 @@ export declare function build(entry: string, outDir: string, programAddress: str
45
53
  }): BuildResult;
46
54
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
47
55
  export declare const COMPILER_VERSION: string;
56
+ /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
57
+ export declare function describeToolchain(m: Pick<BuildManifest, "clang" | "platformTools" | "host" | "compiler">): string;
58
+ /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
59
+ export declare function toolchainDifferences(a: Partial<BuildManifest>, b: Partial<BuildManifest>): string[];
60
+ /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
61
+ export declare function elfLength(elf: Buffer): number;
48
62
  /**
49
63
  * Whether `deployed` (a .so, e.g. from `solana program dump`) is exactly what `entry` builds to. Program accounts
50
64
  * keep the ELF zero-padded to their allocation, so trailing zeros are ignored.
@@ -7,10 +7,10 @@ import { analyze, LIB_PATH } from "./analyze.js";
7
7
  import { hintForTypeScript } from "./hints.js";
8
8
  import { emitProgram } from "./emit/index.js";
9
9
  import { buildIdl } from "./idl.js";
10
- import { buildSharedObject, toolchainVersion } from "./toolchain.js";
10
+ import { buildSharedObject, checkToolchain, shortClang, TESTED_TOOLCHAIN } from "./toolchain.js";
11
11
  import { RUNTIME_DIR } from "./toolchain.js";
12
12
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
13
- export { SBPF_VERSIONS } from "./toolchain.js";
13
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN } from "./toolchain.js";
14
14
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
15
15
  export function typescriptHint(d) {
16
16
  return hintForTypeScript(d, ts.flattenDiagnosticMessageText(d.messageText, "\n"), LIB_PATH);
@@ -33,6 +33,8 @@ export function build(entry, outDir, programAddress, opts = {}) {
33
33
  const soPath = `${base}.so`;
34
34
  const idlPath = `${base}.json`;
35
35
  writeFileSync(cPath, gen.c);
36
+ // Before clang runs: an untested toolchain is a warning (once), or an error in strict mode.
37
+ const toolchain = checkToolchain();
36
38
  buildSharedObject(cPath, soPath, opts.sbpf);
37
39
  const idl = buildIdl(gen.model, programAddress);
38
40
  writeFileSync(idlPath, JSON.stringify(idl, null, 2) + "\n");
@@ -44,7 +46,9 @@ export function build(entry, outDir, programAddress, opts = {}) {
44
46
  const manifest = {
45
47
  program: gen.model.name,
46
48
  compiler: COMPILER_VERSION,
47
- clang: toolchainVersion(),
49
+ clang: toolchain.clang,
50
+ ...(toolchain.platformTools ? { platformTools: toolchain.platformTools } : {}),
51
+ host: { os: process.platform, arch: process.arch },
48
52
  typescript: ts.version,
49
53
  sbpf: opts.sbpf ?? "v0",
50
54
  profile: !!opts.profile,
@@ -57,6 +61,39 @@ export function build(entry, outDir, programAddress, opts = {}) {
57
61
  }
58
62
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
59
63
  export const COMPILER_VERSION = createRequire(import.meta.url)("../../package.json").version;
64
+ /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
65
+ export function describeToolchain(m) {
66
+ return [
67
+ shortClang(m.clang),
68
+ `platform-tools ${m.platformTools ?? "unknown"}`,
69
+ m.host ? `${m.host.os}-${m.host.arch}` : "host unknown",
70
+ `TypeSOL ${m.compiler}`,
71
+ ...(m.clang === TESTED_TOOLCHAIN.clang ? ["the tested toolchain"] : []),
72
+ ].join(", ");
73
+ }
74
+ /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
75
+ export function toolchainDifferences(a, b) {
76
+ const out = [];
77
+ if (a.compiler !== b.compiler)
78
+ out.push("TypeSOL version");
79
+ if (a.clang !== b.clang)
80
+ out.push("clang");
81
+ if (a.platformTools && b.platformTools && a.platformTools !== b.platformTools)
82
+ out.push("platform-tools");
83
+ if (a.typescript !== b.typescript)
84
+ out.push("TypeScript");
85
+ if (a.sbpf !== b.sbpf)
86
+ out.push("SBPF version");
87
+ // The host is recorded, not compared: one clang version is meant to give the same bytes on every host.
88
+ return out;
89
+ }
90
+ /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
91
+ export function elfLength(elf) {
92
+ if (elf.length < 0x40 || elf.readUInt32BE(0) !== 0x7f454c46)
93
+ return elf.length;
94
+ const end = Number(elf.readBigUInt64LE(0x28)) + elf.readUInt16LE(0x3a) * elf.readUInt16LE(0x3c);
95
+ return end > 0 && end <= elf.length ? end : elf.length;
96
+ }
60
97
  /**
61
98
  * Whether `deployed` (a .so, e.g. from `solana program dump`) is exactly what `entry` builds to. Program accounts
62
99
  * keep the ELF zero-padded to their allocation, so trailing zeros are ignored.